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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521
  1. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.JitsiMeetJS=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. var RTC = require("./modules/RTC/RTC");
  3. var XMPPEvents = require("./service/xmpp/XMPPEvents");
  4. var StreamEventTypes = require("./service/RTC/StreamEventTypes");
  5. var RTCEvents = require("./service/RTC/RTCEvents");
  6. var EventEmitter = require("events");
  7. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  8. var JitsiParticipant = require("./JitsiParticipant");
  9. /**
  10. * Creates a JitsiConference object with the given name and properties.
  11. * Note: this constructor is not a part of the public API (objects should be
  12. * created using JitsiConnection.createConference).
  13. * @param options.config properties / settings related to the conference that will be created.
  14. * @param options.name the name of the conference
  15. * @param options.connection the JitsiConnection object for this JitsiConference.
  16. * @constructor
  17. */
  18. function JitsiConference(options) {
  19. this.options = options;
  20. this.connection = this.options.connection;
  21. this.xmpp = this.connection.xmpp;
  22. this.eventEmitter = new EventEmitter();
  23. this.room = this.xmpp.createRoom(this.options.name, null, null, this.options.config);
  24. this.rtc = new RTC(this.room, options);
  25. setupListeners(this);
  26. this.participants = {};
  27. }
  28. /**
  29. * Joins the conference.
  30. * @param password {string} the password
  31. */
  32. JitsiConference.prototype.join = function (password) {
  33. this.room.join(password);
  34. }
  35. /**
  36. * Leaves the conference.
  37. */
  38. JitsiConference.prototype.leave = function () {
  39. this.xmpp.leaveRoom(this.room.roomjid);
  40. this.room = null;
  41. }
  42. /**
  43. * Creates the media tracks and returns them trough the callback.
  44. * @param options Object with properties / settings specifying the tracks which should be created.
  45. * should be created or some additional configurations about resolution for example.
  46. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>} A promise that returns an array of created JitsiTracks if resolved,
  47. * or a JitsiConferenceError if rejected.
  48. */
  49. JitsiConference.prototype.createLocalTracks = function (options) {
  50. return this.rtc.obtainAudioAndVideoPermissions(options || {});
  51. }
  52. /**
  53. * Returns the local tracks.
  54. */
  55. JitsiConference.prototype.getLocalTracks = function () {
  56. return this.rtc.localStreams;
  57. };
  58. /**
  59. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  60. * in JitsiConferenceEvents.
  61. * @param eventId the event ID.
  62. * @param handler handler for the event.
  63. *
  64. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  65. */
  66. JitsiConference.prototype.on = function (eventId, handler) {
  67. this.eventEmitter.on(eventId, handler);
  68. }
  69. /**
  70. * Removes event listener
  71. * @param eventId the event ID.
  72. * @param [handler] optional, the specific handler to unbind
  73. *
  74. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  75. */
  76. JitsiConference.prototype.off = function (eventId, handler) {
  77. this.eventEmitter.removeListener(eventId, listener);
  78. }
  79. // Common aliases for event emitter
  80. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on
  81. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off
  82. /**
  83. * Receives notifications from another participants for commands / custom events(send by sendPresenceCommand method).
  84. * @param command {String} the name of the command
  85. * @param handler {Function} handler for the command
  86. */
  87. JitsiConference.prototype.addCommandListener = function (command, handler) {
  88. this.room.addPresenceListener(command, handler);
  89. }
  90. /**
  91. * Removes command listener
  92. * @param command {String} the name of the command
  93. */
  94. JitsiConference.prototype.removeCommandListener = function (command) {
  95. this.room.removePresenceListener(command);
  96. }
  97. /**
  98. * Sends text message to the other participants in the conference
  99. * @param message the text message.
  100. */
  101. JitsiConference.prototype.sendTextMessage = function (message) {
  102. this.room.sendMessage(message);
  103. }
  104. /**
  105. * Send presence command.
  106. * @param name the name of the command.
  107. * @param values Object with keys and values that will be send.
  108. **/
  109. JitsiConference.prototype.sendCommand = function (name, values) {
  110. this.room.addToPresence(name, values);
  111. this.room.sendPresence();
  112. }
  113. /**
  114. * Send presence command one time.
  115. * @param name the name of the command.
  116. * @param values Object with keys and values that will be send.
  117. **/
  118. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  119. this.sendCommand(name, values);
  120. this.removeCommand(name);
  121. }
  122. /**
  123. * Send presence command.
  124. * @param name the name of the command.
  125. * @param values Object with keys and values that will be send.
  126. * @param persistent if false the command will be sent only one time
  127. **/
  128. JitsiConference.prototype.removeCommand = function (name) {
  129. this.room.removeFromPresence(name);
  130. }
  131. /**
  132. * Sets the display name for this conference.
  133. * @param name the display name to set
  134. */
  135. JitsiConference.prototype.setDisplayName = function(name) {
  136. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  137. }
  138. /**
  139. * Elects the participant with the given id to be the selected participant or the speaker.
  140. * @param id the identifier of the participant
  141. */
  142. JitsiConference.prototype.selectParticipant = function(participantId) {
  143. this.rtc.selectedEndpoint(participantId);
  144. }
  145. /**
  146. *
  147. * @param id the identifier of the participant
  148. */
  149. JitsiConference.prototype.pinParticipant = function(participantId) {
  150. this.rtc.pinEndpoint(participantId);
  151. }
  152. /**
  153. * Returns the list of participants for this conference.
  154. * @return Object a list of participant identifiers containing all conference participants.
  155. */
  156. JitsiConference.prototype.getParticipants = function() {
  157. return this.participants;
  158. }
  159. /**
  160. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  161. * null if there isn't one).
  162. * @param id the id of the participant.
  163. */
  164. JitsiConference.prototype.getParticipantById = function(id) {
  165. return this.participants[id];
  166. }
  167. JitsiConference.prototype.onMemberJoined = function (jid, email, nick) {
  168. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, Strophe.getResourceFromJid(jid));
  169. // this.participants[jid] = new JitsiParticipant();
  170. }
  171. /**
  172. * Setups the listeners needed for the conference.
  173. * @param conference the conference
  174. */
  175. function setupListeners(conference) {
  176. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING,
  177. conference.rtc.onIncommingCall.bind(conference.rtc));
  178. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  179. conference.rtc.createRemoteStream.bind(conference.rtc));
  180. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, function (stream) {
  181. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, stream);
  182. });
  183. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_REMOTE_ENDED, function (stream) {
  184. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, stream);
  185. });
  186. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, function (stream) {
  187. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, stream);
  188. });
  189. conference.rtc.addListener(StreamEventTypes.TRACK_MUTE_CHANGED, function (track) {
  190. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  191. });
  192. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  193. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  194. });
  195. // FIXME
  196. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  197. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  198. // });
  199. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  200. conference.eventEmitter.emit(JitsiConferenceEvents.ACTIVE_SPEAKER_CHANGED, id);
  201. });
  202. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  203. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  204. });
  205. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  206. function (lastNEndpoints, endpointsEnteringLastN) {
  207. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  208. lastNEndpoints, endpointsEnteringLastN);
  209. });
  210. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  211. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT,function (jid) {
  212. conference.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, Strophe.getResourceFromJid(jid));
  213. });
  214. }
  215. module.exports = JitsiConference;
  216. },{"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./modules/RTC/RTC":13,"./service/RTC/RTCEvents":71,"./service/RTC/StreamEventTypes":73,"./service/xmpp/XMPPEvents":76,"events":77}],2:[function(require,module,exports){
  217. /**
  218. * Enumeration with the errors for the conference.
  219. * @type {{string: string}}
  220. */
  221. var JitsiConferenceErrors = {
  222. /**
  223. * Indicates that a password is required in order to join the conference.
  224. */
  225. PASSWORD_REQUIRED: "conference.passwordRequired",
  226. /**
  227. * Indicates that a connection error occurred when trying to join a conference.
  228. */
  229. CONNECTION_ERROR: "conference.connectionError",
  230. /**
  231. * Indicates that there is no available videobridge.
  232. */
  233. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  234. /**
  235. * Many more errors TBD here.
  236. */
  237. };
  238. module.exports = JitsiConferenceErrors;
  239. },{}],3:[function(require,module,exports){
  240. /**
  241. * Enumeration with the events for the conference.
  242. * @type {{string: string}}
  243. */
  244. var JitsiConferenceEvents = {
  245. /**
  246. * A new media track was added to the conference.
  247. */
  248. TRACK_ADDED: "conference.trackAdded",
  249. /**
  250. * The media track was removed to the conference.
  251. */
  252. TRACK_REMOVED: "conference.trackRemoved",
  253. /**
  254. * The active speaker was changed.
  255. */
  256. ACTIVE_SPEAKER_CHANGED: "conference.activeSpeaker",
  257. /**
  258. * A new user joinned the conference.
  259. */
  260. USER_JOINED: "conference.userJoined",
  261. /**
  262. * A user has left the conference.
  263. */
  264. USER_LEFT: "conference.userLeft",
  265. /**
  266. * New text message was received.
  267. */
  268. MESSAGE_RECEIVED: "conference.messageReceived",
  269. /**
  270. * A user has changed it display name
  271. */
  272. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  273. /**
  274. * A participant avatar has changed.
  275. */
  276. AVATAR_CHANGED: "conference.avatarChanged",
  277. /**
  278. * New connection statistics are received.
  279. */
  280. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  281. /**
  282. * The Last N set is changed.
  283. */
  284. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  285. /**
  286. * You are included / excluded in somebody's last N set
  287. */
  288. IN_LAST_N_CHANGED: "conference.lastNEndpointsChanged",
  289. /**
  290. * A media track mute status was changed.
  291. */
  292. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  293. /**
  294. * Audio levels of a media track was changed.
  295. */
  296. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  297. /**
  298. * Indicates that the connection to the conference has been interrupted for some reason.
  299. */
  300. CONNECTION_INTERRUPTED: "conference.connecionInterrupted",
  301. /**
  302. * Indicates that the connection to the conference has been restored.
  303. */
  304. CONNECTION_RESTORED: "conference.connecionRestored",
  305. /**
  306. * Indicates that conference has been joined.
  307. */
  308. CONFERENCE_JOINED: "conference.joined",
  309. /**
  310. * Indicates that conference has been left.
  311. */
  312. CONFERENCE_LEFT: "conference.left"
  313. };
  314. module.exports = JitsiConferenceEvents;
  315. },{}],4:[function(require,module,exports){
  316. var JitsiConference = require("./JitsiConference");
  317. var XMPP = require("./modules/xmpp/xmpp");
  318. /**
  319. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  320. * JitsiConference interface.
  321. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  322. * @param token secret generated by the provider of Jitsi Meet video conferencing services.
  323. * The token will be send to the provider from the Jitsi Meet server deployment for authorization of the current client.
  324. * @param options Object with properties / settings related to connection with the server.
  325. * @constructor
  326. */
  327. function JitsiConnection(appID, token, options) {
  328. this.appID = appID;
  329. this.token = token;
  330. this.options = options;
  331. this.xmpp = new XMPP(options);
  332. this.conferences = {};
  333. }
  334. /**
  335. * Connect the client with the server.
  336. * @param options {object} connecting options (for example authentications parameters).
  337. */
  338. JitsiConnection.prototype.connect = function (options) {
  339. if(!options)
  340. options = {};
  341. this.xmpp.connect(options.id, options.password);
  342. }
  343. /**
  344. * Disconnect the client from the server.
  345. */
  346. JitsiConnection.prototype.disconnect = function () {
  347. this.xmpp.disconnect();
  348. }
  349. /**
  350. * This method allows renewal of the tokens if they are expiring.
  351. * @param token the new token.
  352. */
  353. JitsiConnection.prototype.setToken = function (token) {
  354. this.token = token;
  355. }
  356. /**
  357. * Creates and joins new conference.
  358. * @param name the name of the conference; if null - a generated name will be provided from the api
  359. * @param options Object with properties / settings related to the conference that will be created.
  360. * @returns {JitsiConference} returns the new conference object.
  361. */
  362. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  363. this.conferences[name] = new JitsiConference({name: name, config: options, connection: this});
  364. return this.conferences[name];
  365. }
  366. /**
  367. * Subscribes the passed listener to the event.
  368. * @param event {JitsiConnectionEvents} the connection event.
  369. * @param listener {Function} the function that will receive the event
  370. */
  371. JitsiConnection.prototype.addEventListener = function (event, listener) {
  372. this.xmpp.addListener(event, listener);
  373. }
  374. /**
  375. * Unsubscribes the passed handler.
  376. * @param event {JitsiConnectionEvents} the connection event.
  377. * @param listener {Function} the function that will receive the event
  378. */
  379. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  380. this.xmpp.removeListener(event, listener);
  381. }
  382. module.exports = JitsiConnection;
  383. },{"./JitsiConference":1,"./modules/xmpp/xmpp":33}],5:[function(require,module,exports){
  384. /**
  385. * Enumeration with the errors for the connection.
  386. * @type {{string: string}}
  387. */
  388. var JitsiConnectionErrors = {
  389. /**
  390. * Indicates that a password is required in order to join the conference.
  391. */
  392. PASSWORD_REQUIRED: "connection.passwordRequired",
  393. /**
  394. * Indicates that a connection error occurred when trying to join a conference.
  395. */
  396. CONNECTION_ERROR: "connection.connectionError",
  397. /**
  398. * Not specified errors.
  399. */
  400. OTHER_ERROR: "connection.otherError"
  401. };
  402. module.exports = JitsiConnectionErrors;
  403. },{}],6:[function(require,module,exports){
  404. /**
  405. * Enumeration with the events for the connection.
  406. * @type {{string: string}}
  407. */
  408. var JitsiConnnectionEvents = {
  409. /**
  410. * Indicates that the connection has been failed for some reason.
  411. */
  412. CONNECTION_FAILED: "connection.connecionFailed",
  413. /**
  414. * Indicates that the connection has been established.
  415. */
  416. CONNECTION_ESTABLISHED: "connection.connecionEstablished",
  417. /**
  418. * Indicates that the connection has been disconnected.
  419. */
  420. CONNECTION_DISCONNECTED: "connection.connecionDisconnected",
  421. /**
  422. * Indicates that the perfomed action cannot be executed because the
  423. * connection is not in the correct state(connected, disconnected, etc.)
  424. */
  425. WRONG_STATE: "connection.wrongState"
  426. };
  427. module.exports = JitsiConnnectionEvents;
  428. },{}],7:[function(require,module,exports){
  429. var JitsiConnection = require("./JitsiConnection");
  430. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  431. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  432. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  433. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  434. /**
  435. * Namespace for the interface of Jitsi Meet Library.
  436. */
  437. var LibJitsiMeet = {
  438. JitsiConnection: JitsiConnection,
  439. events: {
  440. conference: JitsiConferenceEvents,
  441. connection: JitsiConnectionEvents
  442. },
  443. errors: {
  444. conference: JitsiConferenceErrors,
  445. connection: JitsiConnectionErrors
  446. },
  447. init: function (options) {
  448. require("./modules/RTC/RTC").init(options || {});
  449. }
  450. }
  451. //Setups the promise object.
  452. window.Promise = window.Promise || require("es6-promise").polyfill();
  453. module.exports = LibJitsiMeet;
  454. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./modules/RTC/RTC":13,"es6-promise":35}],8:[function(require,module,exports){
  455. /**
  456. * Represents a participant in (a member of) a conference.
  457. */
  458. function JitsiParticipant(id, conference, displayName){
  459. this._id = id;
  460. this._conference = conference;
  461. this._displayName = displayName;
  462. }
  463. /**
  464. * @returns {JitsiConference} The conference that this participant belongs to.
  465. */
  466. JitsiParticipant.prototype.getConference = function() {
  467. return this._conference;
  468. }
  469. /**
  470. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  471. */
  472. JitsiParticipant.prototype.getTracks = function() {
  473. }
  474. /**
  475. * @returns {String} The ID (i.e. JID) of this participant.
  476. */
  477. JitsiParticipant.prototype.getId = function() {
  478. return this._id;
  479. }
  480. /**
  481. * @returns {String} The human-readable display name of this participant.
  482. */
  483. JitsiParticipant.prototype.getDisplayName = function() {
  484. return this._displayName;
  485. }
  486. /**
  487. * @returns {Boolean} Whether this participant is a moderator or not.
  488. */
  489. JitsiParticipant.prototype.isModerator = function() {
  490. }
  491. // Gets a link to an etherpad instance advertised by the participant?
  492. //JitsiParticipant.prototype.getEtherpad = function() {
  493. //
  494. //}
  495. /*
  496. * @returns {Boolean} Whether this participant has muted their audio.
  497. */
  498. JitsiParticipant.prototype.isAudioMuted = function() {
  499. }
  500. /*
  501. * @returns {Boolean} Whether this participant has muted their video.
  502. */
  503. JitsiParticipant.prototype.isVideoMuted = function() {
  504. }
  505. /*
  506. * @returns {???} The latest statistics reported by this participant (i.e. info used to populate the GSM bars)
  507. * TODO: do we expose this or handle it internally?
  508. */
  509. JitsiParticipant.prototype.getLatestStats = function() {
  510. }
  511. /**
  512. * @returns {String} The role of this participant.
  513. */
  514. JitsiParticipant.prototype.getRole = function() {
  515. }
  516. /*
  517. * @returns {Boolean} Whether this participant is the conference focus (i.e. jicofo).
  518. */
  519. JitsiParticipant.prototype.isFocus = function() {
  520. }
  521. /*
  522. * @returns {Boolean} Whether this participant is a conference recorder (i.e. jirecon).
  523. */
  524. JitsiParticipant.prototype.isRecorder = function() {
  525. }
  526. /*
  527. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  528. */
  529. JitsiParticipant.prototype.isSipGateway = function() {
  530. }
  531. /**
  532. * @returns {String} The ID for this participant's avatar.
  533. */
  534. JitsiParticipant.prototype.getAvatarId = function() {
  535. }
  536. /**
  537. * @returns {Boolean} Whether this participant is currently sharing their screen.
  538. */
  539. JitsiParticipant.prototype.isScreenSharing = function() {
  540. }
  541. /**
  542. * @returns {String} The user agent of this participant (i.e. browser userAgent string).
  543. */
  544. JitsiParticipant.prototype.getUserAgent = function() {
  545. }
  546. /**
  547. * Kicks the participant from the conference (requires certain privileges).
  548. */
  549. JitsiParticipant.prototype.kick = function() {
  550. }
  551. /**
  552. * Asks this participant to mute themselves.
  553. */
  554. JitsiParticipant.prototype.askToMute = function() {
  555. }
  556. module.exports = JitsiParticipant();
  557. },{}],9:[function(require,module,exports){
  558. /* global config, APP, Strophe */
  559. // cache datachannels to avoid garbage collection
  560. // https://code.google.com/p/chromium/issues/detail?id=405545
  561. var RTCEvents = require("../../service/RTC/RTCEvents");
  562. /**
  563. * Binds "ondatachannel" event listener to given PeerConnection instance.
  564. * @param peerConnection WebRTC peer connection instance.
  565. */
  566. function DataChannels(peerConnection, emitter) {
  567. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  568. this.eventEmitter = emitter;
  569. this._dataChannels = [];
  570. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  571. // Although it's not a requirement to open separate channels from both bridge
  572. // and peer as single channel can be used for sending and receiving data.
  573. // So either channel opened by the bridge or the one opened here is enough
  574. // for communication with the bridge.
  575. /*var dataChannelOptions =
  576. {
  577. reliable: true
  578. };
  579. var dataChannel
  580. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  581. // Can be used only when is in open state
  582. dataChannel.onopen = function ()
  583. {
  584. dataChannel.send("My channel !!!");
  585. };
  586. dataChannel.onmessage = function (event)
  587. {
  588. var msgData = event.data;
  589. console.info("Got My Data Channel Message:", msgData, dataChannel);
  590. };*/
  591. };
  592. /**
  593. * Callback triggered by PeerConnection when new data channel is opened
  594. * on the bridge.
  595. * @param event the event info object.
  596. */
  597. DataChannels.prototype.onDataChannel = function (event) {
  598. var dataChannel = event.channel;
  599. var self = this;
  600. dataChannel.onopen = function () {
  601. console.info("Data channel opened by the Videobridge!", dataChannel);
  602. // Code sample for sending string and/or binary data
  603. // Sends String message to the bridge
  604. //dataChannel.send("Hello bridge!");
  605. // Sends 12 bytes binary message to the bridge
  606. //dataChannel.send(new ArrayBuffer(12));
  607. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  608. };
  609. dataChannel.onerror = function (error) {
  610. console.error("Data Channel Error:", error, dataChannel);
  611. };
  612. dataChannel.onmessage = function (event) {
  613. var data = event.data;
  614. // JSON
  615. var obj;
  616. try {
  617. obj = JSON.parse(data);
  618. }
  619. catch (e) {
  620. console.error(
  621. "Failed to parse data channel message as JSON: ",
  622. data,
  623. dataChannel);
  624. }
  625. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  626. var colibriClass = obj.colibriClass;
  627. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  628. // Endpoint ID from the Videobridge.
  629. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  630. console.info(
  631. "Data channel new dominant speaker event: ",
  632. dominantSpeakerEndpoint);
  633. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  634. }
  635. else if ("InLastNChangeEvent" === colibriClass) {
  636. var oldValue = obj.oldValue;
  637. var newValue = obj.newValue;
  638. // Make sure that oldValue and newValue are of type boolean.
  639. var type;
  640. if ((type = typeof oldValue) !== 'boolean') {
  641. if (type === 'string') {
  642. oldValue = (oldValue == "true");
  643. } else {
  644. oldValue = new Boolean(oldValue).valueOf();
  645. }
  646. }
  647. if ((type = typeof newValue) !== 'boolean') {
  648. if (type === 'string') {
  649. newValue = (newValue == "true");
  650. } else {
  651. newValue = new Boolean(newValue).valueOf();
  652. }
  653. }
  654. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  655. }
  656. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  657. // The new/latest list of last-n endpoint IDs.
  658. var lastNEndpoints = obj.lastNEndpoints;
  659. // The list of endpoint IDs which are entering the list of
  660. // last-n at this time i.e. were not in the old list of last-n
  661. // endpoint IDs.
  662. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  663. console.log(
  664. "Data channel new last-n event: ",
  665. lastNEndpoints, endpointsEnteringLastN, obj);
  666. this.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  667. lastNEndpoints, endpointsEnteringLastN, obj);
  668. }
  669. else {
  670. console.debug("Data channel JSON-formatted message: ", obj);
  671. }
  672. }
  673. };
  674. dataChannel.onclose = function () {
  675. console.info("The Data Channel closed", dataChannel);
  676. var idx = self._dataChannels.indexOf(dataChannel);
  677. if (idx > -1)
  678. self._dataChannels = self._dataChannels.splice(idx, 1);
  679. };
  680. this._dataChannels.push(dataChannel);
  681. };
  682. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  683. console.log('selected endpoint changed: ', userResource);
  684. if (this._dataChannels && this._dataChannels.length != 0) {
  685. this._dataChannels.some(function (dataChannel) {
  686. if (dataChannel.readyState == 'open') {
  687. console.log('sending selected endpoint changed ' +
  688. 'notification to the bridge: ', userResource);
  689. dataChannel.send(JSON.stringify({
  690. 'colibriClass': 'SelectedEndpointChangedEvent',
  691. 'selectedEndpoint':
  692. (!userResource || userResource === null)?
  693. null : userResource
  694. }));
  695. return true;
  696. }
  697. });
  698. }
  699. }
  700. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  701. console.log('pinned endpoint changed: ', userResource);
  702. if (this._dataChannels && this._dataChannels.length != 0) {
  703. this._dataChannels.some(function (dataChannel) {
  704. if (dataChannel.readyState == 'open') {
  705. dataChannel.send(JSON.stringify({
  706. 'colibriClass': 'PinnedEndpointChangedEvent',
  707. 'pinnedEndpoint':
  708. (!userResource || userResource == null)?
  709. null : userResource
  710. }));
  711. return true;
  712. }
  713. });
  714. }
  715. }
  716. module.exports = DataChannels;
  717. },{"../../service/RTC/RTCEvents":71}],10:[function(require,module,exports){
  718. var JitsiTrack = require("./JitsiTrack");
  719. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  720. var RTC = require("./RTCUtils");
  721. var RTCBrowserType = require("./RTCBrowserType");
  722. /**
  723. * Represents a single media track (either audio or video).
  724. * @constructor
  725. */
  726. function JitsiLocalTrack(RTC, stream, eventEmitter, videoType, isGUMStream)
  727. {
  728. JitsiTrack.call(this, RTC, stream);
  729. this.eventEmitter = eventEmitter;
  730. this.videoType = videoType;
  731. this.isGUMStream = true;
  732. this.dontFireRemoveEvent = false;
  733. var self = this;
  734. if(isGUMStream === false)
  735. this.isGUMStream = isGUMStream;
  736. this.stream.onended = function () {
  737. if(!self.dontFireRemoveEvent)
  738. self.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, self);
  739. self.dontFireRemoveEvent = false;
  740. };
  741. }
  742. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  743. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  744. /**
  745. * Mutes / unmutes the track.
  746. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  747. */
  748. JitsiLocalTrack.prototype._setMute = function (mute) {
  749. var isAudio = this.type === JitsiTrack.AUDIO;
  750. this.dontFireRemoveEvent = false;
  751. if ((window.location.protocol != "https:" && this.isGUMStream) ||
  752. (isAudio && this.isGUMStream) || this.videoType === "screen" ||
  753. // FIXME FF does not support 'removeStream' method used to mute
  754. RTCBrowserType.isFirefox()) {
  755. var tracks = this._getTracks();
  756. for (var idx = 0; idx < tracks.length; idx++) {
  757. tracks[idx].enabled = !mute;
  758. }
  759. if(isAudio)
  760. this.rtc.room.setAudioMute(mute);
  761. else
  762. this.rtc.room.setVideoMute(mute);
  763. this.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  764. } else {
  765. if (mute) {
  766. this.dontFireRemoveEvent = true;
  767. this.rtc.room.removeStream(this.stream);
  768. this.stream.stop();
  769. if(isAudio)
  770. this.rtc.room.setAudioMute(mute);
  771. else
  772. this.rtc.room.setVideoMute(mute);
  773. this.stream = null;
  774. this.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  775. //FIXME: Maybe here we should set the SRC for the containers to something
  776. } else {
  777. var self = this;
  778. this.rtc.obtainAudioAndVideoPermissions(
  779. {devices: (isAudio ? ["audio"] : ["video"])}, true)
  780. .then(function (streams) {
  781. var stream = null;
  782. for(var i = 0; i < streams.length; i++) {
  783. stream = streams[i];
  784. if(stream.type === self.type) {
  785. self.stream = stream.stream;
  786. self.videoType = stream.videoType;
  787. self.isGUMStream = stream.isGUMStream;
  788. break;
  789. }
  790. }
  791. if(!stream)
  792. return;
  793. for(var i = 0; i < self.containers.length; i++)
  794. {
  795. RTC.attachMediaStream(self.containers[i], self.stream);
  796. }
  797. self.rtc.room.addStream(stream.stream,
  798. function () {
  799. if(isAudio)
  800. self.rtc.room.setAudioMute(mute);
  801. else
  802. self.rtc.room.setVideoMute(mute);
  803. self.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, self);
  804. });
  805. });
  806. }
  807. }
  808. }
  809. /**
  810. * Stops sending the media track. And removes it from the HTML.
  811. * NOTE: Works for local tracks only.
  812. */
  813. JitsiLocalTrack.prototype.stop = function () {
  814. if(!this.stream)
  815. return;
  816. this.rtc.room.removeStream(this.stream);
  817. this.stream.stop();
  818. this.detach();
  819. }
  820. /**
  821. * Starts sending the track.
  822. * NOTE: Works for local tracks only.
  823. */
  824. JitsiLocalTrack.prototype.start = function() {
  825. this.rtc.room.addStream(this.stream, function () {});
  826. }
  827. /**
  828. * Returns <tt>true</tt> - if the stream is muted
  829. * and <tt>false</tt> otherwise.
  830. * @returns {boolean} <tt>true</tt> - if the stream is muted
  831. * and <tt>false</tt> otherwise.
  832. */
  833. JitsiLocalTrack.prototype.isMuted = function () {
  834. if (!this.stream)
  835. return true;
  836. var tracks = [];
  837. var isAudio = this.type === JitsiTrack.AUDIO;
  838. if (isAudio) {
  839. tracks = this.stream.getAudioTracks();
  840. } else {
  841. if (this.stream.ended)
  842. return true;
  843. tracks = this.stream.getVideoTracks();
  844. }
  845. for (var idx = 0; idx < tracks.length; idx++) {
  846. if(tracks[idx].enabled)
  847. return false;
  848. }
  849. return true;
  850. };
  851. module.exports = JitsiLocalTrack;
  852. },{"../../service/RTC/StreamEventTypes":73,"./JitsiTrack":12,"./RTCBrowserType":14,"./RTCUtils":15}],11:[function(require,module,exports){
  853. var JitsiTrack = require("./JitsiTrack");
  854. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  855. /**
  856. * Represents a single media track (either audio or video).
  857. * @param RTC the rtc instance.
  858. * @param data object with the stream and some details about it(participant id, video type, etc.)
  859. * @param sid sid for the Media Stream
  860. * @param ssrc ssrc for the Media Stream
  861. * @param eventEmitter the event emitter
  862. * @constructor
  863. */
  864. function JitsiRemoteTrack(RTC, data, sid, ssrc, eventEmitter) {
  865. JitsiTrack.call(this, RTC, data.stream);
  866. this.rtc = RTC;
  867. this.sid = sid;
  868. this.stream = data.stream;
  869. this.peerjid = data.peerjid;
  870. this.videoType = data.videoType;
  871. this.ssrc = ssrc;
  872. this.muted = false;
  873. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  874. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  875. this.muted = true
  876. }
  877. this.eventEmitter = eventEmitter;
  878. var self = this;
  879. if(this.stream)
  880. this.stream.onended = function () {
  881. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_ENDED, self);
  882. }
  883. }
  884. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  885. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  886. /**
  887. * Sets current muted status and fires an events for the change.
  888. * @param value the muted status.
  889. */
  890. JitsiRemoteTrack.prototype.setMute = function (value) {
  891. this.stream.muted = value;
  892. this.muted = value;
  893. this.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  894. };
  895. /**
  896. * Returns the current muted status of the track.
  897. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  898. */
  899. JitsiRemoteTrack.prototype.isMuted = function () {
  900. return this.muted;
  901. }
  902. /**
  903. * Returns the participant id which owns the track.
  904. * @returns {string} the id of the participants.
  905. */
  906. JitsiRemoteTrack.prototype.getParitcipantId = function() {
  907. return Strophe.getResourceFromJid(this.peerjid);
  908. };
  909. delete JitsiRemoteTrack.prototype.stop;
  910. delete JitsiRemoteTrack.prototype.start;
  911. module.exports = JitsiRemoteTrack;
  912. },{"../../service/RTC/StreamEventTypes":73,"./JitsiTrack":12}],12:[function(require,module,exports){
  913. var RTC = require("./RTCUtils");
  914. var RTCBrowserType = require("./RTCBrowserType");
  915. /**
  916. * This implements 'onended' callback normally fired by WebRTC after the stream
  917. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  918. * @param stream original WebRTC stream object to which 'onended' handling
  919. * will be added.
  920. */
  921. function implementOnEndedHandling(stream) {
  922. var originalStop = stream.stop;
  923. stream.stop = function () {
  924. originalStop.apply(stream);
  925. if (!stream.ended) {
  926. stream.ended = true;
  927. stream.onended();
  928. }
  929. };
  930. }
  931. /**
  932. * Represents a single media track (either audio or video).
  933. * @constructor
  934. */
  935. function JitsiTrack(RTC, stream)
  936. {
  937. /**
  938. * Array with the HTML elements that are displaying the streams.
  939. * @type {Array}
  940. */
  941. this.containers = [];
  942. this.rtc = RTC;
  943. this.stream = stream;
  944. this.type = (this.stream.getVideoTracks().length > 0)?
  945. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  946. if(this.type == "audio") {
  947. this._getTracks = function () {
  948. return this.stream.getAudioTracks();
  949. }.bind(this);
  950. } else {
  951. this._getTracks = function () {
  952. return this.stream.getVideoTracks();
  953. }.bind(this);
  954. }
  955. if (RTCBrowserType.isFirefox() && this.stream) {
  956. implementOnEndedHandling(this.stream);
  957. }
  958. }
  959. /**
  960. * JitsiTrack video type.
  961. * @type {string}
  962. */
  963. JitsiTrack.VIDEO = "video";
  964. /**
  965. * JitsiTrack audio type.
  966. * @type {string}
  967. */
  968. JitsiTrack.AUDIO = "audio";
  969. /**
  970. * Returns the type (audio or video) of this track.
  971. */
  972. JitsiTrack.prototype.getType = function() {
  973. return this.type;
  974. };
  975. /**
  976. * Returns the RTCMediaStream from the browser (?).
  977. */
  978. JitsiTrack.prototype.getOriginalStream = function() {
  979. return this.stream;
  980. }
  981. /**
  982. * Mutes the track.
  983. */
  984. JitsiTrack.prototype.mute = function () {
  985. this._setMute(true);
  986. }
  987. /**
  988. * Unmutes the stream.
  989. */
  990. JitsiTrack.prototype.unmute = function () {
  991. this._setMute(false);
  992. }
  993. /**
  994. * Attaches the MediaStream of this track to an HTML container (?).
  995. * Adds the container to the list of containers that are displaying the track.
  996. * @param container the HTML container
  997. */
  998. JitsiTrack.prototype.attach = function (container) {
  999. if(this.stream)
  1000. RTC.attachMediaStream(container, this.stream);
  1001. this.containers.push(container);
  1002. }
  1003. /**
  1004. * Removes the track from the passed HTML container.
  1005. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  1006. */
  1007. JitsiTrack.prototype.detach = function (container) {
  1008. for(var i = 0; i < this.containers.length; i++)
  1009. {
  1010. if(this.containers[i].is(container))
  1011. {
  1012. this.containers.splice(i,1);
  1013. }
  1014. if(!container)
  1015. {
  1016. this.containers[i].find(">video").remove();
  1017. }
  1018. }
  1019. if(container)
  1020. $(container).find(">video").remove();
  1021. }
  1022. /**
  1023. * Stops sending the media track. And removes it from the HTML.
  1024. * NOTE: Works for local tracks only.
  1025. */
  1026. JitsiTrack.prototype.stop = function () {
  1027. }
  1028. /**
  1029. * Starts sending the track.
  1030. * NOTE: Works for local tracks only.
  1031. */
  1032. JitsiTrack.prototype.start = function() {
  1033. }
  1034. /**
  1035. * Returns true if this is a video track and the source of the video is a
  1036. * screen capture as opposed to a camera.
  1037. */
  1038. JitsiTrack.prototype.isScreenSharing = function(){
  1039. }
  1040. /**
  1041. * Returns id of the track.
  1042. * @returns {string} id of the track or null if this is fake track.
  1043. */
  1044. JitsiTrack.prototype.getId = function () {
  1045. var tracks = this.stream.getTracks();
  1046. if(!tracks || tracks.length === 0)
  1047. return null;
  1048. return tracks[0].id;
  1049. };
  1050. module.exports = JitsiTrack;
  1051. },{"./RTCBrowserType":14,"./RTCUtils":15}],13:[function(require,module,exports){
  1052. /* global APP */
  1053. var EventEmitter = require("events");
  1054. var RTCBrowserType = require("./RTCBrowserType");
  1055. var RTCUtils = require("./RTCUtils.js");
  1056. var JitsiTrack = require("./JitsiTrack");
  1057. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  1058. var DataChannels = require("./DataChannels");
  1059. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  1060. var DesktopSharingEventTypes
  1061. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1062. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  1063. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  1064. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  1065. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  1066. var desktopsharing = require("../desktopsharing/desktopsharing");
  1067. function getMediaStreamUsage()
  1068. {
  1069. var result = {
  1070. audio: true,
  1071. video: true
  1072. };
  1073. /** There are some issues with the desktop sharing
  1074. * when this property is enabled.
  1075. * WARNING: We must change the implementation to start video/audio if we
  1076. * receive from the focus that the peer is not muted.
  1077. var isSecureConnection = window.location.protocol == "https:";
  1078. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  1079. {
  1080. result = {
  1081. audio: false,
  1082. video: false
  1083. };
  1084. }
  1085. **/
  1086. return result;
  1087. }
  1088. var rtcReady = false;
  1089. function RTC(room, options) {
  1090. this.devices = {
  1091. audio: true,
  1092. video: true
  1093. };
  1094. this.room = room;
  1095. this.localStreams = [];
  1096. this.remoteStreams = {};
  1097. this.localAudio = null;
  1098. this.localVideo = null;
  1099. this.eventEmitter = new EventEmitter();
  1100. var self = this;
  1101. this.options = options || {};
  1102. desktopsharing.addListener(
  1103. function (stream, isUsingScreenStream, callback) {
  1104. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  1105. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  1106. room.addPresenceListener("videomuted", function (values, from) {
  1107. if(self.remoteStreams[from])
  1108. self.remoteStreams[from][JitsiTrack.VIDEO].setMute(values.value == "true");
  1109. });
  1110. room.addPresenceListener("audiomuted", function (values, from) {
  1111. if(self.remoteStreams[from])
  1112. self.remoteStreams[from][JitsiTrack.AUDIO].setMute(values.value == "true");
  1113. });
  1114. }
  1115. /**
  1116. * Creates the local MediaStreams.
  1117. * @param options object for options (NOTE: currently only list of devices and resolution are supported)
  1118. * @param dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1119. * type: "audio" or "video", isMuted: true/false, videoType: "camera" or "desktop"}
  1120. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1121. * @returns {*} Promise object that will receive the new JitsiTracks
  1122. */
  1123. RTC.prototype.obtainAudioAndVideoPermissions = function (options, dontCreateJitsiTrack) {
  1124. return RTCUtils.obtainAudioAndVideoPermissions(this,
  1125. options.devices, getMediaStreamUsage(), options.resolution, dontCreateJitsiTrack);
  1126. }
  1127. RTC.prototype.onIncommingCall = function(event) {
  1128. if(this.options.config.openSctp)
  1129. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  1130. this.room.addLocalStreams(this.localStreams);
  1131. }
  1132. RTC.prototype.selectedEndpoint = function (id) {
  1133. if(this.dataChannels)
  1134. this.dataChannels.handleSelectedEndpointEvent(id);
  1135. }
  1136. RTC.prototype.pinEndpoint = function (id) {
  1137. if(this.dataChannels)
  1138. this.dataChannels.handlePinnedEndpointEvent(id);
  1139. }
  1140. RTC.prototype.addStreamListener = function (listener, eventType) {
  1141. this.eventEmitter.on(eventType, listener);
  1142. };
  1143. RTC.prototype.addListener = function (type, listener) {
  1144. this.eventEmitter.on(type, listener);
  1145. };
  1146. RTC.prototype.removeListener = function (listener, eventType) {
  1147. this.eventEmitter.removeListener(eventType, listener);
  1148. };
  1149. RTC.prototype.removeStreamListener = function (listener, eventType) {
  1150. if(!(eventType instanceof StreamEventTypes))
  1151. throw "Illegal argument";
  1152. this.eventEmitter.removeListener(eventType, listener);
  1153. };
  1154. RTC.addRTCReadyListener = function (listener) {
  1155. RTCUtils.eventEmitter.on(RTCEvents.RTC_READY, listener);
  1156. }
  1157. RTC.removeRTCReadyListener = function (listener) {
  1158. RTCUtils.eventEmitter.removeListener(RTCEvents.RTC_READY, listener);
  1159. }
  1160. RTC.isRTCReady = function () {
  1161. return rtcReady;
  1162. }
  1163. RTC.init = function (options) {
  1164. // In case of IE we continue from 'onReady' callback
  1165. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  1166. // once it is initialized.
  1167. var onReady = function () {
  1168. rtcReady = true;
  1169. RTCUtils.eventEmitter.emit(RTCEvents.RTC_READY, true);
  1170. };
  1171. RTCUtils.init(onReady, options || {});
  1172. // Call onReady() if Temasys plugin is not used
  1173. if (!RTCBrowserType.isTemasysPluginUsed()) {
  1174. onReady();
  1175. }
  1176. }
  1177. RTC.prototype.createLocalStreams = function (streams, change) {
  1178. for (var i = 0; i < streams.length; i++) {
  1179. var localStream = new JitsiLocalTrack(this, streams[i].stream,
  1180. this.eventEmitter, streams[i].videoType,
  1181. streams[i].isGUMStream);
  1182. this.localStreams.push(localStream);
  1183. if (streams[i].isMuted === true)
  1184. localStream.setMute(true);
  1185. if (streams[i].type == "audio") {
  1186. this.localAudio = localStream;
  1187. } else {
  1188. this.localVideo = localStream;
  1189. }
  1190. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  1191. if (change)
  1192. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  1193. this.eventEmitter.emit(eventType, localStream, streams[i].isMuted);
  1194. }
  1195. return this.localStreams;
  1196. };
  1197. RTC.prototype.removeLocalStream = function (stream) {
  1198. for(var i = 0; i < this.localStreams.length; i++) {
  1199. if(this.localStreams[i].getOriginalStream() === stream) {
  1200. delete this.localStreams[i];
  1201. return;
  1202. }
  1203. }
  1204. };
  1205. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  1206. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc,
  1207. this.eventEmitter);
  1208. if(!data.peerjid)
  1209. return;
  1210. var jid = data.peerjid;
  1211. if(!this.remoteStreams[jid]) {
  1212. this.remoteStreams[jid] = {};
  1213. }
  1214. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  1215. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  1216. return remoteStream;
  1217. };
  1218. RTC.getPCConstraints = function () {
  1219. return RTCUtils.pc_constraints;
  1220. };
  1221. RTC.prototype.getUserMediaWithConstraints = function(um, success_callback,
  1222. failure_callback, resolution,
  1223. bandwidth, fps, desktopStream)
  1224. {
  1225. return RTCUtils.getUserMediaWithConstraints(this, um, success_callback,
  1226. failure_callback, resolution, bandwidth, fps, desktopStream);
  1227. };
  1228. RTC.attachMediaStream = function (elSelector, stream) {
  1229. RTCUtils.attachMediaStream(elSelector, stream);
  1230. };
  1231. RTC.getStreamID = function (stream) {
  1232. return RTCUtils.getStreamID(stream);
  1233. };
  1234. RTC.getVideoSrc = function (element) {
  1235. return RTCUtils.getVideoSrc(element);
  1236. };
  1237. RTC.setVideoSrc = function (element, src) {
  1238. RTCUtils.setVideoSrc(element, src);
  1239. };
  1240. RTC.prototype.getVideoElementName = function () {
  1241. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  1242. };
  1243. RTC.prototype.dispose = function() {
  1244. };
  1245. RTC.prototype.muteRemoteVideoStream = function (jid, value) {
  1246. var stream;
  1247. if(this.remoteStreams[jid] &&
  1248. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1249. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  1250. }
  1251. if(!stream)
  1252. return true;
  1253. if (value != stream.muted) {
  1254. stream.setMute(value);
  1255. return true;
  1256. }
  1257. return false;
  1258. };
  1259. RTC.prototype.switchVideoStreams = function (new_stream) {
  1260. this.localVideo.stream = new_stream;
  1261. this.localStreams = [];
  1262. //in firefox we have only one stream object
  1263. if (this.localAudio.getOriginalStream() != new_stream)
  1264. this.localStreams.push(this.localAudio);
  1265. this.localStreams.push(this.localVideo);
  1266. };
  1267. /**
  1268. * Creates <tt>JitsiTrack</tt> instance and replaces it with the local video.
  1269. * The method also handles the sdp changes.
  1270. * @param stream the new MediaStream received by the browser.
  1271. * @param isUsingScreenStream <tt>true</tt> if the stream is for desktop stream.
  1272. * @param callback - function that will be called after the operation is completed.
  1273. */
  1274. RTC.prototype.changeLocalVideo = function (stream, isUsingScreenStream, callback) {
  1275. var oldStream = this.localVideo.getOriginalStream();
  1276. var type = (isUsingScreenStream ? "screen" : "camera");
  1277. var localCallback = callback;
  1278. if(this.localVideo.isMuted() && this.localVideo.videoType !== type) {
  1279. localCallback = function() {
  1280. this.room.setVideoMute(false, function(mute) {
  1281. this.eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);
  1282. }.bind(this));
  1283. callback();
  1284. };
  1285. }
  1286. // FIXME: Workaround for FF/IE/Safari
  1287. if (stream && stream.videoStream) {
  1288. stream = stream.videoStream;
  1289. }
  1290. var videoStream = RTCUtils.createStream(stream, true);
  1291. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  1292. // Stop the stream to trigger onended event for old stream
  1293. oldStream.stop();
  1294. this.switchVideoStreams(videoStream, oldStream);
  1295. this.room.switchStreams(videoStream, oldStream,localCallback);
  1296. };
  1297. /**
  1298. * Creates <tt>JitsiTrack</tt> instance and replaces it with the local audio.
  1299. * The method also handles the sdp changes.
  1300. * @param stream the new MediaStream received by the browser.
  1301. * @param callback - function that will be called after the operation is completed.
  1302. */
  1303. RTC.prototype.changeLocalAudio = function (stream, callback) {
  1304. var oldStream = this.localAudio.getOriginalStream();
  1305. var newStream = RTCUtils.createStream(stream);
  1306. this.localAudio = this.createLocalStream(newStream, "audio", true);
  1307. // Stop the stream to trigger onended event for old stream
  1308. oldStream.stop();
  1309. this.room.switchStreams(newStream, oldStream, callback, true);
  1310. };
  1311. RTC.prototype.isVideoMuted = function (jid) {
  1312. if (jid === APP.xmpp.myJid()) {
  1313. var localVideo = APP.RTC.localVideo;
  1314. return (!localVideo || localVideo.isMuted());
  1315. } else {
  1316. if (!this.remoteStreams[jid] ||
  1317. !this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1318. return null;
  1319. }
  1320. return this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  1321. }
  1322. };
  1323. RTC.prototype.setVideoMute = function (mute, callback, options) {
  1324. if (!this.localVideo)
  1325. return;
  1326. if (mute == this.localVideo.isMuted())
  1327. {
  1328. APP.xmpp.sendVideoInfoPresence(mute);
  1329. if (callback)
  1330. callback(mute);
  1331. }
  1332. else
  1333. {
  1334. this.localVideo.setMute(mute);
  1335. this.room.setVideoMute(
  1336. mute,
  1337. callback,
  1338. options);
  1339. }
  1340. };
  1341. RTC.prototype.setDeviceAvailability = function (devices) {
  1342. if(!devices)
  1343. return;
  1344. if(devices.audio === true || devices.audio === false)
  1345. this.devices.audio = devices.audio;
  1346. if(devices.video === true || devices.video === false)
  1347. this.devices.video = devices.video;
  1348. this.eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  1349. };
  1350. module.exports = RTC;
  1351. },{"../../service/RTC/MediaStreamTypes":70,"../../service/RTC/RTCEvents.js":71,"../../service/RTC/StreamEventTypes.js":73,"../../service/desktopsharing/DesktopSharingEventTypes":75,"../../service/xmpp/XMPPEvents":76,"../desktopsharing/desktopsharing":17,"./DataChannels":9,"./JitsiLocalTrack.js":10,"./JitsiRemoteTrack.js":11,"./JitsiTrack":12,"./RTCBrowserType":14,"./RTCUtils.js":15,"events":77}],14:[function(require,module,exports){
  1352. var currentBrowser;
  1353. var browserVersion;
  1354. var RTCBrowserType = {
  1355. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  1356. RTC_BROWSER_OPERA: "rtc_browser.opera",
  1357. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  1358. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  1359. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  1360. getBrowserType: function () {
  1361. return currentBrowser;
  1362. },
  1363. isChrome: function () {
  1364. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  1365. },
  1366. isOpera: function () {
  1367. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  1368. },
  1369. isFirefox: function () {
  1370. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  1371. },
  1372. isIExplorer: function () {
  1373. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1374. },
  1375. isSafari: function () {
  1376. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  1377. },
  1378. isTemasysPluginUsed: function () {
  1379. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  1380. },
  1381. getFirefoxVersion: function () {
  1382. return RTCBrowserType.isFirefox() ? browserVersion : null;
  1383. },
  1384. getChromeVersion: function () {
  1385. return RTCBrowserType.isChrome() ? browserVersion : null;
  1386. },
  1387. usesPlanB: function() {
  1388. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  1389. RTCBrowserType.isTemasysPluginUsed();
  1390. },
  1391. usesUnifiedPlan: function() {
  1392. return RTCBrowserType.isFirefox();
  1393. }
  1394. // Add version getters for other browsers when needed
  1395. };
  1396. // detectOpera() must be called before detectChrome() !!!
  1397. // otherwise Opera wil be detected as Chrome
  1398. function detectChrome() {
  1399. if (navigator.webkitGetUserMedia) {
  1400. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  1401. var userAgent = navigator.userAgent.toLowerCase();
  1402. // We can assume that user agent is chrome, because it's
  1403. // enforced when 'ext' streaming method is set
  1404. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  1405. console.log("This appears to be Chrome, ver: " + ver);
  1406. return ver;
  1407. }
  1408. return null;
  1409. }
  1410. function detectOpera() {
  1411. var userAgent = navigator.userAgent;
  1412. if (userAgent.match(/Opera|OPR/)) {
  1413. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  1414. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  1415. console.info("This appears to be Opera, ver: " + version);
  1416. return version;
  1417. }
  1418. return null;
  1419. }
  1420. function detectFirefox() {
  1421. if (navigator.mozGetUserMedia) {
  1422. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1423. var version = parseInt(
  1424. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1425. console.log('This appears to be Firefox, ver: ' + version);
  1426. return version;
  1427. }
  1428. return null;
  1429. }
  1430. function detectSafari() {
  1431. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1432. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1433. console.info("This appears to be Safari");
  1434. // FIXME detect Safari version when needed
  1435. return 1;
  1436. }
  1437. return null;
  1438. }
  1439. function detectIE() {
  1440. var version;
  1441. var ua = window.navigator.userAgent;
  1442. var msie = ua.indexOf('MSIE ');
  1443. if (msie > 0) {
  1444. // IE 10 or older => return version number
  1445. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1446. }
  1447. var trident = ua.indexOf('Trident/');
  1448. if (!version && trident > 0) {
  1449. // IE 11 => return version number
  1450. var rv = ua.indexOf('rv:');
  1451. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1452. }
  1453. var edge = ua.indexOf('Edge/');
  1454. if (!version && edge > 0) {
  1455. // IE 12 => return version number
  1456. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1457. }
  1458. if (version) {
  1459. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1460. console.info("This appears to be IExplorer, ver: " + version);
  1461. }
  1462. return version;
  1463. }
  1464. function detectBrowser() {
  1465. var version;
  1466. var detectors = [
  1467. detectOpera,
  1468. detectChrome,
  1469. detectFirefox,
  1470. detectIE,
  1471. detectSafari
  1472. ];
  1473. // Try all browser detectors
  1474. for (var i = 0; i < detectors.length; i++) {
  1475. version = detectors[i]();
  1476. if (version)
  1477. return version;
  1478. }
  1479. console.error("Failed to detect browser type");
  1480. return undefined;
  1481. }
  1482. browserVersion = detectBrowser();
  1483. module.exports = RTCBrowserType;
  1484. },{}],15:[function(require,module,exports){
  1485. /* global config, require, attachMediaStream, getUserMedia */
  1486. var RTCBrowserType = require("./RTCBrowserType");
  1487. var Resolutions = require("../../service/RTC/Resolutions");
  1488. var AdapterJS = require("./adapter.screenshare");
  1489. var SDPUtil = require("../xmpp/SDPUtil");
  1490. var EventEmitter = require("events");
  1491. function DummyMediaStream(id) {
  1492. this.id = id;
  1493. this.label = id;
  1494. this.stop = function() { };
  1495. this.getAudioTracks = function() { return []; };
  1496. this.getVideoTracks = function() { return []; };
  1497. }
  1498. function getPreviousResolution(resolution) {
  1499. if(!Resolutions[resolution])
  1500. return null;
  1501. var order = Resolutions[resolution].order;
  1502. var res = null;
  1503. var resName = null;
  1504. for(var i in Resolutions) {
  1505. var tmp = Resolutions[i];
  1506. if(res == null || (res.order < tmp.order && tmp.order < order)) {
  1507. resName = i;
  1508. res = tmp;
  1509. }
  1510. }
  1511. return resName;
  1512. }
  1513. function setResolutionConstraints(constraints, resolution, isAndroid) {
  1514. if (Resolutions[resolution]) {
  1515. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1516. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1517. }
  1518. else if (isAndroid) {
  1519. // FIXME can't remember if the purpose of this was to always request
  1520. // low resolution on Android ? if yes it should be moved up front
  1521. constraints.video.mandatory.minWidth = 320;
  1522. constraints.video.mandatory.minHeight = 240;
  1523. constraints.video.mandatory.maxFrameRate = 15;
  1524. }
  1525. if (constraints.video.mandatory.minWidth)
  1526. constraints.video.mandatory.maxWidth =
  1527. constraints.video.mandatory.minWidth;
  1528. if (constraints.video.mandatory.minHeight)
  1529. constraints.video.mandatory.maxHeight =
  1530. constraints.video.mandatory.minHeight;
  1531. }
  1532. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1533. {
  1534. var constraints = {audio: false, video: false};
  1535. if (um.indexOf('video') >= 0) {
  1536. // same behaviour as true
  1537. constraints.video = { mandatory: {}, optional: [] };
  1538. constraints.video.optional.push({ googLeakyBucket: true });
  1539. setResolutionConstraints(constraints, resolution, isAndroid);
  1540. }
  1541. if (um.indexOf('audio') >= 0) {
  1542. if (!RTCBrowserType.isFirefox()) {
  1543. // same behaviour as true
  1544. constraints.audio = { mandatory: {}, optional: []};
  1545. // if it is good enough for hangouts...
  1546. constraints.audio.optional.push(
  1547. {googEchoCancellation: true},
  1548. {googAutoGainControl: true},
  1549. {googNoiseSupression: true},
  1550. {googHighpassFilter: true},
  1551. {googNoisesuppression2: true},
  1552. {googEchoCancellation2: true},
  1553. {googAutoGainControl2: true}
  1554. );
  1555. } else {
  1556. constraints.audio = true;
  1557. }
  1558. }
  1559. if (um.indexOf('screen') >= 0) {
  1560. if (RTCBrowserType.isChrome()) {
  1561. constraints.video = {
  1562. mandatory: {
  1563. chromeMediaSource: "screen",
  1564. googLeakyBucket: true,
  1565. maxWidth: window.screen.width,
  1566. maxHeight: window.screen.height,
  1567. maxFrameRate: 3
  1568. },
  1569. optional: []
  1570. };
  1571. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1572. constraints.video = {
  1573. optional: [
  1574. {
  1575. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1576. }
  1577. ]
  1578. };
  1579. } else {
  1580. console.error(
  1581. "'screen' WebRTC media source is supported only in Chrome" +
  1582. " and with Temasys plugin");
  1583. }
  1584. }
  1585. if (um.indexOf('desktop') >= 0) {
  1586. constraints.video = {
  1587. mandatory: {
  1588. chromeMediaSource: "desktop",
  1589. chromeMediaSourceId: desktopStream,
  1590. googLeakyBucket: true,
  1591. maxWidth: window.screen.width,
  1592. maxHeight: window.screen.height,
  1593. maxFrameRate: 3
  1594. },
  1595. optional: []
  1596. };
  1597. }
  1598. if (bandwidth) {
  1599. if (!constraints.video) {
  1600. //same behaviour as true
  1601. constraints.video = {mandatory: {}, optional: []};
  1602. }
  1603. constraints.video.optional.push({bandwidth: bandwidth});
  1604. }
  1605. if (fps) {
  1606. // for some cameras it might be necessary to request 30fps
  1607. // so they choose 30fps mjpg over 10fps yuy2
  1608. if (!constraints.video) {
  1609. // same behaviour as true;
  1610. constraints.video = {mandatory: {}, optional: []};
  1611. }
  1612. constraints.video.mandatory.minFrameRate = fps;
  1613. }
  1614. return constraints;
  1615. }
  1616. //Options parameter is to pass config options. Currently uses only "useIPv6".
  1617. var RTCUtils = {
  1618. eventEmitter: new EventEmitter(),
  1619. init: function (onTemasysPluginReady, options) {
  1620. var self = this;
  1621. if (RTCBrowserType.isFirefox()) {
  1622. var FFversion = RTCBrowserType.getFirefoxVersion();
  1623. if (FFversion >= 40) {
  1624. this.peerconnection = mozRTCPeerConnection;
  1625. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1626. this.pc_constraints = {};
  1627. this.attachMediaStream = function (element, stream) {
  1628. // srcObject is being standardized and FF will eventually
  1629. // support that unprefixed. FF also supports the
  1630. // "element.src = URL.createObjectURL(...)" combo, but that
  1631. // will be deprecated in favour of srcObject.
  1632. //
  1633. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1634. // https://github.com/webrtc/samples/issues/302
  1635. if (!element[0])
  1636. return;
  1637. element[0].mozSrcObject = stream;
  1638. element[0].play();
  1639. };
  1640. this.getStreamID = function (stream) {
  1641. var id = stream.id;
  1642. if (!id) {
  1643. var tracks = stream.getVideoTracks();
  1644. if (!tracks || tracks.length === 0) {
  1645. tracks = stream.getAudioTracks();
  1646. }
  1647. id = tracks[0].id;
  1648. }
  1649. return SDPUtil.filter_special_chars(id);
  1650. };
  1651. this.getVideoSrc = function (element) {
  1652. if (!element)
  1653. return null;
  1654. return element.mozSrcObject;
  1655. };
  1656. this.setVideoSrc = function (element, src) {
  1657. if (element)
  1658. element.mozSrcObject = src;
  1659. };
  1660. RTCSessionDescription = mozRTCSessionDescription;
  1661. RTCIceCandidate = mozRTCIceCandidate;
  1662. } else {
  1663. console.error(
  1664. "Firefox version too old: " + FFversion + ". Required >= 40.");
  1665. window.location.href = 'unsupported_browser.html';
  1666. return;
  1667. }
  1668. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1669. this.peerconnection = webkitRTCPeerConnection;
  1670. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1671. this.attachMediaStream = function (element, stream) {
  1672. element.attr('src', webkitURL.createObjectURL(stream));
  1673. };
  1674. this.getStreamID = function (stream) {
  1675. // streams from FF endpoints have the characters '{' and '}'
  1676. // that make jQuery choke.
  1677. return SDPUtil.filter_special_chars(stream.id);
  1678. };
  1679. this.getVideoSrc = function (element) {
  1680. if (!element)
  1681. return null;
  1682. return element.getAttribute("src");
  1683. };
  1684. this.setVideoSrc = function (element, src) {
  1685. if (element)
  1686. element.setAttribute("src", src);
  1687. };
  1688. // DTLS should now be enabled by default but..
  1689. this.pc_constraints = {'optional': [
  1690. {'DtlsSrtpKeyAgreement': 'true'}
  1691. ]};
  1692. if (options.useIPv6) {
  1693. // https://code.google.com/p/webrtc/issues/detail?id=2828
  1694. this.pc_constraints.optional.push({googIPv6: true});
  1695. }
  1696. if (navigator.userAgent.indexOf('Android') != -1) {
  1697. this.pc_constraints = {}; // disable DTLS on Android
  1698. }
  1699. if (!webkitMediaStream.prototype.getVideoTracks) {
  1700. webkitMediaStream.prototype.getVideoTracks = function () {
  1701. return this.videoTracks;
  1702. };
  1703. }
  1704. if (!webkitMediaStream.prototype.getAudioTracks) {
  1705. webkitMediaStream.prototype.getAudioTracks = function () {
  1706. return this.audioTracks;
  1707. };
  1708. }
  1709. }
  1710. // Detect IE/Safari
  1711. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1712. //AdapterJS.WebRTCPlugin.setLogLevel(
  1713. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1714. AdapterJS.webRTCReady(function (isPlugin) {
  1715. self.peerconnection = RTCPeerConnection;
  1716. self.getUserMedia = getUserMedia;
  1717. self.attachMediaStream = function (elSel, stream) {
  1718. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1719. return;
  1720. }
  1721. attachMediaStream(elSel[0], stream);
  1722. };
  1723. self.getStreamID = function (stream) {
  1724. var id = SDPUtil.filter_special_chars(stream.label);
  1725. return id;
  1726. };
  1727. self.getVideoSrc = function (element) {
  1728. if (!element) {
  1729. console.warn("Attempt to get video SRC of null element");
  1730. return null;
  1731. }
  1732. var children = element.children;
  1733. for (var i = 0; i !== children.length; ++i) {
  1734. if (children[i].name === 'streamId') {
  1735. return children[i].value;
  1736. }
  1737. }
  1738. //console.info(element.id + " SRC: " + src);
  1739. return null;
  1740. };
  1741. self.setVideoSrc = function (element, src) {
  1742. //console.info("Set video src: ", element, src);
  1743. if (!src) {
  1744. console.warn("Not attaching video stream, 'src' is null");
  1745. return;
  1746. }
  1747. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1748. var stream = AdapterJS.WebRTCPlugin.plugin
  1749. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1750. attachMediaStream(element, stream);
  1751. };
  1752. onTemasysPluginReady(isPlugin);
  1753. });
  1754. } else {
  1755. try {
  1756. console.log('Browser does not appear to be WebRTC-capable');
  1757. } catch (e) {
  1758. }
  1759. window.location.href = 'unsupported_browser.html';
  1760. }
  1761. },
  1762. getUserMediaWithConstraints: function (RTC, um, success_callback, failure_callback, resolution, bandwidth, fps, desktopStream) {
  1763. // Check if we are running on Android device
  1764. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1765. var constraints = getConstraints(
  1766. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1767. console.info("Get media constraints", constraints);
  1768. var self = this;
  1769. try {
  1770. this.getUserMedia(constraints,
  1771. function (stream) {
  1772. console.log('onUserMediaSuccess');
  1773. self.setAvailableDevices(RTC, um, true);
  1774. success_callback(stream);
  1775. },
  1776. function (error) {
  1777. self.setAvailableDevices(RTC, um, false);
  1778. console.warn('Failed to get access to local media. Error ',
  1779. error, constraints);
  1780. if (failure_callback) {
  1781. failure_callback(error, resolution);
  1782. }
  1783. });
  1784. } catch (e) {
  1785. console.error('GUM failed: ', e);
  1786. if (failure_callback) {
  1787. failure_callback(e);
  1788. }
  1789. }
  1790. },
  1791. setAvailableDevices: function (RTC, um, available) {
  1792. var devices = {};
  1793. if (um.indexOf("video") != -1) {
  1794. devices.video = available;
  1795. }
  1796. if (um.indexOf("audio") != -1) {
  1797. devices.audio = available;
  1798. }
  1799. RTC.setDeviceAvailability(devices);
  1800. },
  1801. /**
  1802. * Creates the local MediaStreams.
  1803. * @param RTC the rtc service.
  1804. * @param devices the devices that will be requested
  1805. * @param usageOptions object with devices that should be requested.
  1806. * @param resolution resolution constraints
  1807. * @param dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1808. * type: "audio" or "video", isMuted: true/false, videoType: "camera" or "desktop"}
  1809. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1810. * @returns {*} Promise object that will receive the new JitsiTracks
  1811. */
  1812. obtainAudioAndVideoPermissions: function (RTC, devices, usageOptions, resolution, dontCreateJitsiTracks) {
  1813. var self = this;
  1814. // Get AV
  1815. return new Promise(function (resolve, reject) {
  1816. var successCallback = function (stream) {
  1817. var streams = self.successCallback(RTC , stream, usageOptions);
  1818. resolve(dontCreateJitsiTracks? streams: RTC.createLocalStreams(streams));
  1819. };
  1820. if (!devices)
  1821. devices = ['audio', 'video'];
  1822. var newDevices = [];
  1823. if (usageOptions)
  1824. for (var i = 0; i < devices.length; i++) {
  1825. var device = devices[i];
  1826. if (usageOptions[device] === true)
  1827. newDevices.push(device);
  1828. }
  1829. else
  1830. newDevices = devices;
  1831. if (newDevices.length === 0) {
  1832. successCallback();
  1833. return;
  1834. }
  1835. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1836. // With FF/IE we can't split the stream into audio and video because FF
  1837. // doesn't support media stream constructors. So, we need to get the
  1838. // audio stream separately from the video stream using two distinct GUM
  1839. // calls. Not very user friendly :-( but we don't have many other
  1840. // options neither.
  1841. //
  1842. // Note that we pack those 2 streams in a single object and pass it to
  1843. // the successCallback method.
  1844. var obtainVideo = function (audioStream) {
  1845. self.getUserMediaWithConstraints(
  1846. RTC,
  1847. ['video'],
  1848. function (videoStream) {
  1849. return successCallback({
  1850. audioStream: audioStream,
  1851. videoStream: videoStream
  1852. });
  1853. },
  1854. function (error, resolution) {
  1855. console.error(
  1856. 'failed to obtain video stream - stop', error);
  1857. self.errorCallback(error, resolve, RTC, resolution, dontCreateJitsiTracks);
  1858. },
  1859. config.resolution || '360');
  1860. };
  1861. var obtainAudio = function () {
  1862. self.getUserMediaWithConstraints(
  1863. RTC,
  1864. ['audio'],
  1865. function (audioStream) {
  1866. if (newDevices.indexOf('video') !== -1)
  1867. obtainVideo(audioStream);
  1868. },
  1869. function (error) {
  1870. console.error(
  1871. 'failed to obtain audio stream - stop', error);
  1872. self.errorCallback(error, resolve, RTC, null, dontCreateJitsiTracks);
  1873. }
  1874. );
  1875. };
  1876. if (newDevices.indexOf('audio') !== -1) {
  1877. obtainAudio();
  1878. } else {
  1879. obtainVideo(null);
  1880. }
  1881. } else {
  1882. this.getUserMediaWithConstraints(
  1883. RTC,
  1884. newDevices,
  1885. function (stream) {
  1886. successCallback(stream);
  1887. },
  1888. function (error, resolution) {
  1889. self.errorCallback(error, resolve, RTC, resolution, dontCreateJitsiTracks);
  1890. },
  1891. resolution || '360');
  1892. }
  1893. }.bind(this));
  1894. },
  1895. /**
  1896. * Successful callback called from GUM.
  1897. * @param RTC the rtc service
  1898. * @param stream the new MediaStream
  1899. * @param usageOptions the list of the devices that should be queried.
  1900. * @returns {*}
  1901. */
  1902. successCallback: function (RTC, stream, usageOptions) {
  1903. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1904. // it's an object with two properties: audioStream, videoStream.
  1905. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1906. console.log('got', stream, stream.getAudioTracks().length,
  1907. stream.getVideoTracks().length);
  1908. return this.handleLocalStream(RTC, stream, usageOptions);
  1909. },
  1910. /**
  1911. * Error callback called from GUM. Retries the GUM call with different resolutions.
  1912. * @param error the error
  1913. * @param resolve the resolve funtion that will be called on success.
  1914. * @param RTC the rtc service
  1915. * @param currentResolution the last resolution used for GUM.
  1916. * @param dontCreateJitsiTracks if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1917. * type: "audio" or "video", isMuted: true/false, videoType: "camera" or "desktop"}
  1918. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1919. */
  1920. errorCallback: function (error, resolve, RTC, currentResolution, dontCreateJitsiTracks) {
  1921. var self = this;
  1922. console.error('failed to obtain audio/video stream - trying audio only', error);
  1923. var resolution = getPreviousResolution(currentResolution);
  1924. if (typeof error == "object" && error.constraintName && error.name
  1925. && (error.name == "ConstraintNotSatisfiedError" ||
  1926. error.name == "OverconstrainedError") &&
  1927. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1928. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1929. && resolution != null) {
  1930. self.getUserMediaWithConstraints(RTC, ['audio', 'video'],
  1931. function (stream) {
  1932. var streams = self.successCallback(RTC, stream);
  1933. resolve(dontCreateJitsiTracks? streams: RTC.createLocalStreams(streams));
  1934. }, function (error, resolution) {
  1935. return self.errorCallback(error, resolve, RTC, resolution, dontCreateJitsiTracks);
  1936. }, resolution);
  1937. }
  1938. else {
  1939. self.getUserMediaWithConstraints(
  1940. RTC,
  1941. ['audio'],
  1942. function (stream) {
  1943. var streams = self.successCallback(RTC, stream);
  1944. resolve(dontCreateJitsiTracks? streams: RTC.createLocalStreams(streams));
  1945. },
  1946. function (error) {
  1947. console.error('failed to obtain audio/video stream - stop',
  1948. error);
  1949. var streams = self.successCallback(RTC, null);
  1950. resolve(dontCreateJitsiTracks? streams: RTC.createLocalStreams(streams));
  1951. }
  1952. );
  1953. }
  1954. },
  1955. /**
  1956. * Handles the newly created Media Streams.
  1957. * @param service the rtc service
  1958. * @param stream the new Media Streams
  1959. * @param usageOptions the list of the devices that should be queried.
  1960. * @returns {*[]} Promise object with the new Media Streams.
  1961. */
  1962. handleLocalStream: function (service, stream, usageOptions) {
  1963. var audioStream, videoStream;
  1964. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1965. // an object with two properties: audioStream, videoStream.
  1966. if (window.webkitMediaStream) {
  1967. audioStream = new webkitMediaStream();
  1968. videoStream = new webkitMediaStream();
  1969. if (stream) {
  1970. var audioTracks = stream.getAudioTracks();
  1971. for (var i = 0; i < audioTracks.length; i++) {
  1972. audioStream.addTrack(audioTracks[i]);
  1973. }
  1974. var videoTracks = stream.getVideoTracks();
  1975. for (i = 0; i < videoTracks.length; i++) {
  1976. videoStream.addTrack(videoTracks[i]);
  1977. }
  1978. }
  1979. }
  1980. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  1981. if (stream && stream.audioStream)
  1982. audioStream = stream.audioStream;
  1983. else
  1984. audioStream = new DummyMediaStream("dummyAudio");
  1985. if (stream && stream.videoStream)
  1986. videoStream = stream.videoStream;
  1987. else
  1988. videoStream = new DummyMediaStream("dummyVideo");
  1989. }
  1990. var audioMuted = (usageOptions && usageOptions.audio === false),
  1991. videoMuted = (usageOptions && usageOptions.video === false);
  1992. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1993. videoGUM = (!usageOptions || usageOptions.video !== false);
  1994. return [
  1995. {stream: audioStream, type: "audio", isMuted: audioMuted, isGUMStream: audioGUM, videoType: null},
  1996. {stream: videoStream, type: "video", isMuted: videoMuted, isGUMStream: videoGUM, videoType: "camera"}
  1997. ];
  1998. },
  1999. createStream: function (stream, isVideo) {
  2000. var newStream = null;
  2001. if (window.webkitMediaStream) {
  2002. newStream = new webkitMediaStream();
  2003. if (newStream) {
  2004. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  2005. for (var i = 0; i < tracks.length; i++) {
  2006. newStream.addTrack(tracks[i]);
  2007. }
  2008. }
  2009. } else {
  2010. // FIXME: this is duplicated with 'handleLocalStream' !!!
  2011. if (stream) {
  2012. newStream = stream;
  2013. } else {
  2014. newStream =
  2015. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  2016. }
  2017. }
  2018. return newStream;
  2019. }
  2020. }
  2021. module.exports = RTCUtils;
  2022. },{"../../service/RTC/Resolutions":72,"../xmpp/SDPUtil":25,"./RTCBrowserType":14,"./adapter.screenshare":16,"events":77}],16:[function(require,module,exports){
  2023. /*! adapterjs - custom version from - 2015-08-12 */
  2024. // Adapter's interface.
  2025. var AdapterJS = AdapterJS || {};
  2026. // Browserify compatibility
  2027. if(typeof exports !== 'undefined') {
  2028. module.exports = AdapterJS;
  2029. }
  2030. AdapterJS.options = AdapterJS.options || {};
  2031. // uncomment to get virtual webcams
  2032. // AdapterJS.options.getAllCams = true;
  2033. // uncomment to prevent the install prompt when the plugin in not yet installed
  2034. // AdapterJS.options.hidePluginInstallPrompt = true;
  2035. // AdapterJS version
  2036. AdapterJS.VERSION = '0.11.1';
  2037. // This function will be called when the WebRTC API is ready to be used
  2038. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  2039. // the plugin
  2040. // You may Override this function to synchronise the start of your application
  2041. // with the WebRTC API being ready.
  2042. // If you decide not to override use this synchronisation, it may result in
  2043. // an extensive CPU usage on the plugin start (once per tab loaded)
  2044. // Params:
  2045. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  2046. //
  2047. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  2048. // The WebRTC API is ready.
  2049. // Override me and do whatever you want here
  2050. };
  2051. // Sets a callback function to be called when the WebRTC interface is ready.
  2052. // The first argument is the function to callback.\
  2053. // Throws an error if the first argument is not a function
  2054. AdapterJS.webRTCReady = function (callback) {
  2055. if (typeof callback !== 'function') {
  2056. throw new Error('Callback provided is not a function');
  2057. }
  2058. if (true === AdapterJS.onwebrtcreadyDone) {
  2059. // All WebRTC interfaces are ready, just call the callback
  2060. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  2061. } else {
  2062. // will be triggered automatically when your browser/plugin is ready.
  2063. AdapterJS.onwebrtcready = callback;
  2064. }
  2065. };
  2066. // Plugin namespace
  2067. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  2068. // The object to store plugin information
  2069. AdapterJS.WebRTCPlugin.pluginInfo = {
  2070. prefix : 'Tem',
  2071. plugName : 'TemWebRTCPlugin',
  2072. pluginId : 'plugin0',
  2073. type : 'application/x-temwebrtcplugin',
  2074. onload : '__TemWebRTCReady0',
  2075. portalLink : 'http://skylink.io/plugin/',
  2076. downloadLink : null, //set below
  2077. companyName: 'Temasys'
  2078. };
  2079. if(!!navigator.platform.match(/^Mac/i)) {
  2080. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  2081. }
  2082. else if(!!navigator.platform.match(/^Win/i)) {
  2083. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  2084. }
  2085. // Unique identifier of each opened page
  2086. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  2087. // Use this whenever you want to call the plugin.
  2088. AdapterJS.WebRTCPlugin.plugin = null;
  2089. // Set log level for the plugin once it is ready.
  2090. // The different values are
  2091. // This is an asynchronous function that will run when the plugin is ready
  2092. AdapterJS.WebRTCPlugin.setLogLevel = null;
  2093. // Defines webrtc's JS interface according to the plugin's implementation.
  2094. // Define plugin Browsers as WebRTC Interface.
  2095. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  2096. // This function detects whether or not a plugin is installed.
  2097. // Checks if Not IE (firefox, for example), else if it's IE,
  2098. // we're running IE and do something. If not it is not supported.
  2099. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  2100. // Lets adapter.js wait until the the document is ready before injecting the plugin
  2101. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  2102. // Inject the HTML DOM object element into the page.
  2103. AdapterJS.WebRTCPlugin.injectPlugin = null;
  2104. // States of readiness that the plugin goes through when
  2105. // being injected and stated
  2106. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  2107. NONE : 0, // no plugin use
  2108. INITIALIZING : 1, // Detected need for plugin
  2109. INJECTING : 2, // Injecting plugin
  2110. INJECTED: 3, // Plugin element injected but not usable yet
  2111. READY: 4 // Plugin ready to be used
  2112. };
  2113. // Current state of the plugin. You cannot use the plugin before this is
  2114. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  2115. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  2116. // True is AdapterJS.onwebrtcready was already called, false otherwise
  2117. // Used to make sure AdapterJS.onwebrtcready is only called once
  2118. AdapterJS.onwebrtcreadyDone = false;
  2119. // Log levels for the plugin.
  2120. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  2121. /*
  2122. Log outputs are prefixed in some cases.
  2123. INFO: Information reported by the plugin.
  2124. ERROR: Errors originating from within the plugin.
  2125. WEBRTC: Error originating from within the libWebRTC library
  2126. */
  2127. // From the least verbose to the most verbose
  2128. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  2129. NONE : 'NONE',
  2130. ERROR : 'ERROR',
  2131. WARNING : 'WARNING',
  2132. INFO: 'INFO',
  2133. VERBOSE: 'VERBOSE',
  2134. SENSITIVE: 'SENSITIVE'
  2135. };
  2136. // Does a waiting check before proceeding to load the plugin.
  2137. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  2138. // This methid will use an interval to wait for the plugin to be ready.
  2139. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  2140. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  2141. // This function will be called when plugin is ready. It sends necessary
  2142. // details to the plugin.
  2143. // The function will wait for the document to be ready and the set the
  2144. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  2145. // indicating that it can start being requested.
  2146. // This function is not in the IE/Safari condition brackets so that
  2147. // TemPluginLoaded function might be called on Chrome/Firefox.
  2148. // This function is the only private function that is not encapsulated to
  2149. // allow the plugin method to be called.
  2150. __TemWebRTCReady0 = function () {
  2151. if (document.readyState === 'complete') {
  2152. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  2153. AdapterJS.maybeThroughWebRTCReady();
  2154. } else {
  2155. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  2156. if (document.readyState === 'complete') {
  2157. // TODO: update comments, we wait for the document to be ready
  2158. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  2159. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  2160. AdapterJS.maybeThroughWebRTCReady();
  2161. }
  2162. }, 100);
  2163. }
  2164. };
  2165. AdapterJS.maybeThroughWebRTCReady = function() {
  2166. if (!AdapterJS.onwebrtcreadyDone) {
  2167. AdapterJS.onwebrtcreadyDone = true;
  2168. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  2169. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  2170. }
  2171. }
  2172. };
  2173. // Text namespace
  2174. AdapterJS.TEXT = {
  2175. PLUGIN: {
  2176. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  2177. 'to work on this browser.',
  2178. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  2179. BUTTON: 'Install Now'
  2180. },
  2181. REFRESH: {
  2182. REQUIRE_REFRESH: 'Please refresh page',
  2183. BUTTON: 'Refresh Page'
  2184. }
  2185. };
  2186. // The result of ice connection states.
  2187. // - starting: Ice connection is starting.
  2188. // - checking: Ice connection is checking.
  2189. // - connected Ice connection is connected.
  2190. // - completed Ice connection is connected.
  2191. // - done Ice connection has been completed.
  2192. // - disconnected Ice connection has been disconnected.
  2193. // - failed Ice connection has failed.
  2194. // - closed Ice connection is closed.
  2195. AdapterJS._iceConnectionStates = {
  2196. starting : 'starting',
  2197. checking : 'checking',
  2198. connected : 'connected',
  2199. completed : 'connected',
  2200. done : 'completed',
  2201. disconnected : 'disconnected',
  2202. failed : 'failed',
  2203. closed : 'closed'
  2204. };
  2205. //The IceConnection states that has been fired for each peer.
  2206. AdapterJS._iceConnectionFiredStates = [];
  2207. // Check if WebRTC Interface is defined.
  2208. AdapterJS.isDefined = null;
  2209. // This function helps to retrieve the webrtc detected browser information.
  2210. // This sets:
  2211. // - webrtcDetectedBrowser: The browser agent name.
  2212. // - webrtcDetectedVersion: The browser version.
  2213. // - webrtcDetectedType: The types of webRTC support.
  2214. // - 'moz': Mozilla implementation of webRTC.
  2215. // - 'webkit': WebKit implementation of webRTC.
  2216. // - 'plugin': Using the plugin implementation.
  2217. AdapterJS.parseWebrtcDetectedBrowser = function () {
  2218. var hasMatch, checkMatch = navigator.userAgent.match(
  2219. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  2220. if (/trident/i.test(checkMatch[1])) {
  2221. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  2222. webrtcDetectedBrowser = 'IE';
  2223. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  2224. } else if (checkMatch[1] === 'Chrome') {
  2225. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2226. if (hasMatch !== null) {
  2227. webrtcDetectedBrowser = 'opera';
  2228. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  2229. }
  2230. }
  2231. if (navigator.userAgent.indexOf('Safari')) {
  2232. if (typeof InstallTrigger !== 'undefined') {
  2233. webrtcDetectedBrowser = 'firefox';
  2234. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  2235. webrtcDetectedBrowser = 'IE';
  2236. } else if (
  2237. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  2238. webrtcDetectedBrowser = 'safari';
  2239. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  2240. webrtcDetectedBrowser = 'opera';
  2241. } else if (!!window.chrome) {
  2242. webrtcDetectedBrowser = 'chrome';
  2243. }
  2244. }
  2245. if (!webrtcDetectedBrowser) {
  2246. webrtcDetectedVersion = checkMatch[1];
  2247. }
  2248. if (!webrtcDetectedVersion) {
  2249. try {
  2250. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  2251. [navigator.appName, navigator.appVersion, '-?'];
  2252. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  2253. checkMatch.splice(1, 1, hasMatch[1]);
  2254. }
  2255. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  2256. } catch (error) { }
  2257. }
  2258. };
  2259. // To fix configuration as some browsers does not support
  2260. // the 'urls' attribute.
  2261. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  2262. if (pcConfig === null) {
  2263. return;
  2264. }
  2265. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  2266. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  2267. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  2268. delete pcConfig.iceServers[i].urls;
  2269. }
  2270. }
  2271. };
  2272. AdapterJS.addEvent = function(elem, evnt, func) {
  2273. if (elem.addEventListener) { // W3C DOM
  2274. elem.addEventListener(evnt, func, false);
  2275. } else if (elem.attachEvent) {// OLD IE DOM
  2276. elem.attachEvent('on'+evnt, func);
  2277. } else { // No much to do
  2278. elem[evnt] = func;
  2279. }
  2280. };
  2281. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  2282. // only inject once the page is ready
  2283. if (document.readyState !== 'complete') {
  2284. return;
  2285. }
  2286. var w = window;
  2287. var i = document.createElement('iframe');
  2288. i.style.position = 'fixed';
  2289. i.style.top = '-41px';
  2290. i.style.left = 0;
  2291. i.style.right = 0;
  2292. i.style.width = '100%';
  2293. i.style.height = '40px';
  2294. i.style.backgroundColor = '#ffffe1';
  2295. i.style.border = 'none';
  2296. i.style.borderBottom = '1px solid #888888';
  2297. i.style.zIndex = '9999999';
  2298. if(typeof i.style.webkitTransition === 'string') {
  2299. i.style.webkitTransition = 'all .5s ease-out';
  2300. } else if(typeof i.style.transition === 'string') {
  2301. i.style.transition = 'all .5s ease-out';
  2302. }
  2303. document.body.appendChild(i);
  2304. c = (i.contentWindow) ? i.contentWindow :
  2305. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  2306. c.document.open();
  2307. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  2308. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  2309. 'middle; cursor: default;">' + text + '</span>');
  2310. if(buttonText && buttonLink) {
  2311. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  2312. c.document.close();
  2313. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  2314. if (!!displayRefreshBar) {
  2315. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  2316. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  2317. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  2318. }
  2319. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  2320. e.preventDefault();
  2321. try {
  2322. event.cancelBubble = true;
  2323. } catch(error) { }
  2324. var pluginInstallInterval = setInterval(function(){
  2325. if(! isIE) {
  2326. navigator.plugins.refresh(false);
  2327. }
  2328. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2329. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2330. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2331. function() {
  2332. clearInterval(pluginInstallInterval);
  2333. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  2334. },
  2335. function() { //Does nothing because not used here
  2336. });
  2337. } , 500);
  2338. });
  2339. }else {
  2340. c.document.close();
  2341. }
  2342. AdapterJS.addEvent(c.document, 'click', function() {
  2343. w.document.body.removeChild(i);
  2344. });
  2345. setTimeout(function() {
  2346. if(typeof i.style.webkitTransform === 'string') {
  2347. i.style.webkitTransform = 'translateY(40px)';
  2348. } else if(typeof i.style.transform === 'string') {
  2349. i.style.transform = 'translateY(40px)';
  2350. } else {
  2351. i.style.top = '0px';
  2352. }
  2353. }, 300);
  2354. };
  2355. // -----------------------------------------------------------
  2356. // Detected webrtc implementation. Types are:
  2357. // - 'moz': Mozilla implementation of webRTC.
  2358. // - 'webkit': WebKit implementation of webRTC.
  2359. // - 'plugin': Using the plugin implementation.
  2360. webrtcDetectedType = null;
  2361. // Detected webrtc datachannel support. Types are:
  2362. // - 'SCTP': SCTP datachannel support.
  2363. // - 'RTP': RTP datachannel support.
  2364. webrtcDetectedDCSupport = null;
  2365. // Set the settings for creating DataChannels, MediaStream for
  2366. // Cross-browser compability.
  2367. // - This is only for SCTP based support browsers.
  2368. // the 'urls' attribute.
  2369. checkMediaDataChannelSettings =
  2370. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  2371. if (typeof callback !== 'function') {
  2372. return;
  2373. }
  2374. var beOfferer = true;
  2375. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  2376. // Nightly version does not require MozDontOfferDataChannel for interop
  2377. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  2378. var isPeerFirefox = peerBrowserAgent === 'firefox';
  2379. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  2380. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  2381. // Resends an updated version of constraints for MozDataChannel to work
  2382. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  2383. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  2384. try {
  2385. delete constraints.mandatory.MozDontOfferDataChannel;
  2386. } catch (error) {
  2387. console.error('Failed deleting MozDontOfferDataChannel');
  2388. console.error(error);
  2389. }
  2390. } else if ((isLocalFirefox && !isPeerFirefox)) {
  2391. constraints.mandatory.MozDontOfferDataChannel = true;
  2392. }
  2393. if (!isLocalFirefox) {
  2394. // temporary measure to remove Moz* constraints in non Firefox browsers
  2395. for (var prop in constraints.mandatory) {
  2396. if (constraints.mandatory.hasOwnProperty(prop)) {
  2397. if (prop.indexOf('Moz') !== -1) {
  2398. delete constraints.mandatory[prop];
  2399. }
  2400. }
  2401. }
  2402. }
  2403. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  2404. // interopability of the media stream
  2405. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  2406. beOfferer = false;
  2407. }
  2408. callback(beOfferer, constraints);
  2409. };
  2410. // Handles the differences for all browsers ice connection state output.
  2411. // - Tested outcomes are:
  2412. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  2413. // - Chrome (answerer) : 'checking' > 'connected'
  2414. // - Firefox (offerer) : 'checking' > 'connected'
  2415. // - Firefox (answerer): 'checking' > 'connected'
  2416. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  2417. if (typeof callback !== 'function') {
  2418. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  2419. return;
  2420. }
  2421. peerId = (peerId) ? peerId : 'peer';
  2422. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  2423. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  2424. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  2425. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  2426. AdapterJS._iceConnectionFiredStates[peerId] = [];
  2427. }
  2428. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  2429. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  2430. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  2431. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  2432. setTimeout(function () {
  2433. AdapterJS._iceConnectionFiredStates[peerId]
  2434. .push(AdapterJS._iceConnectionStates.done);
  2435. callback(AdapterJS._iceConnectionStates.done);
  2436. }, 1000);
  2437. }
  2438. callback(iceConnectionState);
  2439. }
  2440. return;
  2441. };
  2442. // Firefox:
  2443. // - Creates iceServer from the url for Firefox.
  2444. // - Create iceServer with stun url.
  2445. // - Create iceServer with turn url.
  2446. // - Ignore the transport parameter from TURN url for FF version <=27.
  2447. // - Return null for createIceServer if transport=tcp.
  2448. // - FF 27 and above supports transport parameters in TURN url,
  2449. // - So passing in the full url to create iceServer.
  2450. // Chrome:
  2451. // - Creates iceServer from the url for Chrome M33 and earlier.
  2452. // - Create iceServer with stun url.
  2453. // - Chrome M28 & above uses below TURN format.
  2454. // Plugin:
  2455. // - Creates Ice Server for Plugin Browsers
  2456. // - If Stun - Create iceServer with stun url.
  2457. // - Else - Create iceServer with turn url
  2458. // - This is a WebRTC Function
  2459. createIceServer = null;
  2460. // Firefox:
  2461. // - Creates IceServers for Firefox
  2462. // - Use .url for FireFox.
  2463. // - Multiple Urls support
  2464. // Chrome:
  2465. // - Creates iceServers from the urls for Chrome M34 and above.
  2466. // - .urls is supported since Chrome M34.
  2467. // - Multiple Urls support
  2468. // Plugin:
  2469. // - Creates Ice Servers for Plugin Browsers
  2470. // - Multiple Urls support
  2471. // - This is a WebRTC Function
  2472. createIceServers = null;
  2473. //------------------------------------------------------------
  2474. //The RTCPeerConnection object.
  2475. RTCPeerConnection = null;
  2476. // Creates RTCSessionDescription object for Plugin Browsers
  2477. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  2478. RTCSessionDescription : null;
  2479. // Creates RTCIceCandidate object for Plugin Browsers
  2480. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  2481. RTCIceCandidate : null;
  2482. // Get UserMedia (only difference is the prefix).
  2483. // Code from Adam Barth.
  2484. getUserMedia = null;
  2485. // Attach a media stream to an element.
  2486. attachMediaStream = null;
  2487. // Re-attach a media stream to an element.
  2488. reattachMediaStream = null;
  2489. // Detected browser agent name. Types are:
  2490. // - 'firefox': Firefox browser.
  2491. // - 'chrome': Chrome browser.
  2492. // - 'opera': Opera browser.
  2493. // - 'safari': Safari browser.
  2494. // - 'IE' - Internet Explorer browser.
  2495. webrtcDetectedBrowser = null;
  2496. // Detected browser version.
  2497. webrtcDetectedVersion = null;
  2498. // Check for browser types and react accordingly
  2499. if (navigator.mozGetUserMedia) {
  2500. webrtcDetectedBrowser = 'firefox';
  2501. webrtcDetectedVersion = parseInt(navigator
  2502. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2503. webrtcDetectedType = 'moz';
  2504. webrtcDetectedDCSupport = 'SCTP';
  2505. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2506. AdapterJS.maybeFixConfiguration(pcConfig);
  2507. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  2508. };
  2509. // The RTCSessionDescription object.
  2510. RTCSessionDescription = mozRTCSessionDescription;
  2511. window.RTCSessionDescription = RTCSessionDescription;
  2512. // The RTCIceCandidate object.
  2513. RTCIceCandidate = mozRTCIceCandidate;
  2514. window.RTCIceCandidate = RTCIceCandidate;
  2515. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  2516. navigator.getUserMedia = window.getUserMedia;
  2517. // Shim for MediaStreamTrack.getSources.
  2518. MediaStreamTrack.getSources = function(successCb) {
  2519. setTimeout(function() {
  2520. var infos = [
  2521. { kind: 'audio', id: 'default', label:'', facing:'' },
  2522. { kind: 'video', id: 'default', label:'', facing:'' }
  2523. ];
  2524. successCb(infos);
  2525. }, 0);
  2526. };
  2527. createIceServer = function (url, username, password) {
  2528. var iceServer = null;
  2529. var url_parts = url.split(':');
  2530. if (url_parts[0].indexOf('stun') === 0) {
  2531. iceServer = { url : url };
  2532. } else if (url_parts[0].indexOf('turn') === 0) {
  2533. if (webrtcDetectedVersion < 27) {
  2534. var turn_url_parts = url.split('?');
  2535. if (turn_url_parts.length === 1 ||
  2536. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2537. iceServer = {
  2538. url : turn_url_parts[0],
  2539. credential : password,
  2540. username : username
  2541. };
  2542. }
  2543. } else {
  2544. iceServer = {
  2545. url : url,
  2546. credential : password,
  2547. username : username
  2548. };
  2549. }
  2550. }
  2551. return iceServer;
  2552. };
  2553. createIceServers = function (urls, username, password) {
  2554. var iceServers = [];
  2555. for (i = 0; i < urls.length; i++) {
  2556. var iceServer = createIceServer(urls[i], username, password);
  2557. if (iceServer !== null) {
  2558. iceServers.push(iceServer);
  2559. }
  2560. }
  2561. return iceServers;
  2562. };
  2563. attachMediaStream = function (element, stream) {
  2564. element.mozSrcObject = stream;
  2565. if (stream !== null)
  2566. element.play();
  2567. return element;
  2568. };
  2569. reattachMediaStream = function (to, from) {
  2570. to.mozSrcObject = from.mozSrcObject;
  2571. to.play();
  2572. return to;
  2573. };
  2574. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2575. if (!callback) {
  2576. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2577. ': 1 argument required, but only 0 present.');
  2578. }
  2579. return callback([]);
  2580. };
  2581. // Fake get{Video,Audio}Tracks
  2582. if (!MediaStream.prototype.getVideoTracks) {
  2583. MediaStream.prototype.getVideoTracks = function () {
  2584. return [];
  2585. };
  2586. }
  2587. if (!MediaStream.prototype.getAudioTracks) {
  2588. MediaStream.prototype.getAudioTracks = function () {
  2589. return [];
  2590. };
  2591. }
  2592. AdapterJS.maybeThroughWebRTCReady();
  2593. } else if (navigator.webkitGetUserMedia) {
  2594. webrtcDetectedBrowser = 'chrome';
  2595. webrtcDetectedType = 'webkit';
  2596. webrtcDetectedVersion = parseInt(navigator
  2597. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2598. // check if browser is opera 20+
  2599. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2600. if (checkIfOpera !== null) {
  2601. webrtcDetectedBrowser = 'opera';
  2602. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2603. }
  2604. // check browser datachannel support
  2605. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2606. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2607. webrtcDetectedDCSupport = 'SCTP';
  2608. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2609. webrtcDetectedVersion > 24) {
  2610. webrtcDetectedDCSupport = 'RTP';
  2611. } else {
  2612. webrtcDetectedDCSupport = '';
  2613. }
  2614. createIceServer = function (url, username, password) {
  2615. var iceServer = null;
  2616. var url_parts = url.split(':');
  2617. if (url_parts[0].indexOf('stun') === 0) {
  2618. iceServer = { 'url' : url };
  2619. } else if (url_parts[0].indexOf('turn') === 0) {
  2620. iceServer = {
  2621. 'url' : url,
  2622. 'credential' : password,
  2623. 'username' : username
  2624. };
  2625. }
  2626. return iceServer;
  2627. };
  2628. createIceServers = function (urls, username, password) {
  2629. var iceServers = [];
  2630. if (webrtcDetectedVersion >= 34) {
  2631. iceServers = {
  2632. 'urls' : urls,
  2633. 'credential' : password,
  2634. 'username' : username
  2635. };
  2636. } else {
  2637. for (i = 0; i < urls.length; i++) {
  2638. var iceServer = createIceServer(urls[i], username, password);
  2639. if (iceServer !== null) {
  2640. iceServers.push(iceServer);
  2641. }
  2642. }
  2643. }
  2644. return iceServers;
  2645. };
  2646. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2647. if (webrtcDetectedVersion < 34) {
  2648. AdapterJS.maybeFixConfiguration(pcConfig);
  2649. }
  2650. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2651. };
  2652. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2653. navigator.getUserMedia = window.getUserMedia;
  2654. attachMediaStream = function (element, stream) {
  2655. if (typeof element.srcObject !== 'undefined') {
  2656. element.srcObject = stream;
  2657. } else if (typeof element.mozSrcObject !== 'undefined') {
  2658. element.mozSrcObject = stream;
  2659. } else if (typeof element.src !== 'undefined') {
  2660. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2661. } else {
  2662. console.log('Error attaching stream to element.');
  2663. }
  2664. return element;
  2665. };
  2666. reattachMediaStream = function (to, from) {
  2667. to.src = from.src;
  2668. return to;
  2669. };
  2670. AdapterJS.maybeThroughWebRTCReady();
  2671. } else { // TRY TO USE PLUGIN
  2672. // IE 9 is not offering an implementation of console.log until you open a console
  2673. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2674. /* jshint -W020 */
  2675. console = {} || console;
  2676. // Implemented based on console specs from MDN
  2677. // You may override these functions
  2678. console.log = function (arg) {};
  2679. console.info = function (arg) {};
  2680. console.error = function (arg) {};
  2681. console.dir = function (arg) {};
  2682. console.exception = function (arg) {};
  2683. console.trace = function (arg) {};
  2684. console.warn = function (arg) {};
  2685. console.count = function (arg) {};
  2686. console.debug = function (arg) {};
  2687. console.count = function (arg) {};
  2688. console.time = function (arg) {};
  2689. console.timeEnd = function (arg) {};
  2690. console.group = function (arg) {};
  2691. console.groupCollapsed = function (arg) {};
  2692. console.groupEnd = function (arg) {};
  2693. /* jshint +W020 */
  2694. }
  2695. webrtcDetectedType = 'plugin';
  2696. webrtcDetectedDCSupport = 'plugin';
  2697. AdapterJS.parseWebrtcDetectedBrowser();
  2698. isIE = webrtcDetectedBrowser === 'IE';
  2699. /* jshint -W035 */
  2700. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2701. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2702. /* empty because it needs to prevent the function from running. */
  2703. }
  2704. };
  2705. /* jshint +W035 */
  2706. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2707. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2708. // Call immediately if possible
  2709. // Once the plugin is set, the code will always take this path
  2710. callback();
  2711. } else {
  2712. // otherwise start a 100ms interval
  2713. var checkPluginReadyState = setInterval(function () {
  2714. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2715. clearInterval(checkPluginReadyState);
  2716. callback();
  2717. }
  2718. }, 100);
  2719. }
  2720. };
  2721. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2722. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2723. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2724. });
  2725. };
  2726. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2727. // only inject once the page is ready
  2728. if (document.readyState !== 'complete') {
  2729. return;
  2730. }
  2731. // Prevent multiple injections
  2732. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2733. return;
  2734. }
  2735. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2736. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2737. var frag = document.createDocumentFragment();
  2738. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2739. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2740. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2741. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2742. '<param name="pluginId" value="' +
  2743. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2744. '<param name="windowless" value="false" /> ' +
  2745. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2746. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload +
  2747. '" />' +
  2748. // uncomment to be able to use virtual cams
  2749. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2750. '</object>';
  2751. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2752. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2753. }
  2754. document.body.appendChild(frag);
  2755. // Need to re-fetch the plugin
  2756. AdapterJS.WebRTCPlugin.plugin =
  2757. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2758. } else {
  2759. // Load Plugin
  2760. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2761. AdapterJS.WebRTCPlugin.plugin.id =
  2762. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2763. // IE will only start the plugin if it's ACTUALLY visible
  2764. if (isIE) {
  2765. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2766. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2767. } else { // The size of the plugin on Safari should be 0x0px
  2768. // so that the autorisation prompt is at the top
  2769. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2770. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2771. }
  2772. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2773. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2774. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2775. '<param name="pluginId" value="' +
  2776. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2777. '<param name="windowless" value="false" /> ' +
  2778. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2779. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">';
  2780. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2781. }
  2782. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2783. };
  2784. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2785. function (comName, plugName, installedCb, notInstalledCb) {
  2786. if (!isIE) {
  2787. var pluginArray = navigator.plugins;
  2788. for (var i = 0; i < pluginArray.length; i++) {
  2789. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2790. installedCb();
  2791. return;
  2792. }
  2793. }
  2794. notInstalledCb();
  2795. } else {
  2796. try {
  2797. var axo = new ActiveXObject(comName + '.' + plugName);
  2798. } catch (e) {
  2799. notInstalledCb();
  2800. return;
  2801. }
  2802. installedCb();
  2803. }
  2804. };
  2805. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2806. if (AdapterJS.WebRTCPlugin.pluginState ===
  2807. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2808. console.error("WebRTC interface has been defined already");
  2809. return;
  2810. }
  2811. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2812. AdapterJS.isDefined = function (variable) {
  2813. return variable !== null && variable !== undefined;
  2814. };
  2815. createIceServer = function (url, username, password) {
  2816. var iceServer = null;
  2817. var url_parts = url.split(':');
  2818. if (url_parts[0].indexOf('stun') === 0) {
  2819. iceServer = {
  2820. 'url' : url,
  2821. 'hasCredentials' : false
  2822. };
  2823. } else if (url_parts[0].indexOf('turn') === 0) {
  2824. iceServer = {
  2825. 'url' : url,
  2826. 'hasCredentials' : true,
  2827. 'credential' : password,
  2828. 'username' : username
  2829. };
  2830. }
  2831. return iceServer;
  2832. };
  2833. createIceServers = function (urls, username, password) {
  2834. var iceServers = [];
  2835. for (var i = 0; i < urls.length; ++i) {
  2836. iceServers.push(createIceServer(urls[i], username, password));
  2837. }
  2838. return iceServers;
  2839. };
  2840. RTCSessionDescription = function (info) {
  2841. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2842. return AdapterJS.WebRTCPlugin.plugin.
  2843. ConstructSessionDescription(info.type, info.sdp);
  2844. };
  2845. RTCPeerConnection = function (servers, constraints) {
  2846. var iceServers = null;
  2847. if (servers) {
  2848. iceServers = servers.iceServers;
  2849. for (var i = 0; i < iceServers.length; i++) {
  2850. if (iceServers[i].urls && !iceServers[i].url) {
  2851. iceServers[i].url = iceServers[i].urls;
  2852. }
  2853. iceServers[i].hasCredentials = AdapterJS.
  2854. isDefined(iceServers[i].username) &&
  2855. AdapterJS.isDefined(iceServers[i].credential);
  2856. }
  2857. }
  2858. var mandatory = (constraints && constraints.mandatory) ?
  2859. constraints.mandatory : null;
  2860. var optional = (constraints && constraints.optional) ?
  2861. constraints.optional : null;
  2862. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2863. return AdapterJS.WebRTCPlugin.plugin.
  2864. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2865. iceServers, mandatory, optional);
  2866. };
  2867. MediaStreamTrack = {};
  2868. MediaStreamTrack.getSources = function (callback) {
  2869. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2870. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2871. });
  2872. };
  2873. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2874. constraints.audio = constraints.audio || false;
  2875. constraints.video = constraints.video || false;
  2876. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2877. AdapterJS.WebRTCPlugin.plugin.
  2878. getUserMedia(constraints, successCallback, failureCallback);
  2879. });
  2880. };
  2881. window.navigator.getUserMedia = window.getUserMedia;
  2882. attachMediaStream = function (element, stream) {
  2883. if (!element || !element.parentNode) {
  2884. return;
  2885. }
  2886. var streamId
  2887. if (stream === null) {
  2888. streamId = '';
  2889. }
  2890. else {
  2891. stream.enableSoundTracks(true);
  2892. streamId = stream.id;
  2893. }
  2894. if (element.nodeName.toLowerCase() !== 'audio') {
  2895. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2896. if (!element.isWebRTCPlugin || !element.isWebRTCPlugin()) {
  2897. var frag = document.createDocumentFragment();
  2898. var temp = document.createElement('div');
  2899. var classHTML = '';
  2900. if (element.className) {
  2901. classHTML = 'class="' + element.className + '" ';
  2902. } else if (element.attributes && element.attributes['class']) {
  2903. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2904. }
  2905. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2906. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2907. '<param name="pluginId" value="' + elementId + '" /> ' +
  2908. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2909. '<param name="windowless" value="true" /> ' +
  2910. '<param name="streamId" value="' + streamId + '" /> ' +
  2911. '</object>';
  2912. while (temp.firstChild) {
  2913. frag.appendChild(temp.firstChild);
  2914. }
  2915. var height = '';
  2916. var width = '';
  2917. if (element.getBoundingClientRect) {
  2918. var rectObject = element.getBoundingClientRect();
  2919. width = rectObject.width + 'px';
  2920. height = rectObject.height + 'px';
  2921. }
  2922. else if (element.width) {
  2923. width = element.width;
  2924. height = element.height;
  2925. } else {
  2926. // TODO: What scenario could bring us here?
  2927. }
  2928. element.parentNode.insertBefore(frag, element);
  2929. frag = document.getElementById(elementId);
  2930. frag.width = width;
  2931. frag.height = height;
  2932. element.parentNode.removeChild(element);
  2933. } else {
  2934. var children = element.children;
  2935. for (var i = 0; i !== children.length; ++i) {
  2936. if (children[i].name === 'streamId') {
  2937. children[i].value = streamId;
  2938. break;
  2939. }
  2940. }
  2941. element.setStreamId(streamId);
  2942. }
  2943. var newElement = document.getElementById(elementId);
  2944. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2945. if (isIE) { // on IE the event needs to be plugged manually
  2946. newElement.attachEvent('onplaying', newElement.onplaying);
  2947. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2948. newElement._TemOnClick = function (id) {
  2949. var arg = {
  2950. srcElement : document.getElementById(id)
  2951. };
  2952. newElement.onclick(arg);
  2953. };
  2954. }
  2955. return newElement;
  2956. } else {
  2957. return element;
  2958. }
  2959. };
  2960. reattachMediaStream = function (to, from) {
  2961. var stream = null;
  2962. var children = from.children;
  2963. for (var i = 0; i !== children.length; ++i) {
  2964. if (children[i].name === 'streamId') {
  2965. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2966. stream = AdapterJS.WebRTCPlugin.plugin
  2967. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2968. break;
  2969. }
  2970. }
  2971. if (stream !== null) {
  2972. return attachMediaStream(to, stream);
  2973. } else {
  2974. console.log('Could not find the stream associated with this element');
  2975. }
  2976. };
  2977. RTCIceCandidate = function (candidate) {
  2978. if (!candidate.sdpMid) {
  2979. candidate.sdpMid = '';
  2980. }
  2981. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2982. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2983. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2984. );
  2985. };
  2986. // inject plugin
  2987. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2988. AdapterJS.WebRTCPlugin.injectPlugin();
  2989. };
  2990. // This function will be called if the plugin is needed (browser different
  2991. // from Chrome or Firefox), but the plugin is not installed.
  2992. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2993. function() {
  2994. AdapterJS.addEvent(document,
  2995. 'readystatechange',
  2996. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2997. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2998. };
  2999. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  3000. if (AdapterJS.options.hidePluginInstallPrompt) {
  3001. return;
  3002. }
  3003. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  3004. if(downloadLink) { // if download link
  3005. var popupString;
  3006. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  3007. popupString = 'This website requires you to install the ' +
  3008. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  3009. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  3010. ' WebRTC Plugin</a>' +
  3011. ' to work on this browser.';
  3012. } else { // no portal link, just print a generic explanation
  3013. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  3014. }
  3015. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  3016. } else { // no download link, just print a generic explanation
  3017. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  3018. }
  3019. };
  3020. // Try to detect the plugin and act accordingly
  3021. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3022. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3023. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3024. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  3025. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  3026. }
  3027. (function () {
  3028. 'use strict';
  3029. var baseGetUserMedia = null;
  3030. AdapterJS.TEXT.EXTENSION = {
  3031. REQUIRE_INSTALLATION_FF: 'To enable screensharing you need to install the Skylink WebRTC tools Firefox Add-on.',
  3032. REQUIRE_INSTALLATION_CHROME: 'To enable screensharing you need to install the Skylink WebRTC tools Chrome Extension.',
  3033. REQUIRE_REFRESH: 'Please refresh this page after the Skylink WebRTC tools extension has been installed.',
  3034. BUTTON_FF: 'Install Now',
  3035. BUTTON_CHROME: 'Go to Chrome Web Store'
  3036. };
  3037. var clone = function(obj) {
  3038. if (null == obj || "object" != typeof obj) return obj;
  3039. var copy = obj.constructor();
  3040. for (var attr in obj) {
  3041. if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  3042. }
  3043. return copy;
  3044. };
  3045. if (window.navigator.mozGetUserMedia) {
  3046. baseGetUserMedia = window.navigator.getUserMedia;
  3047. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  3048. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  3049. // intercepting screensharing requests
  3050. if (constraints.video.mediaSource !== 'screen' && constraints.video.mediaSource !== 'window') {
  3051. throw new Error('Only "screen" and "window" option is available as mediaSource');
  3052. }
  3053. var updatedConstraints = clone(constraints);
  3054. //constraints.video.mediaSource = constraints.video.mediaSource;
  3055. updatedConstraints.video.mozMediaSource = updatedConstraints.video.mediaSource;
  3056. // so generally, it requires for document.readyState to be completed before the getUserMedia could be invoked.
  3057. // strange but this works anyway
  3058. var checkIfReady = setInterval(function () {
  3059. if (document.readyState === 'complete') {
  3060. clearInterval(checkIfReady);
  3061. baseGetUserMedia(updatedConstraints, successCb, function (error) {
  3062. if (error.name === 'PermissionDeniedError' && window.parent.location.protocol === 'https:') {
  3063. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_FF,
  3064. AdapterJS.TEXT.EXTENSION.BUTTON_FF,
  3065. 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname, false, true);
  3066. //window.location.href = 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname;
  3067. } else {
  3068. failureCb(error);
  3069. }
  3070. });
  3071. }
  3072. }, 1);
  3073. } else { // regular GetUserMediaRequest
  3074. baseGetUserMedia(constraints, successCb, failureCb);
  3075. }
  3076. };
  3077. getUserMedia = navigator.getUserMedia;
  3078. } else if (window.navigator.webkitGetUserMedia) {
  3079. baseGetUserMedia = window.navigator.getUserMedia;
  3080. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  3081. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  3082. if (window.webrtcDetectedBrowser !== 'chrome') {
  3083. throw new Error('Current browser does not support screensharing');
  3084. }
  3085. // would be fine since no methods
  3086. var updatedConstraints = clone(constraints);
  3087. var chromeCallback = function(error, sourceId) {
  3088. if(!error) {
  3089. updatedConstraints.video.mandatory = updatedConstraints.video.mandatory || {};
  3090. updatedConstraints.video.mandatory.chromeMediaSource = 'desktop';
  3091. updatedConstraints.video.mandatory.maxWidth = window.screen.width > 1920 ? window.screen.width : 1920;
  3092. updatedConstraints.video.mandatory.maxHeight = window.screen.height > 1080 ? window.screen.height : 1080;
  3093. if (sourceId) {
  3094. updatedConstraints.video.mandatory.chromeMediaSourceId = sourceId;
  3095. }
  3096. delete updatedConstraints.video.mediaSource;
  3097. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  3098. } else {
  3099. if (error === 'permission-denied') {
  3100. throw new Error('Permission denied for screen retrieval');
  3101. } else {
  3102. throw new Error('Failed retrieving selected screen');
  3103. }
  3104. }
  3105. };
  3106. var onIFrameCallback = function (event) {
  3107. if (!event.data) {
  3108. return;
  3109. }
  3110. if (event.data.chromeMediaSourceId) {
  3111. if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
  3112. chromeCallback('permission-denied');
  3113. } else {
  3114. chromeCallback(null, event.data.chromeMediaSourceId);
  3115. }
  3116. }
  3117. if (event.data.chromeExtensionStatus) {
  3118. if (event.data.chromeExtensionStatus === 'not-installed') {
  3119. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_CHROME,
  3120. AdapterJS.TEXT.EXTENSION.BUTTON_CHROME,
  3121. event.data.data, true, true);
  3122. } else {
  3123. chromeCallback(event.data.chromeExtensionStatus, null);
  3124. }
  3125. }
  3126. // this event listener is no more needed
  3127. window.removeEventListener('message', onIFrameCallback);
  3128. };
  3129. window.addEventListener('message', onIFrameCallback);
  3130. postFrameMessage({
  3131. captureSourceId: true
  3132. });
  3133. } else {
  3134. baseGetUserMedia(constraints, successCb, failureCb);
  3135. }
  3136. };
  3137. getUserMedia = navigator.getUserMedia;
  3138. } else {
  3139. baseGetUserMedia = window.navigator.getUserMedia;
  3140. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  3141. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  3142. // would be fine since no methods
  3143. var updatedConstraints = clone(constraints);
  3144. // wait for plugin to be ready
  3145. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3146. // check if screensharing feature is available
  3147. if (!!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature &&
  3148. !!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3149. // set the constraints
  3150. updatedConstraints.video.optional = updatedConstraints.video.optional || [];
  3151. updatedConstraints.video.optional.push({
  3152. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey || 'Screensharing'
  3153. });
  3154. delete updatedConstraints.video.mediaSource;
  3155. } else {
  3156. throw new Error('Your WebRTC plugin does not support screensharing');
  3157. }
  3158. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  3159. });
  3160. } else {
  3161. baseGetUserMedia(constraints, successCb, failureCb);
  3162. }
  3163. };
  3164. getUserMedia = window.navigator.getUserMedia;
  3165. }
  3166. if (window.webrtcDetectedBrowser === 'chrome') {
  3167. var iframe = document.createElement('iframe');
  3168. iframe.onload = function() {
  3169. iframe.isLoaded = true;
  3170. };
  3171. iframe.src = 'https://cdn.temasys.com.sg/skylink/extensions/detectRTC.html';
  3172. //'https://temasys-cdn.s3.amazonaws.com/skylink/extensions/detection-script-dev/detectRTC.html';
  3173. iframe.style.display = 'none';
  3174. (document.body || document.documentElement).appendChild(iframe);
  3175. var postFrameMessage = function (object) {
  3176. object = object || {};
  3177. if (!iframe.isLoaded) {
  3178. setTimeout(function () {
  3179. iframe.contentWindow.postMessage(object, '*');
  3180. }, 100);
  3181. return;
  3182. }
  3183. iframe.contentWindow.postMessage(object, '*');
  3184. };
  3185. }
  3186. })();
  3187. },{}],17:[function(require,module,exports){
  3188. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  3189. getUserMediaWithConstraints */
  3190. /**
  3191. * Indicates that desktop stream is currently in use(for toggle purpose).
  3192. * @type {boolean}
  3193. */
  3194. var isUsingScreenStream = false;
  3195. /**
  3196. * Indicates that switch stream operation is in progress and prevent from
  3197. * triggering new events.
  3198. * @type {boolean}
  3199. */
  3200. var switchInProgress = false;
  3201. /**
  3202. * Method used to get screen sharing stream.
  3203. *
  3204. * @type {function (stream_callback, failure_callback}
  3205. */
  3206. var obtainDesktopStream = null;
  3207. /**
  3208. * Indicates whether desktop sharing extension is installed.
  3209. * @type {boolean}
  3210. */
  3211. var extInstalled = false;
  3212. /**
  3213. * Indicates whether update of desktop sharing extension is required.
  3214. * @type {boolean}
  3215. */
  3216. var extUpdateRequired = false;
  3217. var AdapterJS = require("../RTC/adapter.screenshare");
  3218. var EventEmitter = require("events");
  3219. var eventEmitter = new EventEmitter();
  3220. var DesktopSharingEventTypes
  3221. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  3222. var RTCBrowserType = require("../RTC/RTCBrowserType");
  3223. var RTCEvents = require("../../service/RTC/RTCEvents");
  3224. /**
  3225. * Method obtains desktop stream from WebRTC 'screen' source.
  3226. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  3227. */
  3228. function obtainWebRTCScreen(streamCallback, failCallback) {
  3229. APP.RTC.getUserMediaWithConstraints(
  3230. ['screen'],
  3231. streamCallback,
  3232. failCallback
  3233. );
  3234. }
  3235. /**
  3236. * Constructs inline install URL for Chrome desktop streaming extension.
  3237. * The 'chromeExtensionId' must be defined in config.js.
  3238. * @returns {string}
  3239. */
  3240. function getWebStoreInstallUrl()
  3241. {
  3242. return "https://chrome.google.com/webstore/detail/" +
  3243. config.chromeExtensionId;
  3244. }
  3245. /**
  3246. * Checks whether extension update is required.
  3247. * @param minVersion minimal required version
  3248. * @param extVersion current extension version
  3249. * @returns {boolean}
  3250. */
  3251. function isUpdateRequired(minVersion, extVersion)
  3252. {
  3253. try
  3254. {
  3255. var s1 = minVersion.split('.');
  3256. var s2 = extVersion.split('.');
  3257. var len = Math.max(s1.length, s2.length);
  3258. for (var i = 0; i < len; i++)
  3259. {
  3260. var n1 = 0,
  3261. n2 = 0;
  3262. if (i < s1.length)
  3263. n1 = parseInt(s1[i]);
  3264. if (i < s2.length)
  3265. n2 = parseInt(s2[i]);
  3266. if (isNaN(n1) || isNaN(n2))
  3267. {
  3268. return true;
  3269. }
  3270. else if (n1 !== n2)
  3271. {
  3272. return n1 > n2;
  3273. }
  3274. }
  3275. // will happen if boths version has identical numbers in
  3276. // their components (even if one of them is longer, has more components)
  3277. return false;
  3278. }
  3279. catch (e)
  3280. {
  3281. console.error("Failed to parse extension version", e);
  3282. APP.UI.messageHandler.showError("dialog.error",
  3283. "dialog.detectext");
  3284. return true;
  3285. }
  3286. }
  3287. function checkChromeExtInstalled(callback) {
  3288. if (!chrome.runtime) {
  3289. // No API, so no extension for sure
  3290. callback(false, false);
  3291. return;
  3292. }
  3293. chrome.runtime.sendMessage(
  3294. config.chromeExtensionId,
  3295. { getVersion: true },
  3296. function (response) {
  3297. if (!response || !response.version) {
  3298. // Communication failure - assume that no endpoint exists
  3299. console.warn(
  3300. "Extension not installed?: ", chrome.runtime.lastError);
  3301. callback(false, false);
  3302. return;
  3303. }
  3304. // Check installed extension version
  3305. var extVersion = response.version;
  3306. console.log('Extension version is: ' + extVersion);
  3307. var updateRequired
  3308. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  3309. callback(!updateRequired, updateRequired);
  3310. }
  3311. );
  3312. }
  3313. function doGetStreamFromExtension(streamCallback, failCallback) {
  3314. // Sends 'getStream' msg to the extension.
  3315. // Extension id must be defined in the config.
  3316. chrome.runtime.sendMessage(
  3317. config.chromeExtensionId,
  3318. { getStream: true, sources: config.desktopSharingSources },
  3319. function (response) {
  3320. if (!response) {
  3321. failCallback(chrome.runtime.lastError);
  3322. return;
  3323. }
  3324. console.log("Response from extension: " + response);
  3325. if (response.streamId) {
  3326. APP.RTC.getUserMediaWithConstraints(
  3327. ['desktop'],
  3328. function (stream) {
  3329. streamCallback(stream);
  3330. },
  3331. failCallback,
  3332. null, null, null,
  3333. response.streamId);
  3334. } else {
  3335. failCallback("Extension failed to get the stream");
  3336. }
  3337. }
  3338. );
  3339. }
  3340. /**
  3341. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  3342. * stream for returned stream token.
  3343. */
  3344. function obtainScreenFromExtension(streamCallback, failCallback) {
  3345. if (extInstalled) {
  3346. doGetStreamFromExtension(streamCallback, failCallback);
  3347. } else {
  3348. if (extUpdateRequired) {
  3349. alert(
  3350. 'Jitsi Desktop Streamer requires update. ' +
  3351. 'Changes will take effect after next Chrome restart.');
  3352. }
  3353. chrome.webstore.install(
  3354. getWebStoreInstallUrl(),
  3355. function (arg) {
  3356. console.log("Extension installed successfully", arg);
  3357. extInstalled = true;
  3358. // We need to give a moment for the endpoint to become available
  3359. window.setTimeout(function () {
  3360. doGetStreamFromExtension(streamCallback, failCallback);
  3361. }, 500);
  3362. },
  3363. function (arg) {
  3364. console.log("Failed to install the extension", arg);
  3365. failCallback(arg);
  3366. APP.UI.messageHandler.showError("dialog.error",
  3367. "dialog.failtoinstall");
  3368. }
  3369. );
  3370. }
  3371. }
  3372. /**
  3373. * Call this method to toggle desktop sharing feature.
  3374. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  3375. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  3376. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  3377. * enabled), pass any other string or nothing in order to disable this
  3378. * feature completely.
  3379. */
  3380. function setDesktopSharing(method) {
  3381. obtainDesktopStream = null;
  3382. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  3383. // care about 'method' parameter
  3384. if (RTCBrowserType.isTemasysPluginUsed()) {
  3385. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  3386. console.info("Screensharing not supported by this plugin version");
  3387. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3388. console.info(
  3389. "Screensharing not available with Temasys plugin on this site");
  3390. } else {
  3391. obtainDesktopStream = obtainWebRTCScreen;
  3392. console.info("Using Temasys plugin for desktop sharing");
  3393. }
  3394. } else if (RTCBrowserType.isChrome()) {
  3395. if (method == "ext") {
  3396. if (RTCBrowserType.getChromeVersion() >= 34) {
  3397. obtainDesktopStream = obtainScreenFromExtension;
  3398. console.info("Using Chrome extension for desktop sharing");
  3399. initChromeExtension();
  3400. } else {
  3401. console.info("Chrome extension not supported until ver 34");
  3402. }
  3403. } else if (method == "webrtc") {
  3404. obtainDesktopStream = obtainWebRTCScreen;
  3405. console.info("Using Chrome WebRTC for desktop sharing");
  3406. }
  3407. }
  3408. if (!obtainDesktopStream) {
  3409. console.info("Desktop sharing disabled");
  3410. }
  3411. }
  3412. /**
  3413. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3414. * config.js to support inline installs. Host site must be selected as main
  3415. * website of published extension.
  3416. */
  3417. function initInlineInstalls()
  3418. {
  3419. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  3420. }
  3421. function initChromeExtension() {
  3422. // Initialize Chrome extension inline installs
  3423. initInlineInstalls();
  3424. // Check if extension is installed
  3425. checkChromeExtInstalled(function (installed, updateRequired) {
  3426. extInstalled = installed;
  3427. extUpdateRequired = updateRequired;
  3428. console.info(
  3429. "Chrome extension installed: " + extInstalled +
  3430. " updateRequired: " + extUpdateRequired);
  3431. });
  3432. }
  3433. function getVideoStreamFailed(error) {
  3434. console.error("Failed to obtain the stream to switch to", error);
  3435. switchInProgress = false;
  3436. isUsingScreenStream = false;
  3437. newStreamCreated(null);
  3438. }
  3439. function getDesktopStreamFailed(error) {
  3440. console.error("Failed to obtain the stream to switch to", error);
  3441. switchInProgress = false;
  3442. }
  3443. function streamSwitchDone() {
  3444. switchInProgress = false;
  3445. eventEmitter.emit(
  3446. DesktopSharingEventTypes.SWITCHING_DONE,
  3447. isUsingScreenStream);
  3448. }
  3449. function newStreamCreated(stream)
  3450. {
  3451. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  3452. stream, isUsingScreenStream, streamSwitchDone);
  3453. }
  3454. function onEndedHandler(stream) {
  3455. if (!switchInProgress && isUsingScreenStream) {
  3456. APP.desktopsharing.toggleScreenSharing();
  3457. }
  3458. //FIXME: to be verified
  3459. if (stream.removeEventListener) {
  3460. stream.removeEventListener('ended', onEndedHandler);
  3461. } else {
  3462. stream.detachEvent('ended', onEndedHandler);
  3463. }
  3464. }
  3465. // Called when RTC finishes initialization
  3466. function onWebRtcReady() {
  3467. setDesktopSharing(config.desktopSharing);
  3468. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  3469. }
  3470. module.exports = {
  3471. isUsingScreenStream: function () {
  3472. return isUsingScreenStream;
  3473. },
  3474. /**
  3475. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  3476. * and enabled.
  3477. */
  3478. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  3479. init: function () {
  3480. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  3481. },
  3482. addListener: function (listener, type)
  3483. {
  3484. eventEmitter.on(type, listener);
  3485. },
  3486. removeListener: function (listener, type) {
  3487. eventEmitter.removeListener(type, listener);
  3488. },
  3489. /*
  3490. * Toggles screen sharing.
  3491. */
  3492. toggleScreenSharing: function () {
  3493. if (switchInProgress || !obtainDesktopStream) {
  3494. console.warn("Switch in progress or no method defined");
  3495. return;
  3496. }
  3497. switchInProgress = true;
  3498. if (!isUsingScreenStream)
  3499. {
  3500. // Switch to desktop stream
  3501. obtainDesktopStream(
  3502. function (stream) {
  3503. // We now use screen stream
  3504. isUsingScreenStream = true;
  3505. // Hook 'ended' event to restore camera
  3506. // when screen stream stops
  3507. //FIXME: to be verified
  3508. if (stream.addEventListener) {
  3509. stream.addEventListener('ended', function () {
  3510. onEndedHandler(stream);
  3511. });
  3512. } else {
  3513. stream.attachEvent('ended', function () {
  3514. onEndedHandler(stream);
  3515. });
  3516. }
  3517. newStreamCreated(stream);
  3518. },
  3519. getDesktopStreamFailed);
  3520. } else {
  3521. // Disable screen stream
  3522. APP.RTC.getUserMediaWithConstraints(
  3523. ['video'],
  3524. function (stream) {
  3525. // We are now using camera stream
  3526. isUsingScreenStream = false;
  3527. newStreamCreated(stream);
  3528. },
  3529. getVideoStreamFailed, config.resolution || '360'
  3530. );
  3531. }
  3532. }
  3533. };
  3534. },{"../../service/RTC/RTCEvents":71,"../../service/desktopsharing/DesktopSharingEventTypes":75,"../RTC/RTCBrowserType":14,"../RTC/adapter.screenshare":16,"events":77}],18:[function(require,module,exports){
  3535. function supportsLocalStorage() {
  3536. try {
  3537. return 'localStorage' in window && window.localStorage !== null;
  3538. } catch (e) {
  3539. console.log("localstorage is not supported");
  3540. return false;
  3541. }
  3542. }
  3543. function generateUniqueId() {
  3544. function _p8() {
  3545. return (Math.random().toString(16) + "000000000").substr(2, 8);
  3546. }
  3547. return _p8() + _p8() + _p8() + _p8();
  3548. }
  3549. function Settings(conferenceID) {
  3550. this.email = '';
  3551. this.displayName = '';
  3552. this.userId;
  3553. this.language = null;
  3554. this.confSettings = null;
  3555. this.conferenceID = conferenceID;
  3556. if (supportsLocalStorage()) {
  3557. if(!window.localStorage.getItem(conferenceID))
  3558. this.confSettings = {};
  3559. else
  3560. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  3561. if(!this.confSettings.jitsiMeetId) {
  3562. this.confSettings.jitsiMeetId = generateUniqueId();
  3563. console.log("generated id",
  3564. this.confSettings.jitsiMeetId);
  3565. this.save();
  3566. }
  3567. this.userId = this.confSettings.jitsiMeetId || '';
  3568. this.email = this.confSettings.email || '';
  3569. this.displayName = this.confSettings.displayname || '';
  3570. this.language = this.confSettings.language;
  3571. } else {
  3572. console.log("local storage is not supported");
  3573. this.userId = generateUniqueId();
  3574. }
  3575. }
  3576. Settings.prototype.save = function () {
  3577. if(!supportsLocalStorage())
  3578. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  3579. }
  3580. Settings.prototype.setDisplayName = function (newDisplayName) {
  3581. this.displayName = newDisplayName;
  3582. if(this.confSettings != null)
  3583. this.confSettings.displayname = displayName;
  3584. this.save();
  3585. return this.displayName;
  3586. },
  3587. Settings.prototype.setEmail = function (newEmail) {
  3588. this.email = newEmail;
  3589. if(this.confSettings != null)
  3590. this.confSettings.email = newEmail;
  3591. this.save();
  3592. return this.email;
  3593. },
  3594. Settings.prototype.getSettings = function () {
  3595. return {
  3596. email: this.email,
  3597. displayName: this.displayName,
  3598. uid: this.userId,
  3599. language: this.language
  3600. };
  3601. },
  3602. Settings.prototype.setLanguage = function (lang) {
  3603. this.language = lang;
  3604. if(this.confSettings != null)
  3605. this.confSettings.language = lang;
  3606. this.save();
  3607. }
  3608. module.exports = Settings;
  3609. },{}],19:[function(require,module,exports){
  3610. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  3611. var Moderator = require("./moderator");
  3612. var EventEmitter = require("events");
  3613. var parser = {
  3614. packet2JSON: function (packet, nodes) {
  3615. var self = this;
  3616. $(packet).children().each(function (index) {
  3617. var tagName = $(this).prop("tagName");
  3618. var node = {}
  3619. node["tagName"] = tagName;
  3620. node.attributes = {};
  3621. $($(this)[0].attributes).each(function( index, attr ) {
  3622. node.attributes[ attr.name ] = attr.value;
  3623. } );
  3624. var text = Strophe.getText($(this)[0]);
  3625. if(text)
  3626. node.value = text;
  3627. node.children = [];
  3628. nodes.push(node);
  3629. self.packet2JSON($(this), node.children);
  3630. })
  3631. },
  3632. JSON2packet: function (nodes, packet) {
  3633. for(var i = 0; i < nodes.length; i++)
  3634. {
  3635. var node = nodes[i];
  3636. if(!node || node === null){
  3637. continue;
  3638. }
  3639. packet.c(node.tagName, node.attributes);
  3640. if(node.value)
  3641. packet.t(node.value);
  3642. if(node.children)
  3643. this.JSON2packet(node.children, packet);
  3644. packet.up();
  3645. }
  3646. packet.up();
  3647. }
  3648. };
  3649. /**
  3650. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  3651. * @param pres the presence JSON
  3652. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  3653. */
  3654. function filterNodeFromPresenceJSON(pres, nodeName){
  3655. var res = [];
  3656. for(var i = 0; i < pres.length; i++)
  3657. if(pres[i].tagName === nodeName)
  3658. res.push(pres[i]);
  3659. return res;
  3660. }
  3661. function ChatRoom(connection, jid, password, XMPP, options) {
  3662. this.eventEmitter = new EventEmitter();
  3663. this.xmpp = XMPP;
  3664. this.connection = connection;
  3665. this.roomjid = Strophe.getBareJidFromJid(jid);
  3666. this.myroomjid = jid;
  3667. this.password = password;
  3668. console.info("Joined MUC as " + this.myroomjid);
  3669. this.members = {};
  3670. this.presMap = {};
  3671. this.presHandlers = {};
  3672. this.joined = false;
  3673. this.role = null;
  3674. this.focusMucJid = null;
  3675. this.bridgeIsDown = false;
  3676. this.options = options || {};
  3677. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter);
  3678. this.initPresenceMap();
  3679. this.session = null;
  3680. var self = this;
  3681. this.lastPresences = {};
  3682. }
  3683. ChatRoom.prototype.initPresenceMap = function () {
  3684. this.presMap['to'] = this.myroomjid;
  3685. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  3686. this.presMap["nodes"] = [];
  3687. this.presMap["nodes"].push( {
  3688. "tagName": "user-agent",
  3689. "value": navigator.userAgent,
  3690. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  3691. });
  3692. };
  3693. ChatRoom.prototype.join = function (password) {
  3694. if(password)
  3695. this.password = password;
  3696. this.moderator.allocateConferenceFocus(function()
  3697. {
  3698. this.sendPresence();
  3699. }.bind(this));
  3700. }
  3701. ChatRoom.prototype.sendPresence = function () {
  3702. if (!this.presMap['to']) {
  3703. // Too early to send presence - not initialized
  3704. return;
  3705. }
  3706. var pres = $pres({to: this.presMap['to'] });
  3707. pres.c('x', {xmlns: this.presMap['xns']});
  3708. if (this.password) {
  3709. pres.c('password').t(this.password).up();
  3710. }
  3711. pres.up();
  3712. // Send XEP-0115 'c' stanza that contains our capabilities info
  3713. if (this.connection.caps) {
  3714. this.connection.caps.node = this.xmpp.options.clientNode;
  3715. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  3716. }
  3717. parser.JSON2packet(this.presMap.nodes, pres);
  3718. this.connection.send(pres);
  3719. };
  3720. ChatRoom.prototype.doLeave = function () {
  3721. console.log("do leave", this.myroomjid);
  3722. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  3723. this.presMap.length = 0;
  3724. this.connection.send(pres);
  3725. };
  3726. ChatRoom.prototype.createNonAnonymousRoom = function () {
  3727. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  3728. var getForm = $iq({type: 'get', to: this.roomjid})
  3729. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  3730. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  3731. var self = this;
  3732. this.connection.sendIQ(getForm, function (form) {
  3733. if (!$(form).find(
  3734. '>query>x[xmlns="jabber:x:data"]' +
  3735. '>field[var="muc#roomconfig_whois"]').length) {
  3736. console.error('non-anonymous rooms not supported');
  3737. return;
  3738. }
  3739. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  3740. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  3741. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  3742. formSubmit.c('field', {'var': 'FORM_TYPE'})
  3743. .c('value')
  3744. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  3745. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  3746. .c('value').t('anyone').up().up();
  3747. self.connection.sendIQ(formSubmit);
  3748. }, function (error) {
  3749. console.error("Error getting room configuration form");
  3750. });
  3751. };
  3752. ChatRoom.prototype.onPresence = function (pres) {
  3753. var from = pres.getAttribute('from');
  3754. // Parse roles.
  3755. var member = {};
  3756. member.show = $(pres).find('>show').text();
  3757. member.status = $(pres).find('>status').text();
  3758. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  3759. member.affiliation = tmp.attr('affiliation');
  3760. member.role = tmp.attr('role');
  3761. // Focus recognition
  3762. member.jid = tmp.attr('jid');
  3763. member.isFocus = false;
  3764. if (member.jid
  3765. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") == 0) {
  3766. member.isFocus = true;
  3767. }
  3768. $(pres).find(">x").remove();
  3769. var nodes = [];
  3770. parser.packet2JSON(pres, nodes);
  3771. this.lastPresences[from] = nodes;
  3772. for(var i = 0; i < nodes.length; i++)
  3773. {
  3774. var node = nodes[i];
  3775. switch(node.tagName)
  3776. {
  3777. case "nick":
  3778. member.nick = node.value;
  3779. if(!member.isFocus) {
  3780. var displayName = !this.xmpp.options.displayJids
  3781. ? member.nick : Strophe.getResourceFromJid(from);
  3782. if (displayName && displayName.length > 0) {
  3783. this.eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  3784. }
  3785. console.info("Display name: " + displayName, pres);
  3786. }
  3787. break;
  3788. case "userId":
  3789. member.id = node.value;
  3790. break;
  3791. case "email":
  3792. member.email = node.value;
  3793. break;
  3794. case "bridgeIsDown":
  3795. if(!this.bridgeIsDown) {
  3796. this.bridgeIsDown = true;
  3797. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  3798. }
  3799. break;
  3800. default :
  3801. this.processNode(node, from);
  3802. }
  3803. }
  3804. if (from == this.myroomjid) {
  3805. if (member.affiliation == 'owner')
  3806. if (this.role !== member.role) {
  3807. this.role = member.role;
  3808. this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  3809. member, this.isModerator());
  3810. }
  3811. if (!this.joined) {
  3812. this.joined = true;
  3813. this.eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  3814. }
  3815. } else if (this.members[from] === undefined) {
  3816. // new participant
  3817. this.members[from] = member;
  3818. console.log('entered', from, member);
  3819. if (member.isFocus) {
  3820. this.focusMucJid = from;
  3821. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  3822. }
  3823. else {
  3824. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, member.id || member.email, member.nick);
  3825. }
  3826. } else {
  3827. // Presence update for existing participant
  3828. // Watch role change:
  3829. if (this.members[from].role != member.role) {
  3830. this.members[from].role = member.role;
  3831. this.eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  3832. member.role, member.nick);
  3833. }
  3834. }
  3835. if(!member.isFocus)
  3836. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id || member.email);
  3837. // Trigger status message update
  3838. if (member.status) {
  3839. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  3840. }
  3841. };
  3842. ChatRoom.prototype.processNode = function (node, from) {
  3843. if(this.presHandlers[node.tagName])
  3844. this.presHandlers[node.tagName](node, from);
  3845. };
  3846. ChatRoom.prototype.sendMessage = function (body, nickname) {
  3847. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  3848. msg.c('body', body).up();
  3849. if (nickname) {
  3850. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  3851. }
  3852. this.connection.send(msg);
  3853. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  3854. };
  3855. ChatRoom.prototype.setSubject = function (subject) {
  3856. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  3857. msg.c('subject', subject);
  3858. this.connection.send(msg);
  3859. console.log("topic changed to " + subject);
  3860. };
  3861. ChatRoom.prototype.onParticipantLeft = function (jid) {
  3862. delete this.lastPresences[jid];
  3863. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  3864. this.moderator.onMucMemberLeft(jid);
  3865. };
  3866. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  3867. // room destroyed ?
  3868. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  3869. '>destroy').length) {
  3870. var reason;
  3871. var reasonSelect = $(pres).find(
  3872. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  3873. '>destroy>reason');
  3874. if (reasonSelect.length) {
  3875. reason = reasonSelect.text();
  3876. }
  3877. this.xmpp.disposeConference(false);
  3878. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  3879. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(jid)];
  3880. return true;
  3881. }
  3882. // Status code 110 indicates that this notification is "self-presence".
  3883. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  3884. delete this.members[from];
  3885. this.onParticipantLeft(from);
  3886. }
  3887. // If the status code is 110 this means we're leaving and we would like
  3888. // to remove everyone else from our view, so we trigger the event.
  3889. else if (Object.keys(this.members).length > 1) {
  3890. for (var i in this.members) {
  3891. var member = this.members[i];
  3892. delete this.members[i];
  3893. this.onParticipantLeft(member);
  3894. }
  3895. }
  3896. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  3897. if (this.myroomjid === from) {
  3898. this.xmpp.disposeConference(false);
  3899. this.eventEmitter.emit(XMPPEvents.KICKED);
  3900. }
  3901. }
  3902. };
  3903. ChatRoom.prototype.onMessage = function (msg, from) {
  3904. var nick =
  3905. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  3906. .text() ||
  3907. Strophe.getResourceFromJid(from);
  3908. var txt = $(msg).find('>body').text();
  3909. var type = msg.getAttribute("type");
  3910. if (type == "error") {
  3911. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  3912. $(msg).find('>text').text(), txt);
  3913. return true;
  3914. }
  3915. var subject = $(msg).find('>subject');
  3916. if (subject.length) {
  3917. var subjectText = subject.text();
  3918. if (subjectText || subjectText == "") {
  3919. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  3920. console.log("Subject is changed to " + subjectText);
  3921. }
  3922. }
  3923. // xep-0203 delay
  3924. var stamp = $(msg).find('>delay').attr('stamp');
  3925. if (!stamp) {
  3926. // or xep-0091 delay, UTC timestamp
  3927. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  3928. if (stamp) {
  3929. // the format is CCYYMMDDThh:mm:ss
  3930. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  3931. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  3932. }
  3933. }
  3934. if (txt) {
  3935. console.log('chat', nick, txt);
  3936. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  3937. from, nick, txt, this.myroomjid, stamp);
  3938. }
  3939. }
  3940. ChatRoom.prototype.onPresenceError = function (pres, from) {
  3941. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  3942. console.log('on password required', from);
  3943. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  3944. } else if ($(pres).find(
  3945. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  3946. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  3947. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  3948. // enter the room by replying with 'not-authorized'. This would
  3949. // result in reconnection from authorized domain.
  3950. // We're either missing Jicofo/Prosody config for anonymous
  3951. // domains or something is wrong.
  3952. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  3953. } else {
  3954. console.warn('onPresError ', pres);
  3955. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  3956. }
  3957. } else {
  3958. console.warn('onPresError ', pres);
  3959. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  3960. }
  3961. };
  3962. ChatRoom.prototype.kick = function (jid) {
  3963. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  3964. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  3965. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  3966. .c('reason').t('You have been kicked.').up().up().up();
  3967. this.connection.sendIQ(
  3968. kickIQ,
  3969. function (result) {
  3970. console.log('Kick participant with jid: ', jid, result);
  3971. },
  3972. function (error) {
  3973. console.log('Kick participant error: ', error);
  3974. });
  3975. };
  3976. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  3977. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  3978. var ob = this;
  3979. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  3980. function (res) {
  3981. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  3982. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  3983. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  3984. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  3985. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  3986. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  3987. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  3988. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  3989. ob.connection.sendIQ(formsubmit,
  3990. onSuccess,
  3991. onError);
  3992. } else {
  3993. onNotSupported();
  3994. }
  3995. }, onError);
  3996. };
  3997. ChatRoom.prototype.addToPresence = function (key, values) {
  3998. values.tagName = key;
  3999. this.presMap["nodes"].push(values);
  4000. };
  4001. ChatRoom.prototype.removeFromPresence = function (key) {
  4002. for(var i = 0; i < this.presMap.nodes.length; i++)
  4003. {
  4004. if(key === this.presMap.nodes[i].tagName)
  4005. this.presMap.nodes.splice(i, 1);
  4006. }
  4007. };
  4008. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  4009. this.presHandlers[name] = handler;
  4010. }
  4011. ChatRoom.prototype.removePresenceListener = function (name) {
  4012. delete this.presHandlers[name];
  4013. }
  4014. ChatRoom.prototype.isModerator = function (jid) {
  4015. return this.role === 'moderator';
  4016. };
  4017. ChatRoom.prototype.getMemberRole = function (peerJid) {
  4018. if (this.members[peerJid]) {
  4019. return this.members[peerJid].role;
  4020. }
  4021. return null;
  4022. };
  4023. ChatRoom.prototype.setJingleSession = function(session){
  4024. this.session = session;
  4025. this.session.room = this;
  4026. };
  4027. ChatRoom.prototype.removeStream = function (stream) {
  4028. if(!this.session)
  4029. return;
  4030. this.session.peerconnection.removeStream(stream)
  4031. }
  4032. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  4033. if(this.session) {
  4034. // FIXME: will block switchInProgress on true value in case of exception
  4035. this.session.switchStreams(stream, oldStream, callback, isAudio);
  4036. } else {
  4037. // We are done immediately
  4038. console.warn("No conference handler or conference not started yet");
  4039. callback();
  4040. }
  4041. };
  4042. ChatRoom.prototype.addStream = function (stream, callback) {
  4043. if(this.session) {
  4044. // FIXME: will block switchInProgress on true value in case of exception
  4045. this.session.addStream(stream, callback);
  4046. } else {
  4047. // We are done immediately
  4048. console.warn("No conference handler or conference not started yet");
  4049. callback();
  4050. }
  4051. }
  4052. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  4053. var self = this;
  4054. var localCallback = function (mute) {
  4055. self.sendVideoInfoPresence(mute);
  4056. if(callback)
  4057. callback(mute)
  4058. };
  4059. if(this.session)
  4060. {
  4061. this.session.setVideoMute(
  4062. mute, localCallback, options);
  4063. }
  4064. else {
  4065. localCallback(mute);
  4066. }
  4067. };
  4068. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  4069. //This will be for remote streams only
  4070. // if (this.forceMuted && !mute) {
  4071. // console.info("Asking focus for unmute");
  4072. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  4073. // // FIXME: wait for result before resetting muted status
  4074. // this.forceMuted = false;
  4075. // }
  4076. return this.sendAudioInfoPresence(mute, callback);
  4077. };
  4078. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  4079. this.removeFromPresence("audiomuted");
  4080. this.addToPresence("audiomuted",
  4081. {attributes:
  4082. {"audions": "http://jitsi.org/jitmeet/audio"},
  4083. value: mute.toString()});
  4084. }
  4085. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  4086. this.addAudioInfoToPresence(mute);
  4087. if(this.connection) {
  4088. this.sendPresence();
  4089. }
  4090. if(callback)
  4091. callback();
  4092. };
  4093. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  4094. this.removeFromPresence("videomuted");
  4095. this.addToPresence("videomuted",
  4096. {attributes:
  4097. {"videons": "http://jitsi.org/jitmeet/video"},
  4098. value: mute.toString()});
  4099. }
  4100. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  4101. this.addVideoInfoToPresence(mute);
  4102. if(!this.connection)
  4103. return;
  4104. this.sendPresence();
  4105. };
  4106. ChatRoom.prototype.addListener = function(type, listener) {
  4107. this.eventEmitter.on(type, listener);
  4108. };
  4109. ChatRoom.prototype.removeListener = function (type, listener) {
  4110. this.eventEmitter.removeListener(type, listener);
  4111. };
  4112. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  4113. if(this.lastPresences[data.peerjid])
  4114. {
  4115. var pres = this.lastPresences[data.peerjid];
  4116. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  4117. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  4118. data.videomuted = ((videomuted.length > 0
  4119. && videomuted[0]
  4120. && videomuted[0]["value"] === "true")? true : false);
  4121. data.audiomuted = ((audiomuted.length > 0
  4122. && audiomuted[0]
  4123. && audiomuted[0]["value"] === "true")? true : false);
  4124. }
  4125. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  4126. }
  4127. ChatRoom.prototype.addLocalStreams = function (localStreams) {
  4128. this.session.addLocalStreams(localStreams);
  4129. }
  4130. module.exports = ChatRoom;
  4131. },{"../../service/xmpp/XMPPEvents":76,"./moderator":27,"events":77}],20:[function(require,module,exports){
  4132. /*
  4133. * JingleSession provides an API to manage a single Jingle session. We will
  4134. * have different implementations depending on the underlying interface used
  4135. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  4136. */
  4137. function JingleSession(me, sid, connection, service, eventEmitter) {
  4138. /**
  4139. * Our JID.
  4140. */
  4141. this.me = me;
  4142. /**
  4143. * The Jingle session identifier.
  4144. */
  4145. this.sid = sid;
  4146. /**
  4147. * The XMPP connection.
  4148. */
  4149. this.connection = connection;
  4150. /**
  4151. * The XMPP service.
  4152. */
  4153. this.service = service;
  4154. /**
  4155. * The event emitter.
  4156. */
  4157. this.eventEmitter = eventEmitter;
  4158. /**
  4159. * Whether to use dripping or not. Dripping is sending trickle candidates
  4160. * not one-by-one.
  4161. * Note: currently we do not support 'false'.
  4162. */
  4163. this.usedrip = true;
  4164. /**
  4165. * When dripping is used, stores ICE candidates which are to be sent.
  4166. */
  4167. this.drip_container = [];
  4168. // Media constraints. Is this WebRTC only?
  4169. this.media_constraints = null;
  4170. // ICE servers config (RTCConfiguration?).
  4171. this.ice_config = {};
  4172. // The chat room instance associated with the session.
  4173. this.room = null;
  4174. }
  4175. /**
  4176. * Prepares this object to initiate a session.
  4177. * @param peerjid the JID of the remote peer.
  4178. * @param isInitiator whether we will be the Jingle initiator.
  4179. * @param media_constraints
  4180. * @param ice_config
  4181. */
  4182. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  4183. media_constraints, ice_config) {
  4184. this.media_constraints = media_constraints;
  4185. this.ice_config = ice_config;
  4186. if (this.state !== null) {
  4187. console.error('attempt to initiate on session ' + this.sid +
  4188. 'in state ' + this.state);
  4189. return;
  4190. }
  4191. this.state = 'pending';
  4192. this.initiator = isInitiator ? this.me : peerjid;
  4193. this.responder = !isInitiator ? this.me : peerjid;
  4194. this.peerjid = peerjid;
  4195. this.doInitialize();
  4196. };
  4197. /**
  4198. * Finishes initialization.
  4199. */
  4200. JingleSession.prototype.doInitialize = function() {};
  4201. /**
  4202. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  4203. * Note: currently only used on transport-info
  4204. */
  4205. JingleSession.prototype.addIceCandidates = function(contents) {};
  4206. /**
  4207. * Handles an 'add-source' event.
  4208. *
  4209. * @param contents an array of Jingle 'content' elements.
  4210. */
  4211. JingleSession.prototype.addSources = function(contents) {};
  4212. /**
  4213. * Handles a 'remove-source' event.
  4214. *
  4215. * @param contents an array of Jingle 'content' elements.
  4216. */
  4217. JingleSession.prototype.removeSources = function(contents) {};
  4218. /**
  4219. * Terminates this Jingle session (stops sending media and closes the streams?)
  4220. */
  4221. JingleSession.prototype.terminate = function() {};
  4222. /**
  4223. * Sends a Jingle session-terminate message to the peer and terminates the
  4224. * session.
  4225. * @param reason
  4226. * @param text
  4227. */
  4228. JingleSession.prototype.sendTerminate = function(reason, text) {};
  4229. /**
  4230. * Handles an offer from the remote peer (prepares to accept a session).
  4231. * @param jingle the 'jingle' XML element.
  4232. */
  4233. JingleSession.prototype.setOffer = function(jingle) {};
  4234. /**
  4235. * Handles an answer from the remote peer (prepares to accept a session).
  4236. * @param jingle the 'jingle' XML element.
  4237. */
  4238. JingleSession.prototype.setAnswer = function(jingle) {};
  4239. module.exports = JingleSession;
  4240. },{}],21:[function(require,module,exports){
  4241. /* jshint -W117 */
  4242. var JingleSession = require("./JingleSession");
  4243. var TraceablePeerConnection = require("./TraceablePeerConnection");
  4244. var SDPDiffer = require("./SDPDiffer");
  4245. var SDPUtil = require("./SDPUtil");
  4246. var SDP = require("./SDP");
  4247. var async = require("async");
  4248. var transform = require("sdp-transform");
  4249. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  4250. var RTCBrowserType = require("../RTC/RTCBrowserType");
  4251. var SSRCReplacement = require("./LocalSSRCReplacement");
  4252. var RTC = require("../RTC/RTC");
  4253. // Jingle stuff
  4254. function JingleSessionPC(me, sid, connection, service) {
  4255. JingleSession.call(this, me, sid, connection, service);
  4256. this.initiator = null;
  4257. this.responder = null;
  4258. this.peerjid = null;
  4259. this.state = null;
  4260. this.localSDP = null;
  4261. this.remoteSDP = null;
  4262. this.relayedStreams = [];
  4263. this.usetrickle = true;
  4264. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  4265. this.hadstuncandidate = false;
  4266. this.hadturncandidate = false;
  4267. this.lasticecandidate = false;
  4268. this.statsinterval = null;
  4269. this.reason = null;
  4270. this.addssrc = [];
  4271. this.removessrc = [];
  4272. this.pendingop = null;
  4273. this.switchstreams = false;
  4274. this.wait = true;
  4275. this.localStreamsSSRC = null;
  4276. this.ssrcOwners = {};
  4277. this.ssrcVideoTypes = {};
  4278. /**
  4279. * The indicator which determines whether the (local) video has been muted
  4280. * in response to a user command in contrast to an automatic decision made
  4281. * by the application logic.
  4282. */
  4283. this.videoMuteByUser = false;
  4284. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  4285. // We start with the queue paused. We resume it when the signaling state is
  4286. // stable and the ice connection state is connected.
  4287. this.modifySourcesQueue.pause();
  4288. }
  4289. JingleSessionPC.prototype = JingleSession.prototype;
  4290. JingleSessionPC.prototype.constructor = JingleSessionPC;
  4291. JingleSessionPC.prototype.setOffer = function(offer) {
  4292. this.setRemoteDescription(offer, 'offer');
  4293. };
  4294. JingleSessionPC.prototype.setAnswer = function(answer) {
  4295. this.setRemoteDescription(answer, 'answer');
  4296. };
  4297. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  4298. var signalingState = this.peerconnection.signalingState;
  4299. var iceConnectionState = this.peerconnection.iceConnectionState;
  4300. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  4301. this.modifySourcesQueue.resume();
  4302. } else {
  4303. this.modifySourcesQueue.pause();
  4304. }
  4305. };
  4306. JingleSessionPC.prototype.doInitialize = function () {
  4307. var self = this;
  4308. this.hadstuncandidate = false;
  4309. this.hadturncandidate = false;
  4310. this.lasticecandidate = false;
  4311. this.isreconnect = false;
  4312. this.peerconnection = new TraceablePeerConnection(
  4313. this.connection.jingle.ice_config,
  4314. RTC.getPCConstraints(),
  4315. this);
  4316. this.peerconnection.onicecandidate = function (event) {
  4317. self.sendIceCandidate(event.candidate);
  4318. };
  4319. this.peerconnection.onaddstream = function (event) {
  4320. if (event.stream.id !== 'default') {
  4321. console.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  4322. self.remoteStreamAdded(event);
  4323. } else {
  4324. // This is a recvonly stream. Clients that implement Unified Plan,
  4325. // such as Firefox use recvonly "streams/channels/tracks" for
  4326. // receiving remote stream/tracks, as opposed to Plan B where there
  4327. // are only 3 channels: audio, video and data.
  4328. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  4329. }
  4330. };
  4331. this.peerconnection.onremovestream = function (event) {
  4332. // Remove the stream from remoteStreams
  4333. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  4334. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  4335. };
  4336. this.peerconnection.onsignalingstatechange = function (event) {
  4337. if (!(self && self.peerconnection)) return;
  4338. self.updateModifySourcesQueue();
  4339. };
  4340. /**
  4341. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  4342. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  4343. * RTCPeerConnection.iceConnectionState changes.
  4344. *
  4345. * @param event the event containing information about the change
  4346. */
  4347. this.peerconnection.oniceconnectionstatechange = function (event) {
  4348. if (!(self && self.peerconnection)) return;
  4349. self.updateModifySourcesQueue();
  4350. switch (self.peerconnection.iceConnectionState) {
  4351. case 'connected':
  4352. // Informs interested parties that the connection has been restored.
  4353. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  4354. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  4355. self.isreconnect = false;
  4356. break;
  4357. case 'disconnected':
  4358. self.isreconnect = true;
  4359. // Informs interested parties that the connection has been interrupted.
  4360. if (self.peerconnection.signalingState === 'stable')
  4361. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  4362. break;
  4363. case 'failed':
  4364. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4365. break;
  4366. }
  4367. onIceConnectionStateChange(self.sid, self);
  4368. };
  4369. this.peerconnection.onnegotiationneeded = function (event) {
  4370. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  4371. };
  4372. this.relayedStreams.forEach(function(stream) {
  4373. self.peerconnection.addStream(stream);
  4374. });
  4375. };
  4376. JingleSessionPC.prototype.addLocalStreams = function (localStreams) {
  4377. var self = this;
  4378. // add any local and relayed stream
  4379. localStreams.forEach(function(stream) {
  4380. self.peerconnection.addStream(stream.getOriginalStream());
  4381. });
  4382. }
  4383. function onIceConnectionStateChange(sid, session) {
  4384. switch (session.peerconnection.iceConnectionState) {
  4385. case 'checking':
  4386. session.timeChecking = (new Date()).getTime();
  4387. session.firstconnect = true;
  4388. break;
  4389. case 'completed': // on caller side
  4390. case 'connected':
  4391. if (session.firstconnect) {
  4392. session.firstconnect = false;
  4393. var metadata = {};
  4394. metadata.setupTime
  4395. = (new Date()).getTime() - session.timeChecking;
  4396. session.peerconnection.getStats(function (res) {
  4397. if(res && res.result) {
  4398. res.result().forEach(function (report) {
  4399. if (report.type == 'googCandidatePair' &&
  4400. report.stat('googActiveConnection') == 'true') {
  4401. metadata.localCandidateType
  4402. = report.stat('googLocalCandidateType');
  4403. metadata.remoteCandidateType
  4404. = report.stat('googRemoteCandidateType');
  4405. // log pair as well so we can get nice pie
  4406. // charts
  4407. metadata.candidatePair
  4408. = report.stat('googLocalCandidateType') +
  4409. ';' +
  4410. report.stat('googRemoteCandidateType');
  4411. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  4412. {
  4413. metadata.ipv6 = true;
  4414. }
  4415. }
  4416. });
  4417. }
  4418. });
  4419. }
  4420. break;
  4421. }
  4422. }
  4423. JingleSessionPC.prototype.accept = function () {
  4424. this.state = 'active';
  4425. var pranswer = this.peerconnection.localDescription;
  4426. if (!pranswer || pranswer.type != 'pranswer') {
  4427. return;
  4428. }
  4429. console.log('going from pranswer to answer');
  4430. if (this.usetrickle) {
  4431. // remove candidates already sent from session-accept
  4432. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  4433. for (var i = 0; i < lines.length; i++) {
  4434. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  4435. }
  4436. }
  4437. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  4438. // FIXME: change any inactive to sendrecv or whatever they were originally
  4439. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  4440. }
  4441. var prsdp = new SDP(pranswer.sdp);
  4442. var accept = $iq({to: this.peerjid,
  4443. type: 'set'})
  4444. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4445. action: 'session-accept',
  4446. initiator: this.initiator,
  4447. responder: this.responder,
  4448. sid: this.sid });
  4449. // FIXME why do we generate session-accept in 3 different places ?
  4450. prsdp.toJingle(
  4451. accept,
  4452. this.initiator == this.me ? 'initiator' : 'responder',
  4453. this.localStreamsSSRC);
  4454. var sdp = this.peerconnection.localDescription.sdp;
  4455. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  4456. // FIXME: change any inactive to sendrecv or whatever they were originally
  4457. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  4458. }
  4459. var self = this;
  4460. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  4461. function () {
  4462. //console.log('setLocalDescription success');
  4463. self.setLocalDescription();
  4464. SSRCReplacement.processSessionInit(accept);
  4465. self.connection.sendIQ(accept,
  4466. function () {
  4467. var ack = {};
  4468. ack.source = 'answer';
  4469. $(document).trigger('ack.jingle', [self.sid, ack]);
  4470. },
  4471. function (stanza) {
  4472. var error = ($(stanza).find('error').length) ? {
  4473. code: $(stanza).find('error').attr('code'),
  4474. reason: $(stanza).find('error :first')[0].tagName
  4475. }:{};
  4476. error.source = 'answer';
  4477. JingleSessionPC.onJingleError(self.sid, error);
  4478. },
  4479. 10000);
  4480. },
  4481. function (e) {
  4482. console.error('setLocalDescription failed', e);
  4483. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4484. }
  4485. );
  4486. };
  4487. JingleSessionPC.prototype.terminate = function (reason) {
  4488. this.state = 'ended';
  4489. this.reason = reason;
  4490. this.peerconnection.close();
  4491. if (this.statsinterval !== null) {
  4492. window.clearInterval(this.statsinterval);
  4493. this.statsinterval = null;
  4494. }
  4495. };
  4496. JingleSessionPC.prototype.active = function () {
  4497. return this.state == 'active';
  4498. };
  4499. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  4500. var self = this;
  4501. if (candidate && !this.lasticecandidate) {
  4502. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  4503. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  4504. if (!(ice && jcand)) {
  4505. console.error('failed to get ice && jcand');
  4506. return;
  4507. }
  4508. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  4509. if (jcand.type === 'srflx') {
  4510. this.hadstuncandidate = true;
  4511. } else if (jcand.type === 'relay') {
  4512. this.hadturncandidate = true;
  4513. }
  4514. if (this.usetrickle) {
  4515. if (this.usedrip) {
  4516. if (this.drip_container.length === 0) {
  4517. // start 20ms callout
  4518. window.setTimeout(function () {
  4519. if (self.drip_container.length === 0) return;
  4520. self.sendIceCandidates(self.drip_container);
  4521. self.drip_container = [];
  4522. }, 20);
  4523. }
  4524. this.drip_container.push(candidate);
  4525. return;
  4526. } else {
  4527. self.sendIceCandidate([candidate]);
  4528. }
  4529. }
  4530. } else {
  4531. //console.log('sendIceCandidate: last candidate.');
  4532. if (!this.usetrickle) {
  4533. //console.log('should send full offer now...');
  4534. //FIXME why do we generate session-accept in 3 different places ?
  4535. var init = $iq({to: this.peerjid,
  4536. type: 'set'})
  4537. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4538. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  4539. initiator: this.initiator,
  4540. sid: this.sid});
  4541. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  4542. var sendJingle = function (ssrc) {
  4543. if(!ssrc)
  4544. ssrc = {};
  4545. self.localSDP.toJingle(
  4546. init,
  4547. self.initiator == self.me ? 'initiator' : 'responder',
  4548. ssrc);
  4549. SSRCReplacement.processSessionInit(init);
  4550. self.connection.sendIQ(init,
  4551. function () {
  4552. //console.log('session initiate ack');
  4553. var ack = {};
  4554. ack.source = 'offer';
  4555. $(document).trigger('ack.jingle', [self.sid, ack]);
  4556. },
  4557. function (stanza) {
  4558. self.state = 'error';
  4559. self.peerconnection.close();
  4560. var error = ($(stanza).find('error').length) ? {
  4561. code: $(stanza).find('error').attr('code'),
  4562. reason: $(stanza).find('error :first')[0].tagName,
  4563. }:{};
  4564. error.source = 'offer';
  4565. JingleSessionPC.onJingleError(self.sid, error);
  4566. },
  4567. 10000);
  4568. };
  4569. sendJingle();
  4570. }
  4571. this.lasticecandidate = true;
  4572. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  4573. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  4574. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  4575. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  4576. }
  4577. }
  4578. };
  4579. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  4580. console.log('sendIceCandidates', candidates);
  4581. var cand = $iq({to: this.peerjid, type: 'set'})
  4582. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4583. action: 'transport-info',
  4584. initiator: this.initiator,
  4585. sid: this.sid});
  4586. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  4587. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  4588. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  4589. if (cands.length > 0) {
  4590. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  4591. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  4592. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  4593. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  4594. }).c('transport', ice);
  4595. for (var i = 0; i < cands.length; i++) {
  4596. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  4597. }
  4598. // add fingerprint
  4599. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  4600. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  4601. tmp.required = true;
  4602. cand.c(
  4603. 'fingerprint',
  4604. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  4605. .t(tmp.fingerprint);
  4606. delete tmp.fingerprint;
  4607. cand.attrs(tmp);
  4608. cand.up();
  4609. }
  4610. cand.up(); // transport
  4611. cand.up(); // content
  4612. }
  4613. }
  4614. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  4615. //console.log('was this the last candidate', this.lasticecandidate);
  4616. this.connection.sendIQ(cand,
  4617. function () {
  4618. var ack = {};
  4619. ack.source = 'transportinfo';
  4620. $(document).trigger('ack.jingle', [this.sid, ack]);
  4621. },
  4622. function (stanza) {
  4623. var error = ($(stanza).find('error').length) ? {
  4624. code: $(stanza).find('error').attr('code'),
  4625. reason: $(stanza).find('error :first')[0].tagName,
  4626. }:{};
  4627. error.source = 'transportinfo';
  4628. JingleSessionPC.onJingleError(this.sid, error);
  4629. },
  4630. 10000);
  4631. };
  4632. JingleSessionPC.prototype.sendOffer = function () {
  4633. //console.log('sendOffer...');
  4634. var self = this;
  4635. this.peerconnection.createOffer(function (sdp) {
  4636. self.createdOffer(sdp);
  4637. },
  4638. function (e) {
  4639. console.error('createOffer failed', e);
  4640. },
  4641. this.media_constraints
  4642. );
  4643. };
  4644. // FIXME createdOffer is never used in jitsi-meet
  4645. JingleSessionPC.prototype.createdOffer = function (sdp) {
  4646. //console.log('createdOffer', sdp);
  4647. var self = this;
  4648. this.localSDP = new SDP(sdp.sdp);
  4649. //this.localSDP.mangle();
  4650. var sendJingle = function () {
  4651. var init = $iq({to: this.peerjid,
  4652. type: 'set'})
  4653. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4654. action: 'session-initiate',
  4655. initiator: this.initiator,
  4656. sid: this.sid});
  4657. self.localSDP.toJingle(
  4658. init,
  4659. this.initiator == this.me ? 'initiator' : 'responder',
  4660. this.localStreamsSSRC);
  4661. SSRCReplacement.processSessionInit(init);
  4662. self.connection.sendIQ(init,
  4663. function () {
  4664. var ack = {};
  4665. ack.source = 'offer';
  4666. $(document).trigger('ack.jingle', [self.sid, ack]);
  4667. },
  4668. function (stanza) {
  4669. self.state = 'error';
  4670. self.peerconnection.close();
  4671. var error = ($(stanza).find('error').length) ? {
  4672. code: $(stanza).find('error').attr('code'),
  4673. reason: $(stanza).find('error :first')[0].tagName,
  4674. }:{};
  4675. error.source = 'offer';
  4676. JingleSessionPC.onJingleError(self.sid, error);
  4677. },
  4678. 10000);
  4679. }
  4680. sdp.sdp = this.localSDP.raw;
  4681. this.peerconnection.setLocalDescription(sdp,
  4682. function () {
  4683. if(self.usetrickle)
  4684. {
  4685. sendJingle();
  4686. }
  4687. self.setLocalDescription();
  4688. //console.log('setLocalDescription success');
  4689. },
  4690. function (e) {
  4691. console.error('setLocalDescription failed', e);
  4692. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4693. }
  4694. );
  4695. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  4696. for (var i = 0; i < cands.length; i++) {
  4697. var cand = SDPUtil.parse_icecandidate(cands[i]);
  4698. if (cand.type == 'srflx') {
  4699. this.hadstuncandidate = true;
  4700. } else if (cand.type == 'relay') {
  4701. this.hadturncandidate = true;
  4702. }
  4703. }
  4704. };
  4705. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  4706. var self = this;
  4707. $(contents).each(function (idx, content) {
  4708. var name = $(content).attr('name');
  4709. var mediaType = this.getAttribute('name');
  4710. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  4711. ssrcs.each(function () {
  4712. var ssrc = this.getAttribute('ssrc');
  4713. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  4714. function () {
  4715. var owner = this.getAttribute('owner');
  4716. self.ssrcOwners[ssrc] = owner;
  4717. }
  4718. );
  4719. });
  4720. });
  4721. };
  4722. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  4723. return this.ssrcOwners[ssrc];
  4724. };
  4725. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  4726. //console.log('setting remote description... ', desctype);
  4727. this.remoteSDP = new SDP('');
  4728. this.remoteSDP.fromJingle(elem);
  4729. this.readSsrcInfo($(elem).find(">content"));
  4730. if (this.peerconnection.remoteDescription !== null) {
  4731. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  4732. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  4733. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  4734. for (var i = 0; i < pranswer.media.length; i++) {
  4735. // make sure we have ice ufrag and pwd
  4736. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  4737. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  4738. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  4739. } else {
  4740. console.warn('no ice ufrag?');
  4741. }
  4742. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  4743. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  4744. } else {
  4745. console.warn('no ice pwd?');
  4746. }
  4747. }
  4748. // copy over candidates
  4749. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  4750. for (var j = 0; j < lines.length; j++) {
  4751. this.remoteSDP.media[i] += lines[j] + '\r\n';
  4752. }
  4753. }
  4754. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  4755. }
  4756. }
  4757. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  4758. this.peerconnection.setRemoteDescription(remotedesc,
  4759. function () {
  4760. //console.log('setRemoteDescription success');
  4761. },
  4762. function (e) {
  4763. console.error('setRemoteDescription error', e);
  4764. JingleSessionPC.onJingleFatalError(self, e);
  4765. }
  4766. );
  4767. };
  4768. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  4769. var self = this;
  4770. if (this.peerconnection.signalingState == 'closed') {
  4771. return;
  4772. }
  4773. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  4774. console.log('trickle ice candidate arriving before session accept...');
  4775. // create a PRANSWER for setRemoteDescription
  4776. if (!this.remoteSDP) {
  4777. var cobbled = 'v=0\r\n' +
  4778. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  4779. 's=-\r\n' +
  4780. 't=0 0\r\n';
  4781. // first, take some things from the local description
  4782. for (var i = 0; i < this.localSDP.media.length; i++) {
  4783. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  4784. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  4785. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  4786. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  4787. }
  4788. cobbled += 'a=inactive\r\n';
  4789. }
  4790. this.remoteSDP = new SDP(cobbled);
  4791. }
  4792. // then add things like ice and dtls from remote candidate
  4793. elem.each(function () {
  4794. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  4795. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  4796. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  4797. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  4798. var tmp = $(this).find('transport');
  4799. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  4800. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  4801. tmp = $(this).find('transport>fingerprint');
  4802. if (tmp.length) {
  4803. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  4804. } else {
  4805. console.log('no dtls fingerprint (webrtc issue #1718?)');
  4806. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  4807. }
  4808. break;
  4809. }
  4810. }
  4811. }
  4812. });
  4813. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  4814. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  4815. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  4816. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  4817. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  4818. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  4819. }).length == this.remoteSDP.media.length;
  4820. if (iscomplete) {
  4821. console.log('setting pranswer');
  4822. try {
  4823. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  4824. function() {
  4825. },
  4826. function(e) {
  4827. console.log('setRemoteDescription pranswer failed', e.toString());
  4828. });
  4829. } catch (e) {
  4830. console.error('setting pranswer failed', e);
  4831. }
  4832. } else {
  4833. //console.log('not yet setting pranswer');
  4834. }
  4835. }
  4836. // operate on each content element
  4837. elem.each(function () {
  4838. // would love to deactivate this, but firefox still requires it
  4839. var idx = -1;
  4840. var i;
  4841. for (i = 0; i < self.remoteSDP.media.length; i++) {
  4842. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  4843. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  4844. idx = i;
  4845. break;
  4846. }
  4847. }
  4848. if (idx == -1) { // fall back to localdescription
  4849. for (i = 0; i < self.localSDP.media.length; i++) {
  4850. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  4851. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  4852. idx = i;
  4853. break;
  4854. }
  4855. }
  4856. }
  4857. var name = $(this).attr('name');
  4858. // TODO: check ice-pwd and ice-ufrag?
  4859. $(this).find('transport>candidate').each(function () {
  4860. var line, candidate;
  4861. line = SDPUtil.candidateFromJingle(this);
  4862. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  4863. sdpMid: name,
  4864. candidate: line});
  4865. try {
  4866. self.peerconnection.addIceCandidate(candidate);
  4867. } catch (e) {
  4868. console.error('addIceCandidate failed', e.toString(), line);
  4869. }
  4870. });
  4871. });
  4872. };
  4873. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  4874. //console.log('createAnswer', provisional);
  4875. var self = this;
  4876. this.peerconnection.createAnswer(
  4877. function (sdp) {
  4878. self.createdAnswer(sdp, provisional);
  4879. },
  4880. function (e) {
  4881. console.error('createAnswer failed', e);
  4882. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4883. },
  4884. this.media_constraints
  4885. );
  4886. };
  4887. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  4888. //console.log('createAnswer callback');
  4889. var self = this;
  4890. this.localSDP = new SDP(sdp.sdp);
  4891. //this.localSDP.mangle();
  4892. this.usepranswer = provisional === true;
  4893. if (this.usetrickle) {
  4894. if (this.usepranswer) {
  4895. sdp.type = 'pranswer';
  4896. for (var i = 0; i < this.localSDP.media.length; i++) {
  4897. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  4898. }
  4899. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  4900. }
  4901. }
  4902. var self = this;
  4903. var sendJingle = function (ssrcs) {
  4904. // FIXME why do we generate session-accept in 3 different places ?
  4905. var accept = $iq({to: self.peerjid,
  4906. type: 'set'})
  4907. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4908. action: 'session-accept',
  4909. initiator: self.initiator,
  4910. responder: self.responder,
  4911. sid: self.sid });
  4912. self.localSDP.toJingle(
  4913. accept,
  4914. self.initiator == self.me ? 'initiator' : 'responder',
  4915. ssrcs);
  4916. SSRCReplacement.processSessionInit(accept);
  4917. self.connection.sendIQ(accept,
  4918. function () {
  4919. var ack = {};
  4920. ack.source = 'answer';
  4921. $(document).trigger('ack.jingle', [self.sid, ack]);
  4922. },
  4923. function (stanza) {
  4924. var error = ($(stanza).find('error').length) ? {
  4925. code: $(stanza).find('error').attr('code'),
  4926. reason: $(stanza).find('error :first')[0].tagName,
  4927. }:{};
  4928. error.source = 'answer';
  4929. JingleSessionPC.onJingleError(self.sid, error);
  4930. },
  4931. 10000);
  4932. }
  4933. sdp.sdp = this.localSDP.raw;
  4934. this.peerconnection.setLocalDescription(sdp,
  4935. function () {
  4936. //console.log('setLocalDescription success');
  4937. if (self.usetrickle && !self.usepranswer) {
  4938. sendJingle();
  4939. }
  4940. self.setLocalDescription();
  4941. },
  4942. function (e) {
  4943. console.error('setLocalDescription failed', e);
  4944. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4945. }
  4946. );
  4947. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  4948. for (var j = 0; j < cands.length; j++) {
  4949. var cand = SDPUtil.parse_icecandidate(cands[j]);
  4950. if (cand.type == 'srflx') {
  4951. this.hadstuncandidate = true;
  4952. } else if (cand.type == 'relay') {
  4953. this.hadturncandidate = true;
  4954. }
  4955. }
  4956. };
  4957. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  4958. var self = this,
  4959. term = $iq({to: this.peerjid,
  4960. type: 'set'})
  4961. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4962. action: 'session-terminate',
  4963. initiator: this.initiator,
  4964. sid: this.sid})
  4965. .c('reason')
  4966. .c(reason || 'success');
  4967. if (text) {
  4968. term.up().c('text').t(text);
  4969. }
  4970. this.connection.sendIQ(term,
  4971. function () {
  4972. self.peerconnection.close();
  4973. self.peerconnection = null;
  4974. self.terminate();
  4975. var ack = {};
  4976. ack.source = 'terminate';
  4977. $(document).trigger('ack.jingle', [self.sid, ack]);
  4978. },
  4979. function (stanza) {
  4980. var error = ($(stanza).find('error').length) ? {
  4981. code: $(stanza).find('error').attr('code'),
  4982. reason: $(stanza).find('error :first')[0].tagName,
  4983. }:{};
  4984. $(document).trigger('ack.jingle', [self.sid, error]);
  4985. },
  4986. 10000);
  4987. if (this.statsinterval !== null) {
  4988. window.clearInterval(this.statsinterval);
  4989. this.statsinterval = null;
  4990. }
  4991. };
  4992. JingleSessionPC.prototype.addSource = function (elem, fromJid) {
  4993. var self = this;
  4994. // FIXME: dirty waiting
  4995. if (!this.peerconnection.localDescription)
  4996. {
  4997. console.warn("addSource - localDescription not ready yet")
  4998. setTimeout(function()
  4999. {
  5000. self.addSource(elem, fromJid);
  5001. },
  5002. 200
  5003. );
  5004. return;
  5005. }
  5006. console.log('addssrc', new Date().getTime());
  5007. console.log('ice', this.peerconnection.iceConnectionState);
  5008. this.readSsrcInfo(elem);
  5009. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  5010. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  5011. $(elem).each(function (idx, content) {
  5012. var name = $(content).attr('name');
  5013. var lines = '';
  5014. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  5015. var semantics = this.getAttribute('semantics');
  5016. var ssrcs = $(this).find('>source').map(function () {
  5017. return this.getAttribute('ssrc');
  5018. }).get();
  5019. if (ssrcs.length != 0) {
  5020. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  5021. }
  5022. });
  5023. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  5024. tmp.each(function () {
  5025. var ssrc = $(this).attr('ssrc');
  5026. if(mySdp.containsSSRC(ssrc)){
  5027. /**
  5028. * This happens when multiple participants change their streams at the same time and
  5029. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  5030. * addssrc are scheduled for update IQ. See
  5031. */
  5032. console.warn("Got add stream request for my own ssrc: "+ssrc);
  5033. return;
  5034. }
  5035. if (sdp.containsSSRC(ssrc)) {
  5036. console.warn("Source-add request for existing SSRC: " + ssrc);
  5037. return;
  5038. }
  5039. $(this).find('>parameter').each(function () {
  5040. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  5041. if ($(this).attr('value') && $(this).attr('value').length)
  5042. lines += ':' + $(this).attr('value');
  5043. lines += '\r\n';
  5044. });
  5045. });
  5046. sdp.media.forEach(function(media, idx) {
  5047. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  5048. return;
  5049. sdp.media[idx] += lines;
  5050. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  5051. self.addssrc[idx] += lines;
  5052. });
  5053. sdp.raw = sdp.session + sdp.media.join('');
  5054. });
  5055. this.modifySourcesQueue.push(function() {
  5056. // When a source is added and if this is FF, a new channel is allocated
  5057. // for receiving the added source. We need to diffuse the SSRC of this
  5058. // new recvonly channel to the rest of the peers.
  5059. console.log('modify sources done');
  5060. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  5061. console.log("SDPs", mySdp, newSdp);
  5062. self.notifyMySSRCUpdate(mySdp, newSdp);
  5063. });
  5064. };
  5065. JingleSessionPC.prototype.removeSource = function (elem, fromJid) {
  5066. var self = this;
  5067. // FIXME: dirty waiting
  5068. if (!this.peerconnection.localDescription)
  5069. {
  5070. console.warn("removeSource - localDescription not ready yet")
  5071. setTimeout(function()
  5072. {
  5073. self.removeSource(elem, fromJid);
  5074. },
  5075. 200
  5076. );
  5077. return;
  5078. }
  5079. console.log('removessrc', new Date().getTime());
  5080. console.log('ice', this.peerconnection.iceConnectionState);
  5081. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  5082. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  5083. $(elem).each(function (idx, content) {
  5084. var name = $(content).attr('name');
  5085. var lines = '';
  5086. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  5087. var semantics = this.getAttribute('semantics');
  5088. var ssrcs = $(this).find('>source').map(function () {
  5089. return this.getAttribute('ssrc');
  5090. }).get();
  5091. if (ssrcs.length != 0) {
  5092. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  5093. }
  5094. });
  5095. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  5096. tmp.each(function () {
  5097. var ssrc = $(this).attr('ssrc');
  5098. // This should never happen, but can be useful for bug detection
  5099. if(mySdp.containsSSRC(ssrc)){
  5100. console.error("Got remove stream request for my own ssrc: "+ssrc);
  5101. return;
  5102. }
  5103. $(this).find('>parameter').each(function () {
  5104. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  5105. if ($(this).attr('value') && $(this).attr('value').length)
  5106. lines += ':' + $(this).attr('value');
  5107. lines += '\r\n';
  5108. });
  5109. });
  5110. sdp.media.forEach(function(media, idx) {
  5111. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  5112. return;
  5113. sdp.media[idx] += lines;
  5114. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  5115. self.removessrc[idx] += lines;
  5116. });
  5117. sdp.raw = sdp.session + sdp.media.join('');
  5118. });
  5119. this.modifySourcesQueue.push(function() {
  5120. // When a source is removed and if this is FF, the recvonly channel that
  5121. // receives the remote stream is deactivated . We need to diffuse the
  5122. // recvonly SSRC removal to the rest of the peers.
  5123. console.log('modify sources done');
  5124. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  5125. console.log("SDPs", mySdp, newSdp);
  5126. self.notifyMySSRCUpdate(mySdp, newSdp);
  5127. });
  5128. };
  5129. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  5130. var self = this;
  5131. if (this.peerconnection.signalingState == 'closed') return;
  5132. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  5133. // There is nothing to do since scheduled job might have been executed by another succeeding call
  5134. this.setLocalDescription();
  5135. if(successCallback){
  5136. successCallback();
  5137. }
  5138. queueCallback();
  5139. return;
  5140. }
  5141. // Reset switch streams flag
  5142. this.switchstreams = false;
  5143. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  5144. // add sources
  5145. this.addssrc.forEach(function(lines, idx) {
  5146. sdp.media[idx] += lines;
  5147. });
  5148. this.addssrc = [];
  5149. // remove sources
  5150. this.removessrc.forEach(function(lines, idx) {
  5151. lines = lines.split('\r\n');
  5152. lines.pop(); // remove empty last element;
  5153. lines.forEach(function(line) {
  5154. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  5155. });
  5156. });
  5157. this.removessrc = [];
  5158. sdp.raw = sdp.session + sdp.media.join('');
  5159. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  5160. function() {
  5161. if(self.signalingState == 'closed') {
  5162. console.error("createAnswer attempt on closed state");
  5163. queueCallback("createAnswer attempt on closed state");
  5164. return;
  5165. }
  5166. self.peerconnection.createAnswer(
  5167. function(modifiedAnswer) {
  5168. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  5169. if (self.pendingop !== null) {
  5170. var sdp = new SDP(modifiedAnswer.sdp);
  5171. if (sdp.media.length > 1) {
  5172. switch(self.pendingop) {
  5173. case 'mute':
  5174. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  5175. break;
  5176. case 'unmute':
  5177. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  5178. break;
  5179. }
  5180. sdp.raw = sdp.session + sdp.media.join('');
  5181. modifiedAnswer.sdp = sdp.raw;
  5182. }
  5183. self.pendingop = null;
  5184. }
  5185. // FIXME: pushing down an answer while ice connection state
  5186. // is still checking is bad...
  5187. //console.log(self.peerconnection.iceConnectionState);
  5188. // trying to work around another chrome bug
  5189. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  5190. self.peerconnection.setLocalDescription(modifiedAnswer,
  5191. function() {
  5192. //console.log('modified setLocalDescription ok');
  5193. self.setLocalDescription();
  5194. if(successCallback){
  5195. successCallback();
  5196. }
  5197. queueCallback();
  5198. },
  5199. function(error) {
  5200. console.error('modified setLocalDescription failed', error);
  5201. queueCallback(error);
  5202. }
  5203. );
  5204. },
  5205. function(error) {
  5206. console.error('modified answer failed', error);
  5207. queueCallback(error);
  5208. }
  5209. );
  5210. },
  5211. function(error) {
  5212. console.error('modify failed', error);
  5213. queueCallback(error);
  5214. }
  5215. );
  5216. };
  5217. /**
  5218. * Switches video streams.
  5219. * @param new_stream new stream that will be used as video of this session.
  5220. * @param oldStream old video stream of this session.
  5221. * @param success_callback callback executed after successful stream switch.
  5222. */
  5223. JingleSessionPC.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  5224. var self = this;
  5225. // Remember SDP to figure out added/removed SSRCs
  5226. var oldSdp = null;
  5227. if(self.peerconnection) {
  5228. if(self.peerconnection.localDescription) {
  5229. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  5230. }
  5231. self.peerconnection.removeStream(oldStream, true);
  5232. if(new_stream)
  5233. self.peerconnection.addStream(new_stream);
  5234. }
  5235. // Conference is not active
  5236. if(!oldSdp || !self.peerconnection) {
  5237. success_callback();
  5238. return;
  5239. }
  5240. self.switchstreams = true;
  5241. self.modifySourcesQueue.push(function() {
  5242. console.log('modify sources done');
  5243. success_callback();
  5244. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  5245. console.log("SDPs", oldSdp, newSdp);
  5246. self.notifyMySSRCUpdate(oldSdp, newSdp);
  5247. });
  5248. };
  5249. /**
  5250. * Adds streams.
  5251. * @param stream new stream that will be added.
  5252. * @param success_callback callback executed after successful stream addition.
  5253. */
  5254. JingleSessionPC.prototype.addStream = function (stream, callback) {
  5255. var self = this;
  5256. // Remember SDP to figure out added/removed SSRCs
  5257. var oldSdp = null;
  5258. if(this.peerconnection) {
  5259. if(this.peerconnection.localDescription) {
  5260. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  5261. }
  5262. if(stream)
  5263. this.peerconnection.addStream(stream);
  5264. }
  5265. // Conference is not active
  5266. if(!oldSdp || !this.peerconnection) {
  5267. callback();
  5268. return;
  5269. }
  5270. this.modifySourcesQueue.push(function() {
  5271. console.log('modify sources done');
  5272. callback();
  5273. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  5274. console.log("SDPs", oldSdp, newSdp);
  5275. self.notifyMySSRCUpdate(oldSdp, newSdp);
  5276. });
  5277. }
  5278. /**
  5279. * Figures out added/removed ssrcs and send update IQs.
  5280. * @param old_sdp SDP object for old description.
  5281. * @param new_sdp SDP object for new description.
  5282. */
  5283. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  5284. if (!(this.peerconnection.signalingState == 'stable' &&
  5285. this.peerconnection.iceConnectionState == 'connected')){
  5286. console.log("Too early to send updates");
  5287. return;
  5288. }
  5289. // send source-remove IQ.
  5290. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  5291. var remove = $iq({to: this.peerjid, type: 'set'})
  5292. .c('jingle', {
  5293. xmlns: 'urn:xmpp:jingle:1',
  5294. action: 'source-remove',
  5295. initiator: this.initiator,
  5296. sid: this.sid
  5297. }
  5298. );
  5299. var removed = sdpDiffer.toJingle(remove);
  5300. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  5301. // it in the current form
  5302. if (removed)
  5303. remove = SSRCReplacement.processSourceRemove(remove);
  5304. if (removed && remove) {
  5305. console.info("Sending source-remove", remove);
  5306. this.connection.sendIQ(remove,
  5307. function (res) {
  5308. console.info('got remove result', res);
  5309. },
  5310. function (err) {
  5311. console.error('got remove error', err);
  5312. }
  5313. );
  5314. } else {
  5315. console.log('removal not necessary');
  5316. }
  5317. // send source-add IQ.
  5318. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  5319. var add = $iq({to: this.peerjid, type: 'set'})
  5320. .c('jingle', {
  5321. xmlns: 'urn:xmpp:jingle:1',
  5322. action: 'source-add',
  5323. initiator: this.initiator,
  5324. sid: this.sid
  5325. }
  5326. );
  5327. var added = sdpDiffer.toJingle(add);
  5328. // Let 'source-add' IQ through the hack and see if we're allowed to send
  5329. // it in the current form
  5330. if (added)
  5331. add = SSRCReplacement.processSourceAdd(add);
  5332. if (added && add) {
  5333. console.info("Sending source-add", add);
  5334. this.connection.sendIQ(add,
  5335. function (res) {
  5336. console.info('got add result', res);
  5337. },
  5338. function (err) {
  5339. console.error('got add error', err);
  5340. }
  5341. );
  5342. } else {
  5343. console.log('addition not necessary');
  5344. }
  5345. };
  5346. /**
  5347. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  5348. *
  5349. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  5350. * tracks; otherwise, <tt>false</tt>
  5351. * @param callback a function to be invoked with <tt>mute</tt> after all video
  5352. * tracks have been enabled/disabled. The function may, optionally, return
  5353. * another function which is to be invoked after the whole mute/unmute operation
  5354. * has completed successfully.
  5355. * @param options an object which specifies optional arguments such as the
  5356. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  5357. * specifies whether the method was initiated in response to a user command (in
  5358. * contrast to an automatic decision made by the application logic)
  5359. */
  5360. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  5361. var byUser;
  5362. if (options) {
  5363. byUser = options.byUser;
  5364. if (typeof byUser === 'undefined') {
  5365. byUser = true;
  5366. }
  5367. } else {
  5368. byUser = true;
  5369. }
  5370. // The user's command to mute the (local) video takes precedence over any
  5371. // automatic decision made by the application logic.
  5372. if (byUser) {
  5373. this.videoMuteByUser = mute;
  5374. } else if (this.videoMuteByUser) {
  5375. return;
  5376. }
  5377. this.hardMuteVideo(mute);
  5378. var self = this;
  5379. var oldSdp = null;
  5380. if(self.peerconnection) {
  5381. if(self.peerconnection.localDescription) {
  5382. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  5383. }
  5384. }
  5385. this.modifySourcesQueue.push(function() {
  5386. console.log('modify sources done');
  5387. callback(mute);
  5388. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  5389. console.log("SDPs", oldSdp, newSdp);
  5390. self.notifyMySSRCUpdate(oldSdp, newSdp);
  5391. });
  5392. };
  5393. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  5394. this.pendingop = muted ? 'mute' : 'unmute';
  5395. };
  5396. JingleSessionPC.prototype.sendMute = function (muted, content) {
  5397. var info = $iq({to: this.peerjid,
  5398. type: 'set'})
  5399. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5400. action: 'session-info',
  5401. initiator: this.initiator,
  5402. sid: this.sid });
  5403. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  5404. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  5405. if (content) {
  5406. info.attrs({'name': content});
  5407. }
  5408. this.connection.send(info);
  5409. };
  5410. JingleSessionPC.prototype.sendRinging = function () {
  5411. var info = $iq({to: this.peerjid,
  5412. type: 'set'})
  5413. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5414. action: 'session-info',
  5415. initiator: this.initiator,
  5416. sid: this.sid });
  5417. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  5418. this.connection.send(info);
  5419. };
  5420. JingleSessionPC.prototype.getStats = function (interval) {
  5421. var self = this;
  5422. var recv = {audio: 0, video: 0};
  5423. var lost = {audio: 0, video: 0};
  5424. var lastrecv = {audio: 0, video: 0};
  5425. var lastlost = {audio: 0, video: 0};
  5426. var loss = {audio: 0, video: 0};
  5427. var delta = {audio: 0, video: 0};
  5428. this.statsinterval = window.setInterval(function () {
  5429. if (self && self.peerconnection && self.peerconnection.getStats) {
  5430. self.peerconnection.getStats(function (stats) {
  5431. var results = stats.result();
  5432. // TODO: there are so much statistics you can get from this..
  5433. for (var i = 0; i < results.length; ++i) {
  5434. if (results[i].type == 'ssrc') {
  5435. var packetsrecv = results[i].stat('packetsReceived');
  5436. var packetslost = results[i].stat('packetsLost');
  5437. if (packetsrecv && packetslost) {
  5438. packetsrecv = parseInt(packetsrecv, 10);
  5439. packetslost = parseInt(packetslost, 10);
  5440. if (results[i].stat('googFrameRateReceived')) {
  5441. lastlost.video = lost.video;
  5442. lastrecv.video = recv.video;
  5443. recv.video = packetsrecv;
  5444. lost.video = packetslost;
  5445. } else {
  5446. lastlost.audio = lost.audio;
  5447. lastrecv.audio = recv.audio;
  5448. recv.audio = packetsrecv;
  5449. lost.audio = packetslost;
  5450. }
  5451. }
  5452. }
  5453. }
  5454. delta.audio = recv.audio - lastrecv.audio;
  5455. delta.video = recv.video - lastrecv.video;
  5456. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  5457. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  5458. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  5459. });
  5460. }
  5461. }, interval || 3000);
  5462. return this.statsinterval;
  5463. };
  5464. JingleSessionPC.onJingleError = function (session, error)
  5465. {
  5466. console.error("Jingle error", error);
  5467. }
  5468. JingleSessionPC.onJingleFatalError = function (session, error)
  5469. {
  5470. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5471. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  5472. }
  5473. JingleSessionPC.prototype.setLocalDescription = function () {
  5474. var self = this;
  5475. var newssrcs = [];
  5476. var session = transform.parse(this.peerconnection.localDescription.sdp);
  5477. session.media.forEach(function (media) {
  5478. if (media.ssrcs != null && media.ssrcs.length > 0) {
  5479. // TODO(gp) maybe exclude FID streams?
  5480. media.ssrcs.forEach(function (ssrc) {
  5481. if (ssrc.attribute !== 'cname') {
  5482. return;
  5483. }
  5484. newssrcs.push({
  5485. 'ssrc': ssrc.id,
  5486. 'type': media.type
  5487. });
  5488. });
  5489. }
  5490. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  5491. {
  5492. newssrcs.push({
  5493. 'ssrc': self.localStreamsSSRC[media.type],
  5494. 'type': media.type
  5495. });
  5496. }
  5497. });
  5498. console.log('new ssrcs', newssrcs);
  5499. // Bind us as local SSRCs owner
  5500. if (newssrcs.length > 0) {
  5501. for (var i = 1; i <= newssrcs.length; i ++) {
  5502. var ssrc = newssrcs[i-1].ssrc;
  5503. var myJid = self.connection.emuc.myroomjid;
  5504. self.ssrcOwners[ssrc] = myJid;
  5505. }
  5506. }
  5507. }
  5508. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  5509. JingleSessionPC.prototype.sendKeyframe = function () {
  5510. var pc = this.peerconnection;
  5511. console.log('sendkeyframe', pc.iceConnectionState);
  5512. if (pc.iceConnectionState !== 'connected') return; // safe...
  5513. var self = this;
  5514. pc.setRemoteDescription(
  5515. pc.remoteDescription,
  5516. function () {
  5517. pc.createAnswer(
  5518. function (modifiedAnswer) {
  5519. pc.setLocalDescription(
  5520. modifiedAnswer,
  5521. function () {
  5522. // noop
  5523. },
  5524. function (error) {
  5525. console.log('triggerKeyframe setLocalDescription failed', error);
  5526. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  5527. }
  5528. );
  5529. },
  5530. function (error) {
  5531. console.log('triggerKeyframe createAnswer failed', error);
  5532. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  5533. }
  5534. );
  5535. },
  5536. function (error) {
  5537. console.log('triggerKeyframe setRemoteDescription failed', error);
  5538. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  5539. }
  5540. );
  5541. }
  5542. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  5543. var self = this;
  5544. var thessrc;
  5545. var streamId = RTC.getStreamID(data.stream);
  5546. // look up an associated JID for a stream id
  5547. if (!streamId) {
  5548. console.error("No stream ID for", data.stream);
  5549. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  5550. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  5551. var ssrclines
  5552. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  5553. ssrclines = ssrclines.filter(function (line) {
  5554. // NOTE(gp) previously we filtered on the mslabel, but that property
  5555. // is not always present.
  5556. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  5557. if (RTCBrowserType.isTemasysPluginUsed()) {
  5558. return ((line.indexOf('mslabel:' + streamId) !== -1));
  5559. } else {
  5560. return ((line.indexOf('msid:' + streamId) !== -1));
  5561. }
  5562. });
  5563. if (ssrclines.length) {
  5564. thessrc = ssrclines[0].substring(7).split(' ')[0];
  5565. if (!self.ssrcOwners[thessrc]) {
  5566. console.error("No SSRC owner known for: " + thessrc);
  5567. return;
  5568. }
  5569. data.peerjid = self.ssrcOwners[thessrc];
  5570. console.log('associated jid', self.ssrcOwners[thessrc]);
  5571. } else {
  5572. console.error("No SSRC lines for ", streamId);
  5573. }
  5574. }
  5575. this.room.remoteStreamAdded(data, this.sid, thessrc);
  5576. var isVideo = data.stream.getVideoTracks().length > 0;
  5577. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  5578. if (isVideo &&
  5579. data.peerjid && this.peerjid === data.peerjid &&
  5580. data.stream.getVideoTracks().length === 0 &&
  5581. RTC.localVideo.getTracks().length > 0) {
  5582. window.setTimeout(function () {
  5583. self.sendKeyframe();
  5584. }, 3000);
  5585. }
  5586. }
  5587. module.exports = JingleSessionPC;
  5588. },{"../../service/xmpp/XMPPEvents":76,"../RTC/RTC":13,"../RTC/RTCBrowserType":14,"./JingleSession":20,"./LocalSSRCReplacement":22,"./SDP":23,"./SDPDiffer":24,"./SDPUtil":25,"./TraceablePeerConnection":26,"async":34,"sdp-transform":67}],22:[function(require,module,exports){
  5589. /* global $ */
  5590. /*
  5591. Here we do modifications of local video SSRCs. There are 2 situations we have
  5592. to handle:
  5593. 1. We generate SSRC for local recvonly video stream. This is the case when we
  5594. have no local camera and it is not generated automatically, but SSRC=1 is
  5595. used implicitly. If that happens RTCP packets will be dropped by the JVB
  5596. and we won't be able to request video key frames correctly.
  5597. 2. A hack to re-use SSRC of the first video stream for any new stream created
  5598. in future. It turned out that Chrome may keep on using the SSRC of removed
  5599. video stream in RTCP even though a new one has been created. So we just
  5600. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  5601. notifications are blocked once first video SSRC is advertised to the focus.
  5602. What this hack does:
  5603. 1. Stores the SSRC of the first video stream created by
  5604. a) scanning Jingle session-accept/session-invite for existing video SSRC
  5605. b) watching for 'source-add' for new video stream if it has not been
  5606. created in step a)
  5607. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  5608. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  5609. returned to the other parts of the application.
  5610. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  5611. blocks those notifications. This makes Jicofo and all participants think
  5612. that it exists all the time even if the video stream has been removed or
  5613. replaced locally. Thanks to that there is no additional signaling activity
  5614. on video mute or when switching to the desktop stream.
  5615. */
  5616. var SDP = require('./SDP');
  5617. var RTCBrowserType = require('../RTC/RTCBrowserType');
  5618. /**
  5619. * The hack is enabled on all browsers except FF by default
  5620. * FIXME finish the hack once removeStream method is implemented in FF
  5621. * @type {boolean}
  5622. */
  5623. var isEnabled = !RTCBrowserType.isFirefox();
  5624. /**
  5625. * Stored SSRC of local video stream.
  5626. */
  5627. var localVideoSSRC;
  5628. /**
  5629. * SSRC used for recvonly video stream when we have no local camera.
  5630. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  5631. * instead of 1.
  5632. */
  5633. var localRecvOnlySSRC;
  5634. /**
  5635. * cname for <tt>localRecvOnlySSRC</tt>
  5636. */
  5637. var localRecvOnlyCName;
  5638. /**
  5639. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  5640. * from given Jingle IQ.
  5641. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  5642. * @param actionName display name of the action which will be printed in log
  5643. * messages.
  5644. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  5645. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  5646. * other SSRCs left to be signaled after removing it.
  5647. */
  5648. var filterOutSource = function (modifyIq, actionName) {
  5649. var modifyIqTree = $(modifyIq.tree());
  5650. if (!localVideoSSRC)
  5651. return modifyIqTree[0];
  5652. var videoSSRC = modifyIqTree.find(
  5653. '>jingle>content[name="video"]' +
  5654. '>description>source[ssrc="' + localVideoSSRC + '"]');
  5655. if (!videoSSRC.length) {
  5656. return modifyIqTree[0];
  5657. }
  5658. console.info(
  5659. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  5660. videoSSRC.remove();
  5661. // Check if any sources still left to be added/removed
  5662. if (modifyIqTree.find('>jingle>content>description>source').length) {
  5663. return modifyIqTree[0];
  5664. } else {
  5665. return null;
  5666. }
  5667. };
  5668. /**
  5669. * Scans given Jingle IQ for video SSRC and stores it.
  5670. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  5671. */
  5672. var storeLocalVideoSSRC = function (jingleIq) {
  5673. var videoSSRCs =
  5674. $(jingleIq.tree())
  5675. .find('>jingle>content[name="video"]>description>source');
  5676. videoSSRCs.each(function (idx, ssrcElem) {
  5677. if (localVideoSSRC)
  5678. return;
  5679. // We consider SSRC real only if it has msid attribute
  5680. // recvonly streams in FF do not have it as well as local SSRCs
  5681. // we generate for recvonly streams in Chrome
  5682. var ssrSel = $(ssrcElem);
  5683. var msid = ssrSel.find('>parameter[name="msid"]');
  5684. if (msid.length) {
  5685. var ssrcVal = ssrSel.attr('ssrc');
  5686. if (ssrcVal) {
  5687. localVideoSSRC = ssrcVal;
  5688. console.info('Stored local video SSRC' +
  5689. ' for future re-use: ' + localVideoSSRC);
  5690. }
  5691. }
  5692. });
  5693. };
  5694. /**
  5695. * Generates new SSRC for local video recvonly stream.
  5696. * FIXME what about eventual SSRC collision ?
  5697. */
  5698. function generateRecvonlySSRC() {
  5699. //
  5700. localRecvOnlySSRC =
  5701. Math.random().toString(10).substring(2, 11);
  5702. localRecvOnlyCName =
  5703. Math.random().toString(36).substring(2);
  5704. console.info(
  5705. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  5706. ", cname: " + localRecvOnlyCName);
  5707. }
  5708. var LocalSSRCReplacement = {
  5709. /**
  5710. * Method must be called before 'session-initiate' or 'session-invite' is
  5711. * sent. Scans the IQ for local video SSRC and stores it if detected.
  5712. *
  5713. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  5714. * which will be scanned for local video SSRC.
  5715. */
  5716. processSessionInit: function (sessionInit) {
  5717. if (!isEnabled)
  5718. return;
  5719. if (localVideoSSRC) {
  5720. console.error("Local SSRC stored already: " + localVideoSSRC);
  5721. return;
  5722. }
  5723. storeLocalVideoSSRC(sessionInit);
  5724. },
  5725. /**
  5726. * If we have local video SSRC stored searched given
  5727. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  5728. * with the stored one.
  5729. * @param localDescription local description object that will have local
  5730. * video SSRC replaced with the stored one
  5731. * @returns modified <tt>localDescription</tt> object.
  5732. */
  5733. mungeLocalVideoSSRC: function (localDescription) {
  5734. if (!isEnabled)
  5735. return localDescription;
  5736. if (!localDescription) {
  5737. console.warn("localDescription is null or undefined");
  5738. return localDescription;
  5739. }
  5740. // IF we have local video SSRC stored make sure it is replaced
  5741. // with old SSRC
  5742. if (localVideoSSRC) {
  5743. var newSdp = new SDP(localDescription.sdp);
  5744. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  5745. !newSdp.containsSSRC(localVideoSSRC)) {
  5746. // Get new video SSRC
  5747. var map = newSdp.getMediaSsrcMap();
  5748. var videoPart = map[1];
  5749. var videoSSRCs = videoPart.ssrcs;
  5750. var newSSRC = Object.keys(videoSSRCs)[0];
  5751. console.info(
  5752. "Replacing new video SSRC: " + newSSRC +
  5753. " with " + localVideoSSRC);
  5754. localDescription.sdp =
  5755. newSdp.raw.replace(
  5756. new RegExp('a=ssrc:' + newSSRC, 'g'),
  5757. 'a=ssrc:' + localVideoSSRC);
  5758. }
  5759. } else {
  5760. // Make sure we have any SSRC for recvonly video stream
  5761. var sdp = new SDP(localDescription.sdp);
  5762. if (sdp.media[1] && sdp.media[1].indexOf('a=ssrc:') === -1 &&
  5763. sdp.media[1].indexOf('a=recvonly') !== -1) {
  5764. if (!localRecvOnlySSRC) {
  5765. generateRecvonlySSRC();
  5766. }
  5767. console.info('No SSRC in video recvonly stream' +
  5768. ' - adding SSRC: ' + localRecvOnlySSRC);
  5769. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  5770. ' cname:' + localRecvOnlyCName + '\r\n';
  5771. localDescription.sdp = sdp.session + sdp.media.join('');
  5772. }
  5773. }
  5774. return localDescription;
  5775. },
  5776. /**
  5777. * Method must be called before 'source-add' notification is sent. In case
  5778. * we have local video SSRC advertised already it will be removed from the
  5779. * notification. If no other SSRCs are described by given IQ null will be
  5780. * returned which means that there is no point in sending the notification.
  5781. * @param sourceAdd 'source-add' Jingle IQ to be processed
  5782. * @returns modified 'source-add' IQ which can be sent to the focus or
  5783. * <tt>null</tt> if no notification shall be sent. It is no longer
  5784. * a Strophe IQ Builder instance, but DOM element tree.
  5785. */
  5786. processSourceAdd: function (sourceAdd) {
  5787. if (!isEnabled)
  5788. return sourceAdd;
  5789. if (!localVideoSSRC) {
  5790. // Store local SSRC if available
  5791. storeLocalVideoSSRC(sourceAdd);
  5792. return sourceAdd;
  5793. } else {
  5794. return filterOutSource(sourceAdd, 'source-add');
  5795. }
  5796. },
  5797. /**
  5798. * Method must be called before 'source-remove' notification is sent.
  5799. * Removes local video SSRC from the notification. If there are no other
  5800. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  5801. * means that there is no point in sending the notification.
  5802. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  5803. * @returns modified 'source-remove' IQ which can be sent to the focus or
  5804. * <tt>null</tt> if no notification shall be sent. It is no longer
  5805. * a Strophe IQ Builder instance, but DOM element tree.
  5806. */
  5807. processSourceRemove: function (sourceRemove) {
  5808. if (!isEnabled)
  5809. return sourceRemove;
  5810. return filterOutSource(sourceRemove, 'source-remove');
  5811. },
  5812. /**
  5813. * Turns the hack on or off
  5814. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  5815. * to disable it
  5816. */
  5817. setEnabled: function (enabled) {
  5818. isEnabled = enabled;
  5819. }
  5820. };
  5821. module.exports = LocalSSRCReplacement;
  5822. },{"../RTC/RTCBrowserType":14,"./SDP":23}],23:[function(require,module,exports){
  5823. /* jshint -W117 */
  5824. var SDPUtil = require("./SDPUtil");
  5825. // SDP STUFF
  5826. function SDP(sdp) {
  5827. this.media = sdp.split('\r\nm=');
  5828. for (var i = 1; i < this.media.length; i++) {
  5829. this.media[i] = 'm=' + this.media[i];
  5830. if (i != this.media.length - 1) {
  5831. this.media[i] += '\r\n';
  5832. }
  5833. }
  5834. this.session = this.media.shift() + '\r\n';
  5835. this.raw = this.session + this.media.join('');
  5836. }
  5837. /**
  5838. * Returns map of MediaChannel mapped per channel idx.
  5839. */
  5840. SDP.prototype.getMediaSsrcMap = function() {
  5841. var self = this;
  5842. var media_ssrcs = {};
  5843. var tmp;
  5844. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  5845. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  5846. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  5847. var media = {
  5848. mediaindex: mediaindex,
  5849. mid: mid,
  5850. ssrcs: {},
  5851. ssrcGroups: []
  5852. };
  5853. media_ssrcs[mediaindex] = media;
  5854. tmp.forEach(function (line) {
  5855. var linessrc = line.substring(7).split(' ')[0];
  5856. // allocate new ChannelSsrc
  5857. if(!media.ssrcs[linessrc]) {
  5858. media.ssrcs[linessrc] = {
  5859. ssrc: linessrc,
  5860. lines: []
  5861. };
  5862. }
  5863. media.ssrcs[linessrc].lines.push(line);
  5864. });
  5865. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  5866. tmp.forEach(function(line){
  5867. var semantics = line.substr(0, idx).substr(13);
  5868. var ssrcs = line.substr(14 + semantics.length).split(' ');
  5869. if (ssrcs.length != 0) {
  5870. media.ssrcGroups.push({
  5871. semantics: semantics,
  5872. ssrcs: ssrcs
  5873. });
  5874. }
  5875. });
  5876. }
  5877. return media_ssrcs;
  5878. };
  5879. /**
  5880. * Returns <tt>true</tt> if this SDP contains given SSRC.
  5881. * @param ssrc the ssrc to check.
  5882. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  5883. */
  5884. SDP.prototype.containsSSRC = function(ssrc) {
  5885. var medias = this.getMediaSsrcMap();
  5886. var contains = false;
  5887. Object.keys(medias).forEach(function(mediaindex){
  5888. var media = medias[mediaindex];
  5889. //console.log("Check", channel, ssrc);
  5890. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  5891. contains = true;
  5892. }
  5893. });
  5894. return contains;
  5895. };
  5896. // remove iSAC and CN from SDP
  5897. SDP.prototype.mangle = function () {
  5898. var i, j, mline, lines, rtpmap, newdesc;
  5899. for (i = 0; i < this.media.length; i++) {
  5900. lines = this.media[i].split('\r\n');
  5901. lines.pop(); // remove empty last element
  5902. mline = SDPUtil.parse_mline(lines.shift());
  5903. if (mline.media != 'audio')
  5904. continue;
  5905. newdesc = '';
  5906. mline.fmt.length = 0;
  5907. for (j = 0; j < lines.length; j++) {
  5908. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  5909. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  5910. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  5911. continue;
  5912. mline.fmt.push(rtpmap.id);
  5913. newdesc += lines[j] + '\r\n';
  5914. } else {
  5915. newdesc += lines[j] + '\r\n';
  5916. }
  5917. }
  5918. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  5919. this.media[i] += newdesc;
  5920. }
  5921. this.raw = this.session + this.media.join('');
  5922. };
  5923. // remove lines matching prefix from session section
  5924. SDP.prototype.removeSessionLines = function(prefix) {
  5925. var self = this;
  5926. var lines = SDPUtil.find_lines(this.session, prefix);
  5927. lines.forEach(function(line) {
  5928. self.session = self.session.replace(line + '\r\n', '');
  5929. });
  5930. this.raw = this.session + this.media.join('');
  5931. return lines;
  5932. }
  5933. // remove lines matching prefix from a media section specified by mediaindex
  5934. // TODO: non-numeric mediaindex could match mid
  5935. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  5936. var self = this;
  5937. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  5938. lines.forEach(function(line) {
  5939. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  5940. });
  5941. this.raw = this.session + this.media.join('');
  5942. return lines;
  5943. }
  5944. // add content's to a jingle element
  5945. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  5946. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  5947. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  5948. var self = this;
  5949. // new bundle plan
  5950. if (SDPUtil.find_line(this.session, 'a=group:')) {
  5951. lines = SDPUtil.find_lines(this.session, 'a=group:');
  5952. for (i = 0; i < lines.length; i++) {
  5953. tmp = lines[i].split(' ');
  5954. var semantics = tmp.shift().substr(8);
  5955. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  5956. for (j = 0; j < tmp.length; j++) {
  5957. elem.c('content', {name: tmp[j]}).up();
  5958. }
  5959. elem.up();
  5960. }
  5961. }
  5962. for (i = 0; i < this.media.length; i++) {
  5963. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  5964. if (!(mline.media === 'audio' ||
  5965. mline.media === 'video' ||
  5966. mline.media === 'application'))
  5967. {
  5968. continue;
  5969. }
  5970. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  5971. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  5972. } else {
  5973. if(ssrcs && ssrcs[mline.media])
  5974. {
  5975. ssrc = ssrcs[mline.media];
  5976. }
  5977. else
  5978. ssrc = false;
  5979. }
  5980. elem.c('content', {creator: thecreator, name: mline.media});
  5981. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  5982. // prefer identifier from a=mid if present
  5983. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  5984. elem.attrs({ name: mid });
  5985. }
  5986. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  5987. {
  5988. elem.c('description',
  5989. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  5990. media: mline.media });
  5991. if (ssrc) {
  5992. elem.attrs({ssrc: ssrc});
  5993. }
  5994. for (j = 0; j < mline.fmt.length; j++) {
  5995. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  5996. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  5997. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  5998. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  5999. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  6000. for (k = 0; k < tmp.length; k++) {
  6001. elem.c('parameter', tmp[k]).up();
  6002. }
  6003. }
  6004. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  6005. elem.up();
  6006. }
  6007. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  6008. elem.c('encryption', {required: 1});
  6009. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  6010. crypto.forEach(function(line) {
  6011. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  6012. });
  6013. elem.up(); // end of encryption
  6014. }
  6015. if (ssrc) {
  6016. // new style mapping
  6017. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  6018. // FIXME: group by ssrc and support multiple different ssrcs
  6019. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  6020. if(ssrclines.length > 0) {
  6021. ssrclines.forEach(function (line) {
  6022. idx = line.indexOf(' ');
  6023. var linessrc = line.substr(0, idx).substr(7);
  6024. if (linessrc != ssrc) {
  6025. elem.up();
  6026. ssrc = linessrc;
  6027. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  6028. }
  6029. var kv = line.substr(idx + 1);
  6030. elem.c('parameter');
  6031. if (kv.indexOf(':') == -1) {
  6032. elem.attrs({ name: kv });
  6033. } else {
  6034. var k = kv.split(':', 2)[0];
  6035. elem.attrs({ name: k });
  6036. var v = kv.split(':', 2)[1];
  6037. v = SDPUtil.filter_special_chars(v);
  6038. elem.attrs({ value: v });
  6039. }
  6040. elem.up();
  6041. });
  6042. }
  6043. else
  6044. {
  6045. elem.up();
  6046. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  6047. elem.c('parameter');
  6048. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  6049. elem.up();
  6050. var msid = null;
  6051. if(mline.media == "audio")
  6052. {
  6053. msid = APP.RTC.localAudio.getId();
  6054. }
  6055. else
  6056. {
  6057. msid = APP.RTC.localVideo.getId();
  6058. }
  6059. if(msid != null)
  6060. {
  6061. msid = SDPUtil.filter_special_chars(msid);
  6062. elem.c('parameter');
  6063. elem.attrs({name: "msid", value:msid});
  6064. elem.up();
  6065. elem.c('parameter');
  6066. elem.attrs({name: "mslabel", value:msid});
  6067. elem.up();
  6068. elem.c('parameter');
  6069. elem.attrs({name: "label", value:msid});
  6070. elem.up();
  6071. }
  6072. }
  6073. elem.up();
  6074. // XEP-0339 handle ssrc-group attributes
  6075. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  6076. ssrc_group_lines.forEach(function(line) {
  6077. idx = line.indexOf(' ');
  6078. var semantics = line.substr(0, idx).substr(13);
  6079. var ssrcs = line.substr(14 + semantics.length).split(' ');
  6080. if (ssrcs.length != 0) {
  6081. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  6082. ssrcs.forEach(function(ssrc) {
  6083. elem.c('source', { ssrc: ssrc })
  6084. .up();
  6085. });
  6086. elem.up();
  6087. }
  6088. });
  6089. }
  6090. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  6091. elem.c('rtcp-mux').up();
  6092. }
  6093. // XEP-0293 -- map a=rtcp-fb:*
  6094. this.RtcpFbToJingle(i, elem, '*');
  6095. // XEP-0294
  6096. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  6097. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  6098. for (j = 0; j < lines.length; j++) {
  6099. tmp = SDPUtil.parse_extmap(lines[j]);
  6100. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  6101. uri: tmp.uri,
  6102. id: tmp.value });
  6103. if (tmp.hasOwnProperty('direction')) {
  6104. switch (tmp.direction) {
  6105. case 'sendonly':
  6106. elem.attrs({senders: 'responder'});
  6107. break;
  6108. case 'recvonly':
  6109. elem.attrs({senders: 'initiator'});
  6110. break;
  6111. case 'sendrecv':
  6112. elem.attrs({senders: 'both'});
  6113. break;
  6114. case 'inactive':
  6115. elem.attrs({senders: 'none'});
  6116. break;
  6117. }
  6118. }
  6119. // TODO: handle params
  6120. elem.up();
  6121. }
  6122. }
  6123. elem.up(); // end of description
  6124. }
  6125. // map ice-ufrag/pwd, dtls fingerprint, candidates
  6126. this.TransportToJingle(i, elem);
  6127. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  6128. elem.attrs({senders: 'both'});
  6129. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  6130. elem.attrs({senders: 'initiator'});
  6131. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  6132. elem.attrs({senders: 'responder'});
  6133. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  6134. elem.attrs({senders: 'none'});
  6135. }
  6136. if (mline.port == '0') {
  6137. // estos hack to reject an m-line
  6138. elem.attrs({senders: 'rejected'});
  6139. }
  6140. elem.up(); // end of content
  6141. }
  6142. elem.up();
  6143. return elem;
  6144. };
  6145. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  6146. var i = mediaindex;
  6147. var tmp;
  6148. var self = this;
  6149. elem.c('transport');
  6150. // XEP-0343 DTLS/SCTP
  6151. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  6152. {
  6153. var sctpmap = SDPUtil.find_line(
  6154. this.media[i], 'a=sctpmap:', self.session);
  6155. if (sctpmap)
  6156. {
  6157. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  6158. elem.c('sctpmap',
  6159. {
  6160. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  6161. number: sctpAttrs[0], /* SCTP port */
  6162. protocol: sctpAttrs[1], /* protocol */
  6163. });
  6164. // Optional stream count attribute
  6165. if (sctpAttrs.length > 2)
  6166. elem.attrs({ streams: sctpAttrs[2]});
  6167. elem.up();
  6168. }
  6169. }
  6170. // XEP-0320
  6171. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  6172. fingerprints.forEach(function(line) {
  6173. tmp = SDPUtil.parse_fingerprint(line);
  6174. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  6175. elem.c('fingerprint').t(tmp.fingerprint);
  6176. delete tmp.fingerprint;
  6177. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  6178. if (line) {
  6179. tmp.setup = line.substr(8);
  6180. }
  6181. elem.attrs(tmp);
  6182. elem.up(); // end of fingerprint
  6183. });
  6184. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  6185. if (tmp) {
  6186. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6187. elem.attrs(tmp);
  6188. // XEP-0176
  6189. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  6190. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  6191. lines.forEach(function (line) {
  6192. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  6193. });
  6194. }
  6195. }
  6196. elem.up(); // end of transport
  6197. }
  6198. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  6199. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  6200. lines.forEach(function (line) {
  6201. var tmp = SDPUtil.parse_rtcpfb(line);
  6202. if (tmp.type == 'trr-int') {
  6203. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  6204. elem.up();
  6205. } else {
  6206. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  6207. if (tmp.params.length > 0) {
  6208. elem.attrs({'subtype': tmp.params[0]});
  6209. }
  6210. elem.up();
  6211. }
  6212. });
  6213. };
  6214. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  6215. var media = '';
  6216. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  6217. if (tmp.length) {
  6218. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  6219. if (tmp.attr('value')) {
  6220. media += tmp.attr('value');
  6221. } else {
  6222. media += '0';
  6223. }
  6224. media += '\r\n';
  6225. }
  6226. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  6227. tmp.each(function () {
  6228. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  6229. if ($(this).attr('subtype')) {
  6230. media += ' ' + $(this).attr('subtype');
  6231. }
  6232. media += '\r\n';
  6233. });
  6234. return media;
  6235. };
  6236. // construct an SDP from a jingle stanza
  6237. SDP.prototype.fromJingle = function (jingle) {
  6238. var self = this;
  6239. this.raw = 'v=0\r\n' +
  6240. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  6241. 's=-\r\n' +
  6242. 't=0 0\r\n';
  6243. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  6244. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  6245. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  6246. var contents = $(group).find('>content').map(function (idx, content) {
  6247. return content.getAttribute('name');
  6248. }).get();
  6249. if (contents.length > 0) {
  6250. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  6251. }
  6252. });
  6253. }
  6254. this.session = this.raw;
  6255. jingle.find('>content').each(function () {
  6256. var m = self.jingle2media($(this));
  6257. self.media.push(m);
  6258. });
  6259. // reconstruct msid-semantic -- apparently not necessary
  6260. /*
  6261. var msid = SDPUtil.parse_ssrc(this.raw);
  6262. if (msid.hasOwnProperty('mslabel')) {
  6263. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  6264. }
  6265. */
  6266. this.raw = this.session + this.media.join('');
  6267. };
  6268. // translate a jingle content element into an an SDP media part
  6269. SDP.prototype.jingle2media = function (content) {
  6270. var media = '',
  6271. desc = content.find('description'),
  6272. ssrc = desc.attr('ssrc'),
  6273. self = this,
  6274. tmp;
  6275. var sctp = content.find(
  6276. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  6277. tmp = { media: desc.attr('media') };
  6278. tmp.port = '1';
  6279. if (content.attr('senders') == 'rejected') {
  6280. // estos hack to reject an m-line.
  6281. tmp.port = '0';
  6282. }
  6283. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  6284. if (sctp.length)
  6285. tmp.proto = 'DTLS/SCTP';
  6286. else
  6287. tmp.proto = 'RTP/SAVPF';
  6288. } else {
  6289. tmp.proto = 'RTP/AVPF';
  6290. }
  6291. if (!sctp.length)
  6292. {
  6293. tmp.fmt = desc.find('payload-type').map(
  6294. function () { return this.getAttribute('id'); }).get();
  6295. media += SDPUtil.build_mline(tmp) + '\r\n';
  6296. }
  6297. else
  6298. {
  6299. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  6300. media += 'a=sctpmap:' + sctp.attr('number') +
  6301. ' ' + sctp.attr('protocol');
  6302. var streamCount = sctp.attr('streams');
  6303. if (streamCount)
  6304. media += ' ' + streamCount + '\r\n';
  6305. else
  6306. media += '\r\n';
  6307. }
  6308. media += 'c=IN IP4 0.0.0.0\r\n';
  6309. if (!sctp.length)
  6310. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  6311. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  6312. if (tmp.length) {
  6313. if (tmp.attr('ufrag')) {
  6314. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  6315. }
  6316. if (tmp.attr('pwd')) {
  6317. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  6318. }
  6319. tmp.find('>fingerprint').each(function () {
  6320. // FIXME: check namespace at some point
  6321. media += 'a=fingerprint:' + this.getAttribute('hash');
  6322. media += ' ' + $(this).text();
  6323. media += '\r\n';
  6324. if (this.getAttribute('setup')) {
  6325. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  6326. }
  6327. });
  6328. }
  6329. switch (content.attr('senders')) {
  6330. case 'initiator':
  6331. media += 'a=sendonly\r\n';
  6332. break;
  6333. case 'responder':
  6334. media += 'a=recvonly\r\n';
  6335. break;
  6336. case 'none':
  6337. media += 'a=inactive\r\n';
  6338. break;
  6339. case 'both':
  6340. media += 'a=sendrecv\r\n';
  6341. break;
  6342. }
  6343. media += 'a=mid:' + content.attr('name') + '\r\n';
  6344. // <description><rtcp-mux/></description>
  6345. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  6346. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  6347. if (desc.find('rtcp-mux').length) {
  6348. media += 'a=rtcp-mux\r\n';
  6349. }
  6350. if (desc.find('encryption').length) {
  6351. desc.find('encryption>crypto').each(function () {
  6352. media += 'a=crypto:' + this.getAttribute('tag');
  6353. media += ' ' + this.getAttribute('crypto-suite');
  6354. media += ' ' + this.getAttribute('key-params');
  6355. if (this.getAttribute('session-params')) {
  6356. media += ' ' + this.getAttribute('session-params');
  6357. }
  6358. media += '\r\n';
  6359. });
  6360. }
  6361. desc.find('payload-type').each(function () {
  6362. media += SDPUtil.build_rtpmap(this) + '\r\n';
  6363. if ($(this).find('>parameter').length) {
  6364. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  6365. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  6366. media += '\r\n';
  6367. }
  6368. // xep-0293
  6369. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  6370. });
  6371. // xep-0293
  6372. media += self.RtcpFbFromJingle(desc, '*');
  6373. // xep-0294
  6374. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  6375. tmp.each(function () {
  6376. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  6377. });
  6378. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  6379. media += SDPUtil.candidateFromJingle(this);
  6380. });
  6381. // XEP-0339 handle ssrc-group attributes
  6382. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6383. var semantics = this.getAttribute('semantics');
  6384. var ssrcs = $(this).find('>source').map(function() {
  6385. return this.getAttribute('ssrc');
  6386. }).get();
  6387. if (ssrcs.length != 0) {
  6388. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6389. }
  6390. });
  6391. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  6392. tmp.each(function () {
  6393. var ssrc = this.getAttribute('ssrc');
  6394. $(this).find('>parameter').each(function () {
  6395. var name = this.getAttribute('name');
  6396. var value = this.getAttribute('value');
  6397. value = SDPUtil.filter_special_chars(value);
  6398. media += 'a=ssrc:' + ssrc + ' ' + name;
  6399. if (value && value.length)
  6400. media += ':' + value;
  6401. media += '\r\n';
  6402. });
  6403. });
  6404. return media;
  6405. };
  6406. module.exports = SDP;
  6407. },{"./SDPUtil":25}],24:[function(require,module,exports){
  6408. var SDPUtil = require("./SDPUtil");
  6409. function SDPDiffer(mySDP, otherSDP) {
  6410. this.mySDP = mySDP;
  6411. this.otherSDP = otherSDP;
  6412. }
  6413. /**
  6414. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  6415. * @param otherSdp the other SDP to check ssrc with.
  6416. */
  6417. SDPDiffer.prototype.getNewMedia = function() {
  6418. // this could be useful in Array.prototype.
  6419. function arrayEquals(array) {
  6420. // if the other array is a falsy value, return
  6421. if (!array)
  6422. return false;
  6423. // compare lengths - can save a lot of time
  6424. if (this.length != array.length)
  6425. return false;
  6426. for (var i = 0, l=this.length; i < l; i++) {
  6427. // Check if we have nested arrays
  6428. if (this[i] instanceof Array && array[i] instanceof Array) {
  6429. // recurse into the nested arrays
  6430. if (!this[i].equals(array[i]))
  6431. return false;
  6432. }
  6433. else if (this[i] != array[i]) {
  6434. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  6435. return false;
  6436. }
  6437. }
  6438. return true;
  6439. }
  6440. var myMedias = this.mySDP.getMediaSsrcMap();
  6441. var othersMedias = this.otherSDP.getMediaSsrcMap();
  6442. var newMedia = {};
  6443. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  6444. var myMedia = myMedias[othersMediaIdx];
  6445. var othersMedia = othersMedias[othersMediaIdx];
  6446. if(!myMedia && othersMedia) {
  6447. // Add whole channel
  6448. newMedia[othersMediaIdx] = othersMedia;
  6449. return;
  6450. }
  6451. // Look for new ssrcs accross the channel
  6452. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  6453. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  6454. // Allocate channel if we've found ssrc that doesn't exist in our channel
  6455. if(!newMedia[othersMediaIdx]){
  6456. newMedia[othersMediaIdx] = {
  6457. mediaindex: othersMedia.mediaindex,
  6458. mid: othersMedia.mid,
  6459. ssrcs: {},
  6460. ssrcGroups: []
  6461. };
  6462. }
  6463. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  6464. }
  6465. });
  6466. // Look for new ssrc groups across the channels
  6467. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  6468. // try to match the other ssrc-group with an ssrc-group of ours
  6469. var matched = false;
  6470. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  6471. var mySsrcGroup = myMedia.ssrcGroups[i];
  6472. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  6473. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  6474. matched = true;
  6475. break;
  6476. }
  6477. }
  6478. if (!matched) {
  6479. // Allocate channel if we've found an ssrc-group that doesn't
  6480. // exist in our channel
  6481. if(!newMedia[othersMediaIdx]){
  6482. newMedia[othersMediaIdx] = {
  6483. mediaindex: othersMedia.mediaindex,
  6484. mid: othersMedia.mid,
  6485. ssrcs: {},
  6486. ssrcGroups: []
  6487. };
  6488. }
  6489. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  6490. }
  6491. });
  6492. });
  6493. return newMedia;
  6494. };
  6495. /**
  6496. * Sends SSRC update IQ.
  6497. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  6498. * @param sid session identifier that will be put into the IQ.
  6499. * @param initiator initiator identifier.
  6500. * @param toJid destination Jid
  6501. * @param isAdd indicates if this is remove or add operation.
  6502. */
  6503. SDPDiffer.prototype.toJingle = function(modify) {
  6504. var sdpMediaSsrcs = this.getNewMedia();
  6505. var self = this;
  6506. // FIXME: only announce video ssrcs since we mix audio and dont need
  6507. // the audio ssrcs therefore
  6508. var modified = false;
  6509. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  6510. modified = true;
  6511. var media = sdpMediaSsrcs[mediaindex];
  6512. modify.c('content', {name: media.mid});
  6513. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  6514. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  6515. // generate sources from lines
  6516. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  6517. var mediaSsrc = media.ssrcs[ssrcNum];
  6518. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  6519. modify.attrs({ssrc: mediaSsrc.ssrc});
  6520. // iterate over ssrc lines
  6521. mediaSsrc.lines.forEach(function (line) {
  6522. var idx = line.indexOf(' ');
  6523. var kv = line.substr(idx + 1);
  6524. modify.c('parameter');
  6525. if (kv.indexOf(':') == -1) {
  6526. modify.attrs({ name: kv });
  6527. } else {
  6528. var nv = kv.split(':', 2);
  6529. var name = nv[0];
  6530. var value = SDPUtil.filter_special_chars(nv[1]);
  6531. modify.attrs({ name: name });
  6532. modify.attrs({ value: value });
  6533. }
  6534. modify.up(); // end of parameter
  6535. });
  6536. modify.up(); // end of source
  6537. });
  6538. // generate source groups from lines
  6539. media.ssrcGroups.forEach(function(ssrcGroup) {
  6540. if (ssrcGroup.ssrcs.length != 0) {
  6541. modify.c('ssrc-group', {
  6542. semantics: ssrcGroup.semantics,
  6543. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  6544. });
  6545. ssrcGroup.ssrcs.forEach(function (ssrc) {
  6546. modify.c('source', { ssrc: ssrc })
  6547. .up(); // end of source
  6548. });
  6549. modify.up(); // end of ssrc-group
  6550. }
  6551. });
  6552. modify.up(); // end of description
  6553. modify.up(); // end of content
  6554. });
  6555. return modified;
  6556. };
  6557. module.exports = SDPDiffer;
  6558. },{"./SDPUtil":25}],25:[function(require,module,exports){
  6559. SDPUtil = {
  6560. filter_special_chars: function (text) {
  6561. return text.replace(/[\\\/\{,\}\+]/g, "");
  6562. },
  6563. iceparams: function (mediadesc, sessiondesc) {
  6564. var data = null;
  6565. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  6566. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  6567. data = {
  6568. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  6569. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  6570. };
  6571. }
  6572. return data;
  6573. },
  6574. parse_iceufrag: function (line) {
  6575. return line.substring(12);
  6576. },
  6577. build_iceufrag: function (frag) {
  6578. return 'a=ice-ufrag:' + frag;
  6579. },
  6580. parse_icepwd: function (line) {
  6581. return line.substring(10);
  6582. },
  6583. build_icepwd: function (pwd) {
  6584. return 'a=ice-pwd:' + pwd;
  6585. },
  6586. parse_mid: function (line) {
  6587. return line.substring(6);
  6588. },
  6589. parse_mline: function (line) {
  6590. var parts = line.substring(2).split(' '),
  6591. data = {};
  6592. data.media = parts.shift();
  6593. data.port = parts.shift();
  6594. data.proto = parts.shift();
  6595. if (parts[parts.length - 1] === '') { // trailing whitespace
  6596. parts.pop();
  6597. }
  6598. data.fmt = parts;
  6599. return data;
  6600. },
  6601. build_mline: function (mline) {
  6602. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  6603. },
  6604. parse_rtpmap: function (line) {
  6605. var parts = line.substring(9).split(' '),
  6606. data = {};
  6607. data.id = parts.shift();
  6608. parts = parts[0].split('/');
  6609. data.name = parts.shift();
  6610. data.clockrate = parts.shift();
  6611. data.channels = parts.length ? parts.shift() : '1';
  6612. return data;
  6613. },
  6614. /**
  6615. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  6616. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  6617. * @returns [SCTP port number, protocol, streams]
  6618. */
  6619. parse_sctpmap: function (line)
  6620. {
  6621. var parts = line.substring(10).split(' ');
  6622. var sctpPort = parts[0];
  6623. var protocol = parts[1];
  6624. // Stream count is optional
  6625. var streamCount = parts.length > 2 ? parts[2] : null;
  6626. return [sctpPort, protocol, streamCount];// SCTP port
  6627. },
  6628. build_rtpmap: function (el) {
  6629. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  6630. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  6631. line += '/' + el.getAttribute('channels');
  6632. }
  6633. return line;
  6634. },
  6635. parse_crypto: function (line) {
  6636. var parts = line.substring(9).split(' '),
  6637. data = {};
  6638. data.tag = parts.shift();
  6639. data['crypto-suite'] = parts.shift();
  6640. data['key-params'] = parts.shift();
  6641. if (parts.length) {
  6642. data['session-params'] = parts.join(' ');
  6643. }
  6644. return data;
  6645. },
  6646. parse_fingerprint: function (line) { // RFC 4572
  6647. var parts = line.substring(14).split(' '),
  6648. data = {};
  6649. data.hash = parts.shift();
  6650. data.fingerprint = parts.shift();
  6651. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  6652. return data;
  6653. },
  6654. parse_fmtp: function (line) {
  6655. var parts = line.split(' '),
  6656. i, key, value,
  6657. data = [];
  6658. parts.shift();
  6659. parts = parts.join(' ').split(';');
  6660. for (i = 0; i < parts.length; i++) {
  6661. key = parts[i].split('=')[0];
  6662. while (key.length && key[0] == ' ') {
  6663. key = key.substring(1);
  6664. }
  6665. value = parts[i].split('=')[1];
  6666. if (key && value) {
  6667. data.push({name: key, value: value});
  6668. } else if (key) {
  6669. // rfc 4733 (DTMF) style stuff
  6670. data.push({name: '', value: key});
  6671. }
  6672. }
  6673. return data;
  6674. },
  6675. parse_icecandidate: function (line) {
  6676. var candidate = {},
  6677. elems = line.split(' ');
  6678. candidate.foundation = elems[0].substring(12);
  6679. candidate.component = elems[1];
  6680. candidate.protocol = elems[2].toLowerCase();
  6681. candidate.priority = elems[3];
  6682. candidate.ip = elems[4];
  6683. candidate.port = elems[5];
  6684. // elems[6] => "typ"
  6685. candidate.type = elems[7];
  6686. candidate.generation = 0; // default value, may be overwritten below
  6687. for (var i = 8; i < elems.length; i += 2) {
  6688. switch (elems[i]) {
  6689. case 'raddr':
  6690. candidate['rel-addr'] = elems[i + 1];
  6691. break;
  6692. case 'rport':
  6693. candidate['rel-port'] = elems[i + 1];
  6694. break;
  6695. case 'generation':
  6696. candidate.generation = elems[i + 1];
  6697. break;
  6698. case 'tcptype':
  6699. candidate.tcptype = elems[i + 1];
  6700. break;
  6701. default: // TODO
  6702. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  6703. }
  6704. }
  6705. candidate.network = '1';
  6706. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  6707. return candidate;
  6708. },
  6709. build_icecandidate: function (cand) {
  6710. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  6711. line += ' ';
  6712. switch (cand.type) {
  6713. case 'srflx':
  6714. case 'prflx':
  6715. case 'relay':
  6716. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  6717. line += 'raddr';
  6718. line += ' ';
  6719. line += cand['rel-addr'];
  6720. line += ' ';
  6721. line += 'rport';
  6722. line += ' ';
  6723. line += cand['rel-port'];
  6724. line += ' ';
  6725. }
  6726. break;
  6727. }
  6728. if (cand.hasOwnAttribute('tcptype')) {
  6729. line += 'tcptype';
  6730. line += ' ';
  6731. line += cand.tcptype;
  6732. line += ' ';
  6733. }
  6734. line += 'generation';
  6735. line += ' ';
  6736. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  6737. return line;
  6738. },
  6739. parse_ssrc: function (desc) {
  6740. // proprietary mapping of a=ssrc lines
  6741. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  6742. // and parse according to that
  6743. var lines = desc.split('\r\n'),
  6744. data = {};
  6745. for (var i = 0; i < lines.length; i++) {
  6746. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  6747. var idx = lines[i].indexOf(' ');
  6748. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  6749. }
  6750. }
  6751. return data;
  6752. },
  6753. parse_rtcpfb: function (line) {
  6754. var parts = line.substr(10).split(' ');
  6755. var data = {};
  6756. data.pt = parts.shift();
  6757. data.type = parts.shift();
  6758. data.params = parts;
  6759. return data;
  6760. },
  6761. parse_extmap: function (line) {
  6762. var parts = line.substr(9).split(' ');
  6763. var data = {};
  6764. data.value = parts.shift();
  6765. if (data.value.indexOf('/') != -1) {
  6766. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  6767. data.value = data.value.substr(0, data.value.indexOf('/'));
  6768. } else {
  6769. data.direction = 'both';
  6770. }
  6771. data.uri = parts.shift();
  6772. data.params = parts;
  6773. return data;
  6774. },
  6775. find_line: function (haystack, needle, sessionpart) {
  6776. var lines = haystack.split('\r\n');
  6777. for (var i = 0; i < lines.length; i++) {
  6778. if (lines[i].substring(0, needle.length) == needle) {
  6779. return lines[i];
  6780. }
  6781. }
  6782. if (!sessionpart) {
  6783. return false;
  6784. }
  6785. // search session part
  6786. lines = sessionpart.split('\r\n');
  6787. for (var j = 0; j < lines.length; j++) {
  6788. if (lines[j].substring(0, needle.length) == needle) {
  6789. return lines[j];
  6790. }
  6791. }
  6792. return false;
  6793. },
  6794. find_lines: function (haystack, needle, sessionpart) {
  6795. var lines = haystack.split('\r\n'),
  6796. needles = [];
  6797. for (var i = 0; i < lines.length; i++) {
  6798. if (lines[i].substring(0, needle.length) == needle)
  6799. needles.push(lines[i]);
  6800. }
  6801. if (needles.length || !sessionpart) {
  6802. return needles;
  6803. }
  6804. // search session part
  6805. lines = sessionpart.split('\r\n');
  6806. for (var j = 0; j < lines.length; j++) {
  6807. if (lines[j].substring(0, needle.length) == needle) {
  6808. needles.push(lines[j]);
  6809. }
  6810. }
  6811. return needles;
  6812. },
  6813. candidateToJingle: function (line) {
  6814. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  6815. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  6816. if (line.indexOf('candidate:') === 0) {
  6817. line = 'a=' + line;
  6818. } else if (line.substring(0, 12) != 'a=candidate:') {
  6819. console.log('parseCandidate called with a line that is not a candidate line');
  6820. console.log(line);
  6821. return null;
  6822. }
  6823. if (line.substring(line.length - 2) == '\r\n') // chomp it
  6824. line = line.substring(0, line.length - 2);
  6825. var candidate = {},
  6826. elems = line.split(' '),
  6827. i;
  6828. if (elems[6] != 'typ') {
  6829. console.log('did not find typ in the right place');
  6830. console.log(line);
  6831. return null;
  6832. }
  6833. candidate.foundation = elems[0].substring(12);
  6834. candidate.component = elems[1];
  6835. candidate.protocol = elems[2].toLowerCase();
  6836. candidate.priority = elems[3];
  6837. candidate.ip = elems[4];
  6838. candidate.port = elems[5];
  6839. // elems[6] => "typ"
  6840. candidate.type = elems[7];
  6841. candidate.generation = '0'; // default, may be overwritten below
  6842. for (i = 8; i < elems.length; i += 2) {
  6843. switch (elems[i]) {
  6844. case 'raddr':
  6845. candidate['rel-addr'] = elems[i + 1];
  6846. break;
  6847. case 'rport':
  6848. candidate['rel-port'] = elems[i + 1];
  6849. break;
  6850. case 'generation':
  6851. candidate.generation = elems[i + 1];
  6852. break;
  6853. case 'tcptype':
  6854. candidate.tcptype = elems[i + 1];
  6855. break;
  6856. default: // TODO
  6857. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  6858. }
  6859. }
  6860. candidate.network = '1';
  6861. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  6862. return candidate;
  6863. },
  6864. candidateFromJingle: function (cand) {
  6865. var line = 'a=candidate:';
  6866. line += cand.getAttribute('foundation');
  6867. line += ' ';
  6868. line += cand.getAttribute('component');
  6869. line += ' ';
  6870. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  6871. line += ' ';
  6872. line += cand.getAttribute('priority');
  6873. line += ' ';
  6874. line += cand.getAttribute('ip');
  6875. line += ' ';
  6876. line += cand.getAttribute('port');
  6877. line += ' ';
  6878. line += 'typ';
  6879. line += ' ' + cand.getAttribute('type');
  6880. line += ' ';
  6881. switch (cand.getAttribute('type')) {
  6882. case 'srflx':
  6883. case 'prflx':
  6884. case 'relay':
  6885. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  6886. line += 'raddr';
  6887. line += ' ';
  6888. line += cand.getAttribute('rel-addr');
  6889. line += ' ';
  6890. line += 'rport';
  6891. line += ' ';
  6892. line += cand.getAttribute('rel-port');
  6893. line += ' ';
  6894. }
  6895. break;
  6896. }
  6897. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  6898. line += 'tcptype';
  6899. line += ' ';
  6900. line += cand.getAttribute('tcptype');
  6901. line += ' ';
  6902. }
  6903. line += 'generation';
  6904. line += ' ';
  6905. line += cand.getAttribute('generation') || '0';
  6906. return line + '\r\n';
  6907. }
  6908. };
  6909. module.exports = SDPUtil;
  6910. },{}],26:[function(require,module,exports){
  6911. var RTC = require('../RTC/RTC');
  6912. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  6913. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  6914. var SSRCReplacement = require("./LocalSSRCReplacement");
  6915. function TraceablePeerConnection(ice_config, constraints, session) {
  6916. var self = this;
  6917. this.session = session;
  6918. var RTCPeerConnectionType = null;
  6919. if (RTCBrowserType.isFirefox()) {
  6920. RTCPeerConnectionType = mozRTCPeerConnection;
  6921. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  6922. RTCPeerConnectionType = RTCPeerConnection;
  6923. } else {
  6924. RTCPeerConnectionType = webkitRTCPeerConnection;
  6925. }
  6926. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  6927. this.updateLog = [];
  6928. this.stats = {};
  6929. this.statsinterval = null;
  6930. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  6931. var Interop = require('sdp-interop').Interop;
  6932. this.interop = new Interop();
  6933. var Simulcast = require('sdp-simulcast');
  6934. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  6935. // override as desired
  6936. this.trace = function (what, info) {
  6937. /*console.warn('WTRACE', what, info);
  6938. if (info && RTCBrowserType.isIExplorer()) {
  6939. if (info.length > 1024) {
  6940. console.warn('WTRACE', what, info.substr(1024));
  6941. }
  6942. if (info.length > 2048) {
  6943. console.warn('WTRACE', what, info.substr(2048));
  6944. }
  6945. }*/
  6946. self.updateLog.push({
  6947. time: new Date(),
  6948. type: what,
  6949. value: info || ""
  6950. });
  6951. };
  6952. this.onicecandidate = null;
  6953. this.peerconnection.onicecandidate = function (event) {
  6954. // FIXME: this causes stack overflow with Temasys Plugin
  6955. if (!RTCBrowserType.isTemasysPluginUsed())
  6956. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  6957. if (self.onicecandidate !== null) {
  6958. self.onicecandidate(event);
  6959. }
  6960. };
  6961. this.onaddstream = null;
  6962. this.peerconnection.onaddstream = function (event) {
  6963. self.trace('onaddstream', event.stream.id);
  6964. if (self.onaddstream !== null) {
  6965. self.onaddstream(event);
  6966. }
  6967. };
  6968. this.onremovestream = null;
  6969. this.peerconnection.onremovestream = function (event) {
  6970. self.trace('onremovestream', event.stream.id);
  6971. if (self.onremovestream !== null) {
  6972. self.onremovestream(event);
  6973. }
  6974. };
  6975. this.onsignalingstatechange = null;
  6976. this.peerconnection.onsignalingstatechange = function (event) {
  6977. self.trace('onsignalingstatechange', self.signalingState);
  6978. if (self.onsignalingstatechange !== null) {
  6979. self.onsignalingstatechange(event);
  6980. }
  6981. };
  6982. this.oniceconnectionstatechange = null;
  6983. this.peerconnection.oniceconnectionstatechange = function (event) {
  6984. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  6985. if (self.oniceconnectionstatechange !== null) {
  6986. self.oniceconnectionstatechange(event);
  6987. }
  6988. };
  6989. this.onnegotiationneeded = null;
  6990. this.peerconnection.onnegotiationneeded = function (event) {
  6991. self.trace('onnegotiationneeded');
  6992. if (self.onnegotiationneeded !== null) {
  6993. self.onnegotiationneeded(event);
  6994. }
  6995. };
  6996. self.ondatachannel = null;
  6997. this.peerconnection.ondatachannel = function (event) {
  6998. self.trace('ondatachannel', event);
  6999. if (self.ondatachannel !== null) {
  7000. self.ondatachannel(event);
  7001. }
  7002. };
  7003. // XXX: do all non-firefox browsers which we support also support this?
  7004. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  7005. this.statsinterval = window.setInterval(function() {
  7006. self.peerconnection.getStats(function(stats) {
  7007. var results = stats.result();
  7008. var now = new Date();
  7009. for (var i = 0; i < results.length; ++i) {
  7010. results[i].names().forEach(function (name) {
  7011. var id = results[i].id + '-' + name;
  7012. if (!self.stats[id]) {
  7013. self.stats[id] = {
  7014. startTime: now,
  7015. endTime: now,
  7016. values: [],
  7017. times: []
  7018. };
  7019. }
  7020. self.stats[id].values.push(results[i].stat(name));
  7021. self.stats[id].times.push(now.getTime());
  7022. if (self.stats[id].values.length > self.maxstats) {
  7023. self.stats[id].values.shift();
  7024. self.stats[id].times.shift();
  7025. }
  7026. self.stats[id].endTime = now;
  7027. });
  7028. }
  7029. });
  7030. }, 1000);
  7031. }
  7032. }
  7033. /**
  7034. * Returns a string representation of a SessionDescription object.
  7035. */
  7036. var dumpSDP = function(description) {
  7037. if (typeof description === 'undefined' || description == null) {
  7038. return '';
  7039. }
  7040. return 'type: ' + description.type + '\r\n' + description.sdp;
  7041. };
  7042. /**
  7043. * Takes a SessionDescription object and returns a "normalized" version.
  7044. * Currently it only takes care of ordering the a=ssrc lines.
  7045. */
  7046. var normalizePlanB = function(desc) {
  7047. if (typeof desc !== 'object' || desc === null ||
  7048. typeof desc.sdp !== 'string') {
  7049. console.warn('An empty description was passed as an argument.');
  7050. return desc;
  7051. }
  7052. var transform = require('sdp-transform');
  7053. var session = transform.parse(desc.sdp);
  7054. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  7055. Array.isArray(session.media)) {
  7056. session.media.forEach(function (mLine) {
  7057. // Chrome appears to be picky about the order in which a=ssrc lines
  7058. // are listed in an m-line when rtx is enabled (and thus there are
  7059. // a=ssrc-group lines with FID semantics). Specifically if we have
  7060. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  7061. // the "a=ssrc:S1" lines, SRD fails.
  7062. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  7063. // first.
  7064. var firstSsrcs = [];
  7065. var newSsrcLines = [];
  7066. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  7067. mLine.ssrcGroups.forEach(function (group) {
  7068. if (typeof group.semantics !== 'undefined' &&
  7069. group.semantics === 'FID') {
  7070. if (typeof group.ssrcs !== 'undefined') {
  7071. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  7072. }
  7073. }
  7074. });
  7075. }
  7076. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  7077. for (var i = 0; i<mLine.ssrcs.length; i++){
  7078. if (typeof mLine.ssrcs[i] === 'object'
  7079. && typeof mLine.ssrcs[i].id !== 'undefined'
  7080. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  7081. newSsrcLines.push(mLine.ssrcs[i]);
  7082. delete mLine.ssrcs[i];
  7083. }
  7084. }
  7085. for (var i = 0; i<mLine.ssrcs.length; i++){
  7086. if (typeof mLine.ssrcs[i] !== 'undefined') {
  7087. newSsrcLines.push(mLine.ssrcs[i]);
  7088. }
  7089. }
  7090. mLine.ssrcs = newSsrcLines;
  7091. }
  7092. });
  7093. }
  7094. var resStr = transform.write(session);
  7095. return new RTCSessionDescription({
  7096. type: desc.type,
  7097. sdp: resStr
  7098. });
  7099. };
  7100. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  7101. TraceablePeerConnection.prototype.__defineGetter__(
  7102. 'signalingState',
  7103. function() { return this.peerconnection.signalingState; });
  7104. TraceablePeerConnection.prototype.__defineGetter__(
  7105. 'iceConnectionState',
  7106. function() { return this.peerconnection.iceConnectionState; });
  7107. TraceablePeerConnection.prototype.__defineGetter__(
  7108. 'localDescription',
  7109. function() {
  7110. var desc = this.peerconnection.localDescription;
  7111. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  7112. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  7113. // if we're running on FF, transform to Plan B first.
  7114. if (RTCBrowserType.usesUnifiedPlan()) {
  7115. desc = this.interop.toPlanB(desc);
  7116. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  7117. }
  7118. return desc;
  7119. });
  7120. TraceablePeerConnection.prototype.__defineGetter__(
  7121. 'remoteDescription',
  7122. function() {
  7123. var desc = this.peerconnection.remoteDescription;
  7124. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  7125. // if we're running on FF, transform to Plan B first.
  7126. if (RTCBrowserType.usesUnifiedPlan()) {
  7127. desc = this.interop.toPlanB(desc);
  7128. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  7129. }
  7130. return desc;
  7131. });
  7132. }
  7133. TraceablePeerConnection.prototype.addStream = function (stream) {
  7134. this.trace('addStream', stream.id);
  7135. try
  7136. {
  7137. this.peerconnection.addStream(stream);
  7138. }
  7139. catch (e)
  7140. {
  7141. console.error(e);
  7142. }
  7143. };
  7144. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  7145. this.trace('removeStream', stream.id);
  7146. if(stopStreams) {
  7147. stream.getAudioTracks().forEach(function (track) {
  7148. // stop() not supported with IE
  7149. if (track.stop) {
  7150. track.stop();
  7151. }
  7152. });
  7153. stream.getVideoTracks().forEach(function (track) {
  7154. // stop() not supported with IE
  7155. if (track.stop) {
  7156. track.stop();
  7157. }
  7158. });
  7159. if (stream.stop) {
  7160. stream.stop();
  7161. }
  7162. }
  7163. try {
  7164. // FF doesn't support this yet.
  7165. if (this.peerconnection.removeStream)
  7166. this.peerconnection.removeStream(stream);
  7167. } catch (e) {
  7168. console.error(e);
  7169. }
  7170. };
  7171. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  7172. this.trace('createDataChannel', label, opts);
  7173. return this.peerconnection.createDataChannel(label, opts);
  7174. };
  7175. TraceablePeerConnection.prototype.setLocalDescription
  7176. = function (description, successCallback, failureCallback) {
  7177. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  7178. // if we're running on FF, transform to Plan A first.
  7179. if (RTCBrowserType.usesUnifiedPlan()) {
  7180. description = this.interop.toUnifiedPlan(description);
  7181. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  7182. }
  7183. var self = this;
  7184. this.peerconnection.setLocalDescription(description,
  7185. function () {
  7186. self.trace('setLocalDescriptionOnSuccess');
  7187. successCallback();
  7188. },
  7189. function (err) {
  7190. self.trace('setLocalDescriptionOnFailure', err);
  7191. failureCallback(err);
  7192. }
  7193. );
  7194. /*
  7195. if (this.statsinterval === null && this.maxstats > 0) {
  7196. // start gathering stats
  7197. }
  7198. */
  7199. };
  7200. TraceablePeerConnection.prototype.setRemoteDescription
  7201. = function (description, successCallback, failureCallback) {
  7202. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  7203. // TODO the focus should squeze or explode the remote simulcast
  7204. description = this.simulcast.mungeRemoteDescription(description);
  7205. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  7206. // if we're running on FF, transform to Plan A first.
  7207. if (RTCBrowserType.usesUnifiedPlan()) {
  7208. description = this.interop.toUnifiedPlan(description);
  7209. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  7210. }
  7211. if (RTCBrowserType.usesPlanB()) {
  7212. description = normalizePlanB(description);
  7213. }
  7214. var self = this;
  7215. this.peerconnection.setRemoteDescription(description,
  7216. function () {
  7217. self.trace('setRemoteDescriptionOnSuccess');
  7218. successCallback();
  7219. },
  7220. function (err) {
  7221. self.trace('setRemoteDescriptionOnFailure', err);
  7222. failureCallback(err);
  7223. }
  7224. );
  7225. /*
  7226. if (this.statsinterval === null && this.maxstats > 0) {
  7227. // start gathering stats
  7228. }
  7229. */
  7230. };
  7231. TraceablePeerConnection.prototype.close = function () {
  7232. this.trace('stop');
  7233. if (this.statsinterval !== null) {
  7234. window.clearInterval(this.statsinterval);
  7235. this.statsinterval = null;
  7236. }
  7237. this.peerconnection.close();
  7238. };
  7239. TraceablePeerConnection.prototype.createOffer
  7240. = function (successCallback, failureCallback, constraints) {
  7241. var self = this;
  7242. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  7243. this.peerconnection.createOffer(
  7244. function (offer) {
  7245. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  7246. // NOTE this is not tested because in meet the focus generates the
  7247. // offer.
  7248. // if we're running on FF, transform to Plan B first.
  7249. if (RTCBrowserType.usesUnifiedPlan()) {
  7250. offer = self.interop.toPlanB(offer);
  7251. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  7252. }
  7253. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  7254. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  7255. offer = self.simulcast.mungeLocalDescription(offer);
  7256. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  7257. }
  7258. successCallback(offer);
  7259. },
  7260. function(err) {
  7261. self.trace('createOfferOnFailure', err);
  7262. failureCallback(err);
  7263. },
  7264. constraints
  7265. );
  7266. };
  7267. TraceablePeerConnection.prototype.createAnswer
  7268. = function (successCallback, failureCallback, constraints) {
  7269. var self = this;
  7270. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  7271. this.peerconnection.createAnswer(
  7272. function (answer) {
  7273. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  7274. // if we're running on FF, transform to Plan A first.
  7275. if (RTCBrowserType.usesUnifiedPlan()) {
  7276. answer = self.interop.toPlanB(answer);
  7277. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  7278. }
  7279. // munge local video SSRC
  7280. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  7281. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  7282. answer = self.simulcast.mungeLocalDescription(answer);
  7283. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  7284. }
  7285. successCallback(answer);
  7286. },
  7287. function(err) {
  7288. self.trace('createAnswerOnFailure', err);
  7289. failureCallback(err);
  7290. },
  7291. constraints
  7292. );
  7293. };
  7294. TraceablePeerConnection.prototype.addIceCandidate
  7295. = function (candidate, successCallback, failureCallback) {
  7296. //var self = this;
  7297. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  7298. this.peerconnection.addIceCandidate(candidate);
  7299. /* maybe later
  7300. this.peerconnection.addIceCandidate(candidate,
  7301. function () {
  7302. self.trace('addIceCandidateOnSuccess');
  7303. successCallback();
  7304. },
  7305. function (err) {
  7306. self.trace('addIceCandidateOnFailure', err);
  7307. failureCallback(err);
  7308. }
  7309. );
  7310. */
  7311. };
  7312. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  7313. // TODO: Is this the correct way to handle Opera, Temasys?
  7314. if (RTCBrowserType.isFirefox()) {
  7315. // ignore for now...
  7316. if(!errback)
  7317. errback = function () {};
  7318. this.peerconnection.getStats(null, callback, errback);
  7319. } else {
  7320. this.peerconnection.getStats(callback);
  7321. }
  7322. };
  7323. module.exports = TraceablePeerConnection;
  7324. },{"../../service/xmpp/XMPPEvents":76,"../RTC/RTC":13,"../RTC/RTCBrowserType.js":14,"./LocalSSRCReplacement":22,"sdp-interop":53,"sdp-simulcast":60,"sdp-transform":67}],27:[function(require,module,exports){
  7325. /* global $, $iq, APP, config, messageHandler,
  7326. roomName, sessionTerminated, Strophe, Util */
  7327. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7328. var Settings = require("../settings/Settings");
  7329. var AuthenticationEvents
  7330. = require("../../service/authentication/AuthenticationEvents");
  7331. function createExpBackoffTimer(step) {
  7332. var count = 1;
  7333. return function (reset) {
  7334. // Reset call
  7335. if (reset) {
  7336. count = 1;
  7337. return;
  7338. }
  7339. // Calculate next timeout
  7340. var timeout = Math.pow(2, count - 1);
  7341. count += 1;
  7342. return timeout * step;
  7343. };
  7344. }
  7345. function Moderator(roomName, xmpp, emitter) {
  7346. this.roomName = roomName;
  7347. this.xmppService = xmpp;
  7348. this.getNextTimeout = createExpBackoffTimer(1000);
  7349. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  7350. // External authentication stuff
  7351. this.externalAuthEnabled = false;
  7352. this.settings = new Settings(roomName);
  7353. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  7354. // it will be enabled automatically if focus detects the component through
  7355. // service discovery.
  7356. this.sipGatewayEnabled = this.xmppService.options.hosts.call_control !== undefined;
  7357. this.eventEmitter = emitter;
  7358. this.connection = this.xmppService.connection;
  7359. this.focusUserJid;
  7360. //FIXME:
  7361. // Message listener that talks to POPUP window
  7362. function listener(event) {
  7363. if (event.data && event.data.sessionId) {
  7364. if (event.origin !== window.location.origin) {
  7365. console.warn("Ignoring sessionId from different origin: " +
  7366. event.origin);
  7367. return;
  7368. }
  7369. localStorage.setItem('sessionId', event.data.sessionId);
  7370. // After popup is closed we will authenticate
  7371. }
  7372. }
  7373. // Register
  7374. if (window.addEventListener) {
  7375. window.addEventListener("message", listener, false);
  7376. } else {
  7377. window.attachEvent("onmessage", listener);
  7378. }
  7379. }
  7380. Moderator.prototype.isExternalAuthEnabled = function () {
  7381. return this.externalAuthEnabled;
  7382. };
  7383. Moderator.prototype.isSipGatewayEnabled = function () {
  7384. return this.sipGatewayEnabled;
  7385. };
  7386. Moderator.prototype.onMucMemberLeft = function (jid) {
  7387. console.info("Someone left is it focus ? " + jid);
  7388. var resource = Strophe.getResourceFromJid(jid);
  7389. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  7390. console.info(
  7391. "Focus has left the room - leaving conference");
  7392. //hangUp();
  7393. // We'd rather reload to have everything re-initialized
  7394. //FIXME: show some message before reload
  7395. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  7396. }
  7397. };
  7398. Moderator.prototype.setFocusUserJid = function (focusJid) {
  7399. if (!this.focusUserJid) {
  7400. this.focusUserJid = focusJid;
  7401. console.info("Focus jid set to: " + this.focusUserJid);
  7402. }
  7403. };
  7404. Moderator.prototype.getFocusUserJid = function () {
  7405. return this.focusUserJid;
  7406. };
  7407. Moderator.prototype.getFocusComponent = function () {
  7408. // Get focus component address
  7409. var focusComponent = this.xmppService.options.hosts.focus;
  7410. // If not specified use default: 'focus.domain'
  7411. if (!focusComponent) {
  7412. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  7413. }
  7414. return focusComponent;
  7415. };
  7416. Moderator.prototype.createConferenceIq = function () {
  7417. // Generate create conference IQ
  7418. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  7419. // Session Id used for authentication
  7420. var sessionId = localStorage.getItem('sessionId');
  7421. var machineUID = this.settings.getSettings().uid;
  7422. console.info(
  7423. "Session ID: " + sessionId + " machine UID: " + machineUID);
  7424. elem.c('conference', {
  7425. xmlns: 'http://jitsi.org/protocol/focus',
  7426. room: this.roomName,
  7427. 'machine-uid': machineUID
  7428. });
  7429. if (sessionId) {
  7430. elem.attrs({ 'session-id': sessionId});
  7431. }
  7432. if (this.xmppService.options.hosts.bridge !== undefined) {
  7433. elem.c(
  7434. 'property',
  7435. {name: 'bridge',value: this.xmppService.options.hosts.bridge})
  7436. .up();
  7437. }
  7438. // Tell the focus we have Jigasi configured
  7439. if (this.xmppService.options.hosts.call_control !== undefined) {
  7440. elem.c(
  7441. 'property',
  7442. {name: 'call_control',value: this.xmppService.options.hosts.call_control})
  7443. .up();
  7444. }
  7445. if (this.xmppService.options.channelLastN !== undefined) {
  7446. elem.c(
  7447. 'property',
  7448. {name: 'channelLastN',value: this.xmppService.options.channelLastN})
  7449. .up();
  7450. }
  7451. if (this.xmppService.options.adaptiveLastN !== undefined) {
  7452. elem.c(
  7453. 'property',
  7454. {name: 'adaptiveLastN',value: this.xmppService.options.adaptiveLastN})
  7455. .up();
  7456. }
  7457. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  7458. elem.c(
  7459. 'property',
  7460. {name: 'adaptiveSimulcast',value: this.xmppService.options.adaptiveSimulcast})
  7461. .up();
  7462. }
  7463. if (this.xmppService.options.openSctp !== undefined) {
  7464. elem.c(
  7465. 'property',
  7466. {name: 'openSctp',value: this.xmppService.options.openSctp})
  7467. .up();
  7468. }
  7469. if(this.xmppService.options.startAudioMuted !== undefined)
  7470. {
  7471. elem.c(
  7472. 'property',
  7473. {name: 'startAudioMuted',value: this.xmppService.options.startAudioMuted})
  7474. .up();
  7475. }
  7476. if(this.xmppService.options.startVideoMuted !== undefined)
  7477. {
  7478. elem.c(
  7479. 'property',
  7480. {name: 'startVideoMuted',value: this.xmppService.options.startVideoMuted})
  7481. .up();
  7482. }
  7483. elem.c(
  7484. 'property',
  7485. {name: 'simulcastMode',value: 'rewriting'})
  7486. .up();
  7487. elem.up();
  7488. return elem;
  7489. };
  7490. Moderator.prototype.parseSessionId = function (resultIq) {
  7491. var sessionId = $(resultIq).find('conference').attr('session-id');
  7492. if (sessionId) {
  7493. console.info('Received sessionId: ' + sessionId);
  7494. localStorage.setItem('sessionId', sessionId);
  7495. }
  7496. };
  7497. Moderator.prototype.parseConfigOptions = function (resultIq) {
  7498. this.setFocusUserJid(
  7499. $(resultIq).find('conference').attr('focusjid'));
  7500. var authenticationEnabled
  7501. = $(resultIq).find(
  7502. '>conference>property' +
  7503. '[name=\'authentication\'][value=\'true\']').length > 0;
  7504. console.info("Authentication enabled: " + authenticationEnabled);
  7505. this.externalAuthEnabled = $(resultIq).find(
  7506. '>conference>property' +
  7507. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  7508. console.info('External authentication enabled: ' + this.externalAuthEnabled);
  7509. if (!this.externalAuthEnabled) {
  7510. // We expect to receive sessionId in 'internal' authentication mode
  7511. this.parseSessionId(resultIq);
  7512. }
  7513. var authIdentity = $(resultIq).find('>conference').attr('identity');
  7514. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  7515. authenticationEnabled, authIdentity);
  7516. // Check if focus has auto-detected Jigasi component(this will be also
  7517. // included if we have passed our host from the config)
  7518. if ($(resultIq).find(
  7519. '>conference>property' +
  7520. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  7521. this.sipGatewayEnabled = true;
  7522. }
  7523. console.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  7524. };
  7525. // FIXME = we need to show the fact that we're waiting for the focus
  7526. // to the user(or that focus is not available)
  7527. Moderator.prototype.allocateConferenceFocus = function ( callback) {
  7528. // Try to use focus user JID from the config
  7529. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  7530. // Send create conference IQ
  7531. var iq = this.createConferenceIq();
  7532. var self = this;
  7533. this.connection.sendIQ(
  7534. iq,
  7535. function (result) {
  7536. // Setup config options
  7537. self.parseConfigOptions(result);
  7538. if ('true' === $(result).find('conference').attr('ready')) {
  7539. // Reset both timers
  7540. self.getNextTimeout(true);
  7541. self.getNextErrorTimeout(true);
  7542. // Exec callback
  7543. callback();
  7544. } else {
  7545. var waitMs = self.getNextTimeout();
  7546. console.info("Waiting for the focus... " + waitMs);
  7547. // Reset error timeout
  7548. self.getNextErrorTimeout(true);
  7549. window.setTimeout(
  7550. function () {
  7551. self.allocateConferenceFocus(callback);
  7552. }, waitMs);
  7553. }
  7554. },
  7555. function (error) {
  7556. // Invalid session ? remove and try again
  7557. // without session ID to get a new one
  7558. var invalidSession
  7559. = $(error).find('>error>session-invalid').length;
  7560. if (invalidSession) {
  7561. console.info("Session expired! - removing");
  7562. localStorage.removeItem("sessionId");
  7563. }
  7564. if ($(error).find('>error>graceful-shutdown').length) {
  7565. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  7566. return;
  7567. }
  7568. // Check for error returned by the reservation system
  7569. var reservationErr = $(error).find('>error>reservation-error');
  7570. if (reservationErr.length) {
  7571. // Trigger error event
  7572. var errorCode = reservationErr.attr('error-code');
  7573. var errorMsg;
  7574. if ($(error).find('>error>text')) {
  7575. errorMsg = $(error).find('>error>text').text();
  7576. }
  7577. self.eventEmitter.emit(
  7578. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  7579. return;
  7580. }
  7581. // Not authorized to create new room
  7582. if ($(error).find('>error>not-authorized').length) {
  7583. console.warn("Unauthorized to start the conference", error);
  7584. var toDomain
  7585. = Strophe.getDomainFromJid(error.getAttribute('to'));
  7586. if (toDomain !== this.xmppService.options.hosts.anonymousdomain) {
  7587. //FIXME: "is external" should come either from
  7588. // the focus or config.js
  7589. self.externalAuthEnabled = true;
  7590. }
  7591. self.eventEmitter.emit(
  7592. XMPPEvents.AUTHENTICATION_REQUIRED,
  7593. function () {
  7594. self.allocateConferenceFocus(
  7595. callback);
  7596. });
  7597. return;
  7598. }
  7599. var waitMs = self.getNextErrorTimeout();
  7600. console.error("Focus error, retry after " + waitMs, error);
  7601. // Show message
  7602. var focusComponent = self.getFocusComponent();
  7603. var retrySec = waitMs / 1000;
  7604. //FIXME: message is duplicated ?
  7605. // Do not show in case of session invalid
  7606. // which means just a retry
  7607. if (!invalidSession) {
  7608. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  7609. focusComponent, retrySec);
  7610. }
  7611. // Reset response timeout
  7612. self.getNextTimeout(true);
  7613. window.setTimeout(
  7614. function () {
  7615. self.allocateConferenceFocus(callback);
  7616. }, waitMs);
  7617. }
  7618. );
  7619. };
  7620. Moderator.prototype.getLoginUrl = function (urlCallback) {
  7621. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  7622. iq.c('login-url', {
  7623. xmlns: 'http://jitsi.org/protocol/focus',
  7624. room: this.roomName,
  7625. 'machine-uid': this.settings.getSettings().uid
  7626. });
  7627. this.connection.sendIQ(
  7628. iq,
  7629. function (result) {
  7630. var url = $(result).find('login-url').attr('url');
  7631. url = url = decodeURIComponent(url);
  7632. if (url) {
  7633. console.info("Got auth url: " + url);
  7634. urlCallback(url);
  7635. } else {
  7636. console.error(
  7637. "Failed to get auth url from the focus", result);
  7638. }
  7639. },
  7640. function (error) {
  7641. console.error("Get auth url error", error);
  7642. }
  7643. );
  7644. };
  7645. Moderator.prototype.getPopupLoginUrl = function (urlCallback) {
  7646. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  7647. iq.c('login-url', {
  7648. xmlns: 'http://jitsi.org/protocol/focus',
  7649. room: this.roomName,
  7650. 'machine-uid': this.settings.getSettings().uid,
  7651. popup: true
  7652. });
  7653. this.connection.sendIQ(
  7654. iq,
  7655. function (result) {
  7656. var url = $(result).find('login-url').attr('url');
  7657. url = url = decodeURIComponent(url);
  7658. if (url) {
  7659. console.info("Got POPUP auth url: " + url);
  7660. urlCallback(url);
  7661. } else {
  7662. console.error(
  7663. "Failed to get POPUP auth url from the focus", result);
  7664. }
  7665. },
  7666. function (error) {
  7667. console.error('Get POPUP auth url error', error);
  7668. }
  7669. );
  7670. };
  7671. Moderator.prototype.logout = function (callback) {
  7672. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  7673. var sessionId = localStorage.getItem('sessionId');
  7674. if (!sessionId) {
  7675. callback();
  7676. return;
  7677. }
  7678. iq.c('logout', {
  7679. xmlns: 'http://jitsi.org/protocol/focus',
  7680. 'session-id': sessionId
  7681. });
  7682. this.connection.sendIQ(
  7683. iq,
  7684. function (result) {
  7685. var logoutUrl = $(result).find('logout').attr('logout-url');
  7686. if (logoutUrl) {
  7687. logoutUrl = decodeURIComponent(logoutUrl);
  7688. }
  7689. console.info("Log out OK, url: " + logoutUrl, result);
  7690. localStorage.removeItem('sessionId');
  7691. callback(logoutUrl);
  7692. },
  7693. function (error) {
  7694. console.error("Logout error", error);
  7695. }
  7696. );
  7697. };
  7698. module.exports = Moderator;
  7699. },{"../../service/authentication/AuthenticationEvents":74,"../../service/xmpp/XMPPEvents":76,"../settings/Settings":18}],28:[function(require,module,exports){
  7700. /* jshint -W117 */
  7701. /* a simple MUC connection plugin
  7702. * can only handle a single MUC room
  7703. */
  7704. var ChatRoom = require("./ChatRoom");
  7705. module.exports = function(XMPP) {
  7706. Strophe.addConnectionPlugin('emuc', {
  7707. connection: null,
  7708. rooms: {},//map with the rooms
  7709. init: function (conn) {
  7710. this.connection = conn;
  7711. // add handlers (just once)
  7712. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, null, null);
  7713. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null);
  7714. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null);
  7715. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null);
  7716. },
  7717. createRoom: function (jid, password, options) {
  7718. var roomJid = Strophe.getBareJidFromJid(jid);
  7719. if (this.rooms[roomJid]) {
  7720. console.error("You are already in the room!");
  7721. return;
  7722. }
  7723. this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, options);
  7724. return this.rooms[roomJid];
  7725. },
  7726. doLeave: function (jid) {
  7727. this.rooms[jid].doLeave();
  7728. delete this.rooms[jid];
  7729. },
  7730. onPresence: function (pres) {
  7731. var from = pres.getAttribute('from');
  7732. // What is this for? A workaround for something?
  7733. if (pres.getAttribute('type')) {
  7734. return true;
  7735. }
  7736. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7737. if(!room)
  7738. return;
  7739. // Parse status.
  7740. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  7741. room.createNonAnonymousRoom();
  7742. }
  7743. room.onPresence(pres);
  7744. return true;
  7745. },
  7746. onPresenceUnavailable: function (pres) {
  7747. var from = pres.getAttribute('from');
  7748. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7749. if(!room)
  7750. return;
  7751. room.onPresenceUnavailable(pres, from);
  7752. return true;
  7753. },
  7754. onPresenceError: function (pres) {
  7755. var from = pres.getAttribute('from');
  7756. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7757. if(!room)
  7758. return;
  7759. room.onPresenceError(pres, from);
  7760. return true;
  7761. },
  7762. onMessage: function (msg) {
  7763. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  7764. var from = msg.getAttribute('from');
  7765. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7766. if(!room)
  7767. return;
  7768. room.onMessage(msg, from);
  7769. return true;
  7770. },
  7771. setJingleSession: function (from, session) {
  7772. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7773. if(!room)
  7774. return;
  7775. room.setJingleSession(session);
  7776. }
  7777. });
  7778. };
  7779. },{"./ChatRoom":19}],29:[function(require,module,exports){
  7780. /* jshint -W117 */
  7781. var JingleSession = require("./JingleSessionPC");
  7782. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7783. var RTCBrowserType = require("../RTC/RTCBrowserType");
  7784. module.exports = function(XMPP, eventEmitter) {
  7785. Strophe.addConnectionPlugin('jingle', {
  7786. connection: null,
  7787. sessions: {},
  7788. jid2session: {},
  7789. ice_config: {iceServers: []},
  7790. media_constraints: {
  7791. mandatory: {
  7792. 'OfferToReceiveAudio': true,
  7793. 'OfferToReceiveVideo': true
  7794. }
  7795. // MozDontOfferDataChannel: true when this is firefox
  7796. },
  7797. init: function (conn) {
  7798. this.connection = conn;
  7799. if (this.connection.disco) {
  7800. // http://xmpp.org/extensions/xep-0167.html#support
  7801. // http://xmpp.org/extensions/xep-0176.html#support
  7802. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  7803. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  7804. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  7805. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  7806. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  7807. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  7808. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  7809. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  7810. || RTCBrowserType.isTemasysPluginUsed()) {
  7811. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  7812. }
  7813. // this is dealt with by SDP O/A so we don't need to announce this
  7814. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  7815. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  7816. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  7817. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  7818. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  7819. }
  7820. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  7821. },
  7822. onJingle: function (iq) {
  7823. var sid = $(iq).find('jingle').attr('sid');
  7824. var action = $(iq).find('jingle').attr('action');
  7825. var fromJid = iq.getAttribute('from');
  7826. // send ack first
  7827. var ack = $iq({type: 'result',
  7828. to: fromJid,
  7829. id: iq.getAttribute('id')
  7830. });
  7831. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  7832. var sess = this.sessions[sid];
  7833. if ('session-initiate' != action) {
  7834. if (sess === null) {
  7835. ack.type = 'error';
  7836. ack.c('error', {type: 'cancel'})
  7837. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  7838. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  7839. this.connection.send(ack);
  7840. return true;
  7841. }
  7842. // local jid is not checked
  7843. if (fromJid != sess.peerjid) {
  7844. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  7845. ack.type = 'error';
  7846. ack.c('error', {type: 'cancel'})
  7847. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  7848. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  7849. this.connection.send(ack);
  7850. return true;
  7851. }
  7852. } else if (sess !== undefined) {
  7853. // existing session with same session id
  7854. // this might be out-of-order if the sess.peerjid is the same as from
  7855. ack.type = 'error';
  7856. ack.c('error', {type: 'cancel'})
  7857. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  7858. console.warn('duplicate session id', sid);
  7859. this.connection.send(ack);
  7860. return true;
  7861. }
  7862. // FIXME: check for a defined action
  7863. this.connection.send(ack);
  7864. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  7865. switch (action) {
  7866. case 'session-initiate':
  7867. var startMuted = $(iq).find('jingle>startmuted');
  7868. if (startMuted && startMuted.length > 0) {
  7869. var audioMuted = startMuted.attr("audio");
  7870. var videoMuted = startMuted.attr("video");
  7871. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  7872. audioMuted === "true", videoMuted === "true");
  7873. }
  7874. sess = new JingleSession(
  7875. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  7876. this.connection, XMPP);
  7877. // configure session
  7878. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  7879. this.connection.emuc.setJingleSession(fromBareJid, sess);
  7880. sess.media_constraints = this.media_constraints;
  7881. sess.ice_config = this.ice_config;
  7882. sess.initialize(fromJid, false);
  7883. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  7884. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  7885. sess.setOffer($(iq).find('>jingle'));
  7886. this.sessions[sess.sid] = sess;
  7887. this.jid2session[sess.peerjid] = sess;
  7888. // the callback should either
  7889. // .sendAnswer and .accept
  7890. // or .sendTerminate -- not necessarily synchronous
  7891. sess.sendAnswer();
  7892. sess.accept();
  7893. break;
  7894. case 'session-accept':
  7895. sess.setAnswer($(iq).find('>jingle'));
  7896. sess.accept();
  7897. break;
  7898. case 'session-terminate':
  7899. // If this is not the focus sending the terminate, we have
  7900. // nothing more to do here.
  7901. if (Object.keys(this.sessions).length < 1
  7902. || !(this.sessions[Object.keys(this.sessions)[0]]
  7903. instanceof JingleSession))
  7904. {
  7905. break;
  7906. }
  7907. console.log('terminating...', sess.sid);
  7908. sess.terminate();
  7909. this.terminate(sess.sid);
  7910. if ($(iq).find('>jingle>reason').length) {
  7911. $(document).trigger('callterminated.jingle', [
  7912. sess.sid,
  7913. sess.peerjid,
  7914. $(iq).find('>jingle>reason>:first')[0].tagName,
  7915. $(iq).find('>jingle>reason>text').text()
  7916. ]);
  7917. } else {
  7918. $(document).trigger('callterminated.jingle',
  7919. [sess.sid, sess.peerjid]);
  7920. }
  7921. break;
  7922. case 'transport-info':
  7923. sess.addIceCandidate($(iq).find('>jingle>content'));
  7924. break;
  7925. case 'session-info':
  7926. var affected;
  7927. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  7928. $(document).trigger('ringing.jingle', [sess.sid]);
  7929. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  7930. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  7931. $(document).trigger('mute.jingle', [sess.sid, affected]);
  7932. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  7933. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  7934. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  7935. }
  7936. break;
  7937. case 'addsource': // FIXME: proprietary, un-jingleish
  7938. case 'source-add': // FIXME: proprietary
  7939. sess.addSource($(iq).find('>jingle>content'), fromJid);
  7940. break;
  7941. case 'removesource': // FIXME: proprietary, un-jingleish
  7942. case 'source-remove': // FIXME: proprietary
  7943. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  7944. break;
  7945. default:
  7946. console.warn('jingle action not implemented', action);
  7947. break;
  7948. }
  7949. return true;
  7950. },
  7951. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  7952. if (sid === null || sid === undefined) {
  7953. for (sid in this.sessions) {
  7954. if (this.sessions[sid].state != 'ended') {
  7955. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  7956. this.sessions[sid].terminate();
  7957. }
  7958. delete this.jid2session[this.sessions[sid].peerjid];
  7959. delete this.sessions[sid];
  7960. }
  7961. } else if (this.sessions.hasOwnProperty(sid)) {
  7962. if (this.sessions[sid].state != 'ended') {
  7963. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  7964. this.sessions[sid].terminate();
  7965. }
  7966. delete this.jid2session[this.sessions[sid].peerjid];
  7967. delete this.sessions[sid];
  7968. }
  7969. },
  7970. getStunAndTurnCredentials: function () {
  7971. // get stun and turn configuration from server via xep-0215
  7972. // uses time-limited credentials as described in
  7973. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  7974. //
  7975. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  7976. // for a prosody module which implements this
  7977. //
  7978. // currently, this doesn't work with updateIce and therefore credentials with a long
  7979. // validity have to be fetched before creating the peerconnection
  7980. // TODO: implement refresh via updateIce as described in
  7981. // https://code.google.com/p/webrtc/issues/detail?id=1650
  7982. var self = this;
  7983. this.connection.sendIQ(
  7984. $iq({type: 'get', to: this.connection.domain})
  7985. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  7986. function (res) {
  7987. var iceservers = [];
  7988. $(res).find('>services>service').each(function (idx, el) {
  7989. el = $(el);
  7990. var dict = {};
  7991. var type = el.attr('type');
  7992. switch (type) {
  7993. case 'stun':
  7994. dict.url = 'stun:' + el.attr('host');
  7995. if (el.attr('port')) {
  7996. dict.url += ':' + el.attr('port');
  7997. }
  7998. iceservers.push(dict);
  7999. break;
  8000. case 'turn':
  8001. case 'turns':
  8002. dict.url = type + ':';
  8003. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  8004. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  8005. dict.url += el.attr('username') + '@';
  8006. } else {
  8007. dict.username = el.attr('username'); // only works in M28
  8008. }
  8009. }
  8010. dict.url += el.attr('host');
  8011. if (el.attr('port') && el.attr('port') != '3478') {
  8012. dict.url += ':' + el.attr('port');
  8013. }
  8014. if (el.attr('transport') && el.attr('transport') != 'udp') {
  8015. dict.url += '?transport=' + el.attr('transport');
  8016. }
  8017. if (el.attr('password')) {
  8018. dict.credential = el.attr('password');
  8019. }
  8020. iceservers.push(dict);
  8021. break;
  8022. }
  8023. });
  8024. self.ice_config.iceServers = iceservers;
  8025. },
  8026. function (err) {
  8027. console.warn('getting turn credentials failed', err);
  8028. console.warn('is mod_turncredentials or similar installed?');
  8029. }
  8030. );
  8031. // implement push?
  8032. },
  8033. /**
  8034. * Returns the data saved in 'updateLog' in a format to be logged.
  8035. */
  8036. getLog: function () {
  8037. var data = {};
  8038. var self = this;
  8039. Object.keys(this.sessions).forEach(function (sid) {
  8040. var session = self.sessions[sid];
  8041. if (session.peerconnection && session.peerconnection.updateLog) {
  8042. // FIXME: should probably be a .dump call
  8043. data["jingle_" + session.sid] = {
  8044. updateLog: session.peerconnection.updateLog,
  8045. stats: session.peerconnection.stats,
  8046. url: window.location.href
  8047. };
  8048. }
  8049. });
  8050. return data;
  8051. }
  8052. });
  8053. };
  8054. },{"../../service/xmpp/XMPPEvents":76,"../RTC/RTCBrowserType":14,"./JingleSessionPC":21}],30:[function(require,module,exports){
  8055. /* global Strophe */
  8056. module.exports = function () {
  8057. Strophe.addConnectionPlugin('logger', {
  8058. // logs raw stanzas and makes them available for download as JSON
  8059. connection: null,
  8060. log: [],
  8061. init: function (conn) {
  8062. this.connection = conn;
  8063. this.connection.rawInput = this.log_incoming.bind(this);
  8064. this.connection.rawOutput = this.log_outgoing.bind(this);
  8065. },
  8066. log_incoming: function (stanza) {
  8067. this.log.push([new Date().getTime(), 'incoming', stanza]);
  8068. },
  8069. log_outgoing: function (stanza) {
  8070. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  8071. }
  8072. });
  8073. };
  8074. },{}],31:[function(require,module,exports){
  8075. /* jshint -W117 */
  8076. module.exports = function() {
  8077. Strophe.addConnectionPlugin('rayo',
  8078. {
  8079. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  8080. connection: null,
  8081. init: function (conn) {
  8082. this.connection = conn;
  8083. if (this.connection.disco) {
  8084. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  8085. }
  8086. this.connection.addHandler(
  8087. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  8088. },
  8089. onRayo: function (iq) {
  8090. console.info("Rayo IQ", iq);
  8091. },
  8092. dial: function (to, from, roomName, roomPass) {
  8093. var self = this;
  8094. var req = $iq(
  8095. {
  8096. type: 'set',
  8097. to: this.connection.emuc.focusMucJid
  8098. }
  8099. );
  8100. req.c('dial',
  8101. {
  8102. xmlns: this.RAYO_XMLNS,
  8103. to: to,
  8104. from: from
  8105. });
  8106. req.c('header',
  8107. {
  8108. name: 'JvbRoomName',
  8109. value: roomName
  8110. }).up();
  8111. if (roomPass !== null && roomPass.length) {
  8112. req.c('header',
  8113. {
  8114. name: 'JvbRoomPassword',
  8115. value: roomPass
  8116. }).up();
  8117. }
  8118. this.connection.sendIQ(
  8119. req,
  8120. function (result) {
  8121. console.info('Dial result ', result);
  8122. var resource = $(result).find('ref').attr('uri');
  8123. this.call_resource = resource.substr('xmpp:'.length);
  8124. console.info(
  8125. "Received call resource: " + this.call_resource);
  8126. },
  8127. function (error) {
  8128. console.info('Dial error ', error);
  8129. }
  8130. );
  8131. },
  8132. hang_up: function () {
  8133. if (!this.call_resource) {
  8134. console.warn("No call in progress");
  8135. return;
  8136. }
  8137. var self = this;
  8138. var req = $iq(
  8139. {
  8140. type: 'set',
  8141. to: this.call_resource
  8142. }
  8143. );
  8144. req.c('hangup',
  8145. {
  8146. xmlns: this.RAYO_XMLNS
  8147. });
  8148. this.connection.sendIQ(
  8149. req,
  8150. function (result) {
  8151. console.info('Hangup result ', result);
  8152. self.call_resource = null;
  8153. },
  8154. function (error) {
  8155. console.info('Hangup error ', error);
  8156. self.call_resource = null;
  8157. }
  8158. );
  8159. }
  8160. }
  8161. );
  8162. };
  8163. },{}],32:[function(require,module,exports){
  8164. /**
  8165. * Strophe logger implementation. Logs from level WARN and above.
  8166. */
  8167. module.exports = function () {
  8168. Strophe.log = function (level, msg) {
  8169. switch (level) {
  8170. case Strophe.LogLevel.WARN:
  8171. console.warn("Strophe: " + msg);
  8172. break;
  8173. case Strophe.LogLevel.ERROR:
  8174. case Strophe.LogLevel.FATAL:
  8175. console.error("Strophe: " + msg);
  8176. break;
  8177. }
  8178. };
  8179. Strophe.getStatusString = function (status) {
  8180. switch (status) {
  8181. case Strophe.Status.ERROR:
  8182. return "ERROR";
  8183. case Strophe.Status.CONNECTING:
  8184. return "CONNECTING";
  8185. case Strophe.Status.CONNFAIL:
  8186. return "CONNFAIL";
  8187. case Strophe.Status.AUTHENTICATING:
  8188. return "AUTHENTICATING";
  8189. case Strophe.Status.AUTHFAIL:
  8190. return "AUTHFAIL";
  8191. case Strophe.Status.CONNECTED:
  8192. return "CONNECTED";
  8193. case Strophe.Status.DISCONNECTED:
  8194. return "DISCONNECTED";
  8195. case Strophe.Status.DISCONNECTING:
  8196. return "DISCONNECTING";
  8197. case Strophe.Status.ATTACHED:
  8198. return "ATTACHED";
  8199. default:
  8200. return "unknown";
  8201. }
  8202. };
  8203. };
  8204. },{}],33:[function(require,module,exports){
  8205. /* global $, APP, config, Strophe*/
  8206. var EventEmitter = require("events");
  8207. var Pako = require("pako");
  8208. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  8209. var RTCEvents = require("../../service/RTC/RTCEvents");
  8210. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8211. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  8212. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  8213. var RTC = require("../RTC/RTC");
  8214. var authenticatedUser = false;
  8215. function createConnection(bosh) {
  8216. bosh = bosh || '/http-bind';
  8217. return new Strophe.Connection(bosh);
  8218. };
  8219. //!!!!!!!!!! FIXME: ...
  8220. function initStrophePlugins(XMPP)
  8221. {
  8222. require("./strophe.emuc")(XMPP);
  8223. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  8224. // require("./strophe.moderate")(XMPP, eventEmitter);
  8225. require("./strophe.util")();
  8226. require("./strophe.rayo")();
  8227. require("./strophe.logger")();
  8228. }
  8229. //!!!!!!!!!! FIXME: ...
  8230. ///**
  8231. // * If given <tt>localStream</tt> is video one this method will advertise it's
  8232. // * video type in MUC presence.
  8233. // * @param localStream new or modified <tt>LocalStream</tt>.
  8234. // */
  8235. //function broadcastLocalVideoType(localStream) {
  8236. // if (localStream.videoType)
  8237. // XMPP.addToPresence('videoType', localStream.videoType);
  8238. //}
  8239. //
  8240. //function registerListeners() {
  8241. // RTC.addStreamListener(
  8242. // broadcastLocalVideoType,
  8243. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  8244. // );
  8245. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  8246. // XMPP.addToPresence("devices", devices);
  8247. // });
  8248. //}
  8249. function XMPP(options) {
  8250. this.eventEmitter = new EventEmitter();
  8251. this.connection = null;
  8252. this.disconnectInProgress = false;
  8253. this.forceMuted = false;
  8254. this.options = options;
  8255. initStrophePlugins(this);
  8256. // registerListeners();
  8257. this.connection = createConnection(options.bosh);
  8258. }
  8259. XMPP.prototype.getConnection = function(){ return connection; };
  8260. XMPP.prototype._connect = function (jid, password) {
  8261. var self = this;
  8262. // connection.connect() starts the connection process.
  8263. //
  8264. // As the connection process proceeds, the user supplied callback will
  8265. // be triggered multiple times with status updates. The callback should
  8266. // take two arguments - the status code and the error condition.
  8267. //
  8268. // The status code will be one of the values in the Strophe.Status
  8269. // constants. The error condition will be one of the conditions defined
  8270. // in RFC 3920 or the condition ‘strophe-parsererror’.
  8271. //
  8272. // The Parameters wait, hold and route are optional and only relevant
  8273. // for BOSH connections. Please see XEP 124 for a more detailed
  8274. // explanation of the optional parameters.
  8275. //
  8276. // Connection status constants for use by the connection handler
  8277. // callback.
  8278. //
  8279. // Status.ERROR - An error has occurred (websockets specific)
  8280. // Status.CONNECTING - The connection is currently being made
  8281. // Status.CONNFAIL - The connection attempt failed
  8282. // Status.AUTHENTICATING - The connection is authenticating
  8283. // Status.AUTHFAIL - The authentication attempt failed
  8284. // Status.CONNECTED - The connection has succeeded
  8285. // Status.DISCONNECTED - The connection has been terminated
  8286. // Status.DISCONNECTING - The connection is currently being terminated
  8287. // Status.ATTACHED - The connection has been attached
  8288. var anonymousConnectionFailed = false;
  8289. var connectionFailed = false;
  8290. var lastErrorMsg;
  8291. this.connection.connect(jid, password, function (status, msg) {
  8292. console.log('Strophe status changed to',
  8293. Strophe.getStatusString(status), msg);
  8294. if (status === Strophe.Status.CONNECTED) {
  8295. if (self.options.useStunTurn) {
  8296. self.connection.jingle.getStunAndTurnCredentials();
  8297. }
  8298. console.info("My Jabber ID: " + self.connection.jid);
  8299. if (password)
  8300. authenticatedUser = true;
  8301. if (self.connection && self.connection.connected &&
  8302. Strophe.getResourceFromJid(self.connection.jid)) {
  8303. // .connected is true while connecting?
  8304. // self.connection.send($pres());
  8305. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  8306. Strophe.getResourceFromJid(self.connection.jid));
  8307. }
  8308. } else if (status === Strophe.Status.CONNFAIL) {
  8309. if (msg === 'x-strophe-bad-non-anon-jid') {
  8310. anonymousConnectionFailed = true;
  8311. }
  8312. else
  8313. {
  8314. connectionFailed = true;
  8315. }
  8316. lastErrorMsg = msg;
  8317. } else if (status === Strophe.Status.DISCONNECTED) {
  8318. self.disconnectInProgress = false;
  8319. if (anonymousConnectionFailed) {
  8320. // prompt user for username and password
  8321. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  8322. JitsiConnectionErrors.PASSWORD_REQUIRED);
  8323. } else if(connectionFailed) {
  8324. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  8325. JitsiConnectionErrors.OTHER_ERROR,
  8326. msg ? msg : lastErrorMsg);
  8327. } else {
  8328. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  8329. msg ? msg : lastErrorMsg);
  8330. }
  8331. } else if (status === Strophe.Status.AUTHFAIL) {
  8332. // wrong password or username, prompt user
  8333. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  8334. JitsiConnectionErrors.PASSWORD_REQUIRED);
  8335. }
  8336. });
  8337. }
  8338. XMPP.prototype.connect = function (jid, password) {
  8339. if(!jid) {
  8340. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  8341. // Force authenticated domain if room is appended with '?login=true'
  8342. if (this.options.hosts.anonymousdomain &&
  8343. window.location.search.indexOf("login=true") !== -1) {
  8344. configDomain = this.options.hosts.domain;
  8345. }
  8346. jid = configDomain || window.location.hostname;
  8347. }
  8348. return this._connect(jid, password);
  8349. };
  8350. XMPP.prototype.createRoom = function (roomName, options, useNicks, nick) {
  8351. var roomjid = roomName + '@' + this.options.hosts.muc;
  8352. if (useNicks) {
  8353. if (nick) {
  8354. roomjid += '/' + nick;
  8355. } else {
  8356. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  8357. }
  8358. } else {
  8359. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  8360. if(!authenticatedUser)
  8361. tmpJid = tmpJid.substr(0, 8);
  8362. roomjid += '/' + tmpJid;
  8363. }
  8364. return this.connection.emuc.createRoom(roomjid, null, options);
  8365. }
  8366. XMPP.prototype.addListener = function(type, listener) {
  8367. this.eventEmitter.on(type, listener);
  8368. };
  8369. XMPP.prototype.removeListener = function (type, listener) {
  8370. this.eventEmitter.removeListener(type, listener);
  8371. };
  8372. //FIXME: this should work with the room
  8373. XMPP.prototype.leaveRoom = function (jid) {
  8374. var handler = this.connection.jingle.jid2session[jid];
  8375. if (handler && handler.peerconnection) {
  8376. // FIXME: probably removing streams is not required and close() should
  8377. // be enough
  8378. if (RTC.localAudio) {
  8379. handler.peerconnection.removeStream(
  8380. RTC.localAudio.getOriginalStream(), true);
  8381. }
  8382. if (RTC.localVideo) {
  8383. handler.peerconnection.removeStream(
  8384. RTC.localVideo.getOriginalStream(), true);
  8385. }
  8386. handler.peerconnection.close();
  8387. }
  8388. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  8389. this.connection.emuc.doLeave(jid);
  8390. };
  8391. /**
  8392. * Sends 'data' as a log message to the focus. Returns true iff a message
  8393. * was sent.
  8394. * @param data
  8395. * @returns {boolean} true iff a message was sent.
  8396. */
  8397. XMPP.prototype.sendLogs = function (data) {
  8398. if(!this.connection.emuc.focusMucJid)
  8399. return false;
  8400. var deflate = true;
  8401. var content = JSON.stringify(data);
  8402. if (deflate) {
  8403. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  8404. }
  8405. content = Base64.encode(content);
  8406. // XEP-0337-ish
  8407. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  8408. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  8409. id: 'PeerConnectionStats'});
  8410. message.c('message').t(content).up();
  8411. if (deflate) {
  8412. message.c('tag', {name: "deflated", value: "true"}).up();
  8413. }
  8414. message.up();
  8415. this.connection.send(message);
  8416. return true;
  8417. };
  8418. // Gets the logs from strophe.jingle.
  8419. XMPP.prototype.getJingleLog = function () {
  8420. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  8421. };
  8422. // Gets the logs from strophe.
  8423. XMPP.prototype.getXmppLog = function () {
  8424. return this.connection.logger ? this.connection.logger.log : null;
  8425. };
  8426. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  8427. this.connection.rayo.dial(to, from, roomName,roomPass);
  8428. };
  8429. XMPP.prototype.setMute = function (jid, mute) {
  8430. this.connection.moderate.setMute(jid, mute);
  8431. };
  8432. XMPP.prototype.eject = function (jid) {
  8433. this.connection.moderate.eject(jid);
  8434. };
  8435. XMPP.prototype.getJidFromSSRC = function (ssrc) {
  8436. if (!this.isConferenceInProgress())
  8437. return null;
  8438. return this.connection.jingle.activecall.getSsrcOwner(ssrc);
  8439. };
  8440. XMPP.prototype.getSessions = function () {
  8441. return this.connection.jingle.sessions;
  8442. };
  8443. XMPP.prototype.disconnect = function () {
  8444. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  8445. {
  8446. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  8447. return;
  8448. }
  8449. this.disconnectInProgress = true;
  8450. this.connection.disconnect();
  8451. };
  8452. module.exports = XMPP;
  8453. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":71,"../../service/RTC/StreamEventTypes":73,"../../service/xmpp/XMPPEvents":76,"../RTC/RTC":13,"./strophe.emuc":28,"./strophe.jingle":29,"./strophe.logger":30,"./strophe.rayo":31,"./strophe.util":32,"events":77,"pako":36}],34:[function(require,module,exports){
  8454. (function (process){
  8455. /*!
  8456. * async
  8457. * https://github.com/caolan/async
  8458. *
  8459. * Copyright 2010-2014 Caolan McMahon
  8460. * Released under the MIT license
  8461. */
  8462. /*jshint onevar: false, indent:4 */
  8463. /*global setImmediate: false, setTimeout: false, console: false */
  8464. (function () {
  8465. var async = {};
  8466. // global on the server, window in the browser
  8467. var root, previous_async;
  8468. root = this;
  8469. if (root != null) {
  8470. previous_async = root.async;
  8471. }
  8472. async.noConflict = function () {
  8473. root.async = previous_async;
  8474. return async;
  8475. };
  8476. function only_once(fn) {
  8477. var called = false;
  8478. return function() {
  8479. if (called) throw new Error("Callback was already called.");
  8480. called = true;
  8481. fn.apply(root, arguments);
  8482. }
  8483. }
  8484. //// cross-browser compatiblity functions ////
  8485. var _toString = Object.prototype.toString;
  8486. var _isArray = Array.isArray || function (obj) {
  8487. return _toString.call(obj) === '[object Array]';
  8488. };
  8489. var _each = function (arr, iterator) {
  8490. if (arr.forEach) {
  8491. return arr.forEach(iterator);
  8492. }
  8493. for (var i = 0; i < arr.length; i += 1) {
  8494. iterator(arr[i], i, arr);
  8495. }
  8496. };
  8497. var _map = function (arr, iterator) {
  8498. if (arr.map) {
  8499. return arr.map(iterator);
  8500. }
  8501. var results = [];
  8502. _each(arr, function (x, i, a) {
  8503. results.push(iterator(x, i, a));
  8504. });
  8505. return results;
  8506. };
  8507. var _reduce = function (arr, iterator, memo) {
  8508. if (arr.reduce) {
  8509. return arr.reduce(iterator, memo);
  8510. }
  8511. _each(arr, function (x, i, a) {
  8512. memo = iterator(memo, x, i, a);
  8513. });
  8514. return memo;
  8515. };
  8516. var _keys = function (obj) {
  8517. if (Object.keys) {
  8518. return Object.keys(obj);
  8519. }
  8520. var keys = [];
  8521. for (var k in obj) {
  8522. if (obj.hasOwnProperty(k)) {
  8523. keys.push(k);
  8524. }
  8525. }
  8526. return keys;
  8527. };
  8528. //// exported async module functions ////
  8529. //// nextTick implementation with browser-compatible fallback ////
  8530. if (typeof process === 'undefined' || !(process.nextTick)) {
  8531. if (typeof setImmediate === 'function') {
  8532. async.nextTick = function (fn) {
  8533. // not a direct alias for IE10 compatibility
  8534. setImmediate(fn);
  8535. };
  8536. async.setImmediate = async.nextTick;
  8537. }
  8538. else {
  8539. async.nextTick = function (fn) {
  8540. setTimeout(fn, 0);
  8541. };
  8542. async.setImmediate = async.nextTick;
  8543. }
  8544. }
  8545. else {
  8546. async.nextTick = process.nextTick;
  8547. if (typeof setImmediate !== 'undefined') {
  8548. async.setImmediate = function (fn) {
  8549. // not a direct alias for IE10 compatibility
  8550. setImmediate(fn);
  8551. };
  8552. }
  8553. else {
  8554. async.setImmediate = async.nextTick;
  8555. }
  8556. }
  8557. async.each = function (arr, iterator, callback) {
  8558. callback = callback || function () {};
  8559. if (!arr.length) {
  8560. return callback();
  8561. }
  8562. var completed = 0;
  8563. _each(arr, function (x) {
  8564. iterator(x, only_once(done) );
  8565. });
  8566. function done(err) {
  8567. if (err) {
  8568. callback(err);
  8569. callback = function () {};
  8570. }
  8571. else {
  8572. completed += 1;
  8573. if (completed >= arr.length) {
  8574. callback();
  8575. }
  8576. }
  8577. }
  8578. };
  8579. async.forEach = async.each;
  8580. async.eachSeries = function (arr, iterator, callback) {
  8581. callback = callback || function () {};
  8582. if (!arr.length) {
  8583. return callback();
  8584. }
  8585. var completed = 0;
  8586. var iterate = function () {
  8587. iterator(arr[completed], function (err) {
  8588. if (err) {
  8589. callback(err);
  8590. callback = function () {};
  8591. }
  8592. else {
  8593. completed += 1;
  8594. if (completed >= arr.length) {
  8595. callback();
  8596. }
  8597. else {
  8598. iterate();
  8599. }
  8600. }
  8601. });
  8602. };
  8603. iterate();
  8604. };
  8605. async.forEachSeries = async.eachSeries;
  8606. async.eachLimit = function (arr, limit, iterator, callback) {
  8607. var fn = _eachLimit(limit);
  8608. fn.apply(null, [arr, iterator, callback]);
  8609. };
  8610. async.forEachLimit = async.eachLimit;
  8611. var _eachLimit = function (limit) {
  8612. return function (arr, iterator, callback) {
  8613. callback = callback || function () {};
  8614. if (!arr.length || limit <= 0) {
  8615. return callback();
  8616. }
  8617. var completed = 0;
  8618. var started = 0;
  8619. var running = 0;
  8620. (function replenish () {
  8621. if (completed >= arr.length) {
  8622. return callback();
  8623. }
  8624. while (running < limit && started < arr.length) {
  8625. started += 1;
  8626. running += 1;
  8627. iterator(arr[started - 1], function (err) {
  8628. if (err) {
  8629. callback(err);
  8630. callback = function () {};
  8631. }
  8632. else {
  8633. completed += 1;
  8634. running -= 1;
  8635. if (completed >= arr.length) {
  8636. callback();
  8637. }
  8638. else {
  8639. replenish();
  8640. }
  8641. }
  8642. });
  8643. }
  8644. })();
  8645. };
  8646. };
  8647. var doParallel = function (fn) {
  8648. return function () {
  8649. var args = Array.prototype.slice.call(arguments);
  8650. return fn.apply(null, [async.each].concat(args));
  8651. };
  8652. };
  8653. var doParallelLimit = function(limit, fn) {
  8654. return function () {
  8655. var args = Array.prototype.slice.call(arguments);
  8656. return fn.apply(null, [_eachLimit(limit)].concat(args));
  8657. };
  8658. };
  8659. var doSeries = function (fn) {
  8660. return function () {
  8661. var args = Array.prototype.slice.call(arguments);
  8662. return fn.apply(null, [async.eachSeries].concat(args));
  8663. };
  8664. };
  8665. var _asyncMap = function (eachfn, arr, iterator, callback) {
  8666. arr = _map(arr, function (x, i) {
  8667. return {index: i, value: x};
  8668. });
  8669. if (!callback) {
  8670. eachfn(arr, function (x, callback) {
  8671. iterator(x.value, function (err) {
  8672. callback(err);
  8673. });
  8674. });
  8675. } else {
  8676. var results = [];
  8677. eachfn(arr, function (x, callback) {
  8678. iterator(x.value, function (err, v) {
  8679. results[x.index] = v;
  8680. callback(err);
  8681. });
  8682. }, function (err) {
  8683. callback(err, results);
  8684. });
  8685. }
  8686. };
  8687. async.map = doParallel(_asyncMap);
  8688. async.mapSeries = doSeries(_asyncMap);
  8689. async.mapLimit = function (arr, limit, iterator, callback) {
  8690. return _mapLimit(limit)(arr, iterator, callback);
  8691. };
  8692. var _mapLimit = function(limit) {
  8693. return doParallelLimit(limit, _asyncMap);
  8694. };
  8695. // reduce only has a series version, as doing reduce in parallel won't
  8696. // work in many situations.
  8697. async.reduce = function (arr, memo, iterator, callback) {
  8698. async.eachSeries(arr, function (x, callback) {
  8699. iterator(memo, x, function (err, v) {
  8700. memo = v;
  8701. callback(err);
  8702. });
  8703. }, function (err) {
  8704. callback(err, memo);
  8705. });
  8706. };
  8707. // inject alias
  8708. async.inject = async.reduce;
  8709. // foldl alias
  8710. async.foldl = async.reduce;
  8711. async.reduceRight = function (arr, memo, iterator, callback) {
  8712. var reversed = _map(arr, function (x) {
  8713. return x;
  8714. }).reverse();
  8715. async.reduce(reversed, memo, iterator, callback);
  8716. };
  8717. // foldr alias
  8718. async.foldr = async.reduceRight;
  8719. var _filter = function (eachfn, arr, iterator, callback) {
  8720. var results = [];
  8721. arr = _map(arr, function (x, i) {
  8722. return {index: i, value: x};
  8723. });
  8724. eachfn(arr, function (x, callback) {
  8725. iterator(x.value, function (v) {
  8726. if (v) {
  8727. results.push(x);
  8728. }
  8729. callback();
  8730. });
  8731. }, function (err) {
  8732. callback(_map(results.sort(function (a, b) {
  8733. return a.index - b.index;
  8734. }), function (x) {
  8735. return x.value;
  8736. }));
  8737. });
  8738. };
  8739. async.filter = doParallel(_filter);
  8740. async.filterSeries = doSeries(_filter);
  8741. // select alias
  8742. async.select = async.filter;
  8743. async.selectSeries = async.filterSeries;
  8744. var _reject = function (eachfn, arr, iterator, callback) {
  8745. var results = [];
  8746. arr = _map(arr, function (x, i) {
  8747. return {index: i, value: x};
  8748. });
  8749. eachfn(arr, function (x, callback) {
  8750. iterator(x.value, function (v) {
  8751. if (!v) {
  8752. results.push(x);
  8753. }
  8754. callback();
  8755. });
  8756. }, function (err) {
  8757. callback(_map(results.sort(function (a, b) {
  8758. return a.index - b.index;
  8759. }), function (x) {
  8760. return x.value;
  8761. }));
  8762. });
  8763. };
  8764. async.reject = doParallel(_reject);
  8765. async.rejectSeries = doSeries(_reject);
  8766. var _detect = function (eachfn, arr, iterator, main_callback) {
  8767. eachfn(arr, function (x, callback) {
  8768. iterator(x, function (result) {
  8769. if (result) {
  8770. main_callback(x);
  8771. main_callback = function () {};
  8772. }
  8773. else {
  8774. callback();
  8775. }
  8776. });
  8777. }, function (err) {
  8778. main_callback();
  8779. });
  8780. };
  8781. async.detect = doParallel(_detect);
  8782. async.detectSeries = doSeries(_detect);
  8783. async.some = function (arr, iterator, main_callback) {
  8784. async.each(arr, function (x, callback) {
  8785. iterator(x, function (v) {
  8786. if (v) {
  8787. main_callback(true);
  8788. main_callback = function () {};
  8789. }
  8790. callback();
  8791. });
  8792. }, function (err) {
  8793. main_callback(false);
  8794. });
  8795. };
  8796. // any alias
  8797. async.any = async.some;
  8798. async.every = function (arr, iterator, main_callback) {
  8799. async.each(arr, function (x, callback) {
  8800. iterator(x, function (v) {
  8801. if (!v) {
  8802. main_callback(false);
  8803. main_callback = function () {};
  8804. }
  8805. callback();
  8806. });
  8807. }, function (err) {
  8808. main_callback(true);
  8809. });
  8810. };
  8811. // all alias
  8812. async.all = async.every;
  8813. async.sortBy = function (arr, iterator, callback) {
  8814. async.map(arr, function (x, callback) {
  8815. iterator(x, function (err, criteria) {
  8816. if (err) {
  8817. callback(err);
  8818. }
  8819. else {
  8820. callback(null, {value: x, criteria: criteria});
  8821. }
  8822. });
  8823. }, function (err, results) {
  8824. if (err) {
  8825. return callback(err);
  8826. }
  8827. else {
  8828. var fn = function (left, right) {
  8829. var a = left.criteria, b = right.criteria;
  8830. return a < b ? -1 : a > b ? 1 : 0;
  8831. };
  8832. callback(null, _map(results.sort(fn), function (x) {
  8833. return x.value;
  8834. }));
  8835. }
  8836. });
  8837. };
  8838. async.auto = function (tasks, callback) {
  8839. callback = callback || function () {};
  8840. var keys = _keys(tasks);
  8841. var remainingTasks = keys.length
  8842. if (!remainingTasks) {
  8843. return callback();
  8844. }
  8845. var results = {};
  8846. var listeners = [];
  8847. var addListener = function (fn) {
  8848. listeners.unshift(fn);
  8849. };
  8850. var removeListener = function (fn) {
  8851. for (var i = 0; i < listeners.length; i += 1) {
  8852. if (listeners[i] === fn) {
  8853. listeners.splice(i, 1);
  8854. return;
  8855. }
  8856. }
  8857. };
  8858. var taskComplete = function () {
  8859. remainingTasks--
  8860. _each(listeners.slice(0), function (fn) {
  8861. fn();
  8862. });
  8863. };
  8864. addListener(function () {
  8865. if (!remainingTasks) {
  8866. var theCallback = callback;
  8867. // prevent final callback from calling itself if it errors
  8868. callback = function () {};
  8869. theCallback(null, results);
  8870. }
  8871. });
  8872. _each(keys, function (k) {
  8873. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  8874. var taskCallback = function (err) {
  8875. var args = Array.prototype.slice.call(arguments, 1);
  8876. if (args.length <= 1) {
  8877. args = args[0];
  8878. }
  8879. if (err) {
  8880. var safeResults = {};
  8881. _each(_keys(results), function(rkey) {
  8882. safeResults[rkey] = results[rkey];
  8883. });
  8884. safeResults[k] = args;
  8885. callback(err, safeResults);
  8886. // stop subsequent errors hitting callback multiple times
  8887. callback = function () {};
  8888. }
  8889. else {
  8890. results[k] = args;
  8891. async.setImmediate(taskComplete);
  8892. }
  8893. };
  8894. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  8895. var ready = function () {
  8896. return _reduce(requires, function (a, x) {
  8897. return (a && results.hasOwnProperty(x));
  8898. }, true) && !results.hasOwnProperty(k);
  8899. };
  8900. if (ready()) {
  8901. task[task.length - 1](taskCallback, results);
  8902. }
  8903. else {
  8904. var listener = function () {
  8905. if (ready()) {
  8906. removeListener(listener);
  8907. task[task.length - 1](taskCallback, results);
  8908. }
  8909. };
  8910. addListener(listener);
  8911. }
  8912. });
  8913. };
  8914. async.retry = function(times, task, callback) {
  8915. var DEFAULT_TIMES = 5;
  8916. var attempts = [];
  8917. // Use defaults if times not passed
  8918. if (typeof times === 'function') {
  8919. callback = task;
  8920. task = times;
  8921. times = DEFAULT_TIMES;
  8922. }
  8923. // Make sure times is a number
  8924. times = parseInt(times, 10) || DEFAULT_TIMES;
  8925. var wrappedTask = function(wrappedCallback, wrappedResults) {
  8926. var retryAttempt = function(task, finalAttempt) {
  8927. return function(seriesCallback) {
  8928. task(function(err, result){
  8929. seriesCallback(!err || finalAttempt, {err: err, result: result});
  8930. }, wrappedResults);
  8931. };
  8932. };
  8933. while (times) {
  8934. attempts.push(retryAttempt(task, !(times-=1)));
  8935. }
  8936. async.series(attempts, function(done, data){
  8937. data = data[data.length - 1];
  8938. (wrappedCallback || callback)(data.err, data.result);
  8939. });
  8940. }
  8941. // If a callback is passed, run this as a controll flow
  8942. return callback ? wrappedTask() : wrappedTask
  8943. };
  8944. async.waterfall = function (tasks, callback) {
  8945. callback = callback || function () {};
  8946. if (!_isArray(tasks)) {
  8947. var err = new Error('First argument to waterfall must be an array of functions');
  8948. return callback(err);
  8949. }
  8950. if (!tasks.length) {
  8951. return callback();
  8952. }
  8953. var wrapIterator = function (iterator) {
  8954. return function (err) {
  8955. if (err) {
  8956. callback.apply(null, arguments);
  8957. callback = function () {};
  8958. }
  8959. else {
  8960. var args = Array.prototype.slice.call(arguments, 1);
  8961. var next = iterator.next();
  8962. if (next) {
  8963. args.push(wrapIterator(next));
  8964. }
  8965. else {
  8966. args.push(callback);
  8967. }
  8968. async.setImmediate(function () {
  8969. iterator.apply(null, args);
  8970. });
  8971. }
  8972. };
  8973. };
  8974. wrapIterator(async.iterator(tasks))();
  8975. };
  8976. var _parallel = function(eachfn, tasks, callback) {
  8977. callback = callback || function () {};
  8978. if (_isArray(tasks)) {
  8979. eachfn.map(tasks, function (fn, callback) {
  8980. if (fn) {
  8981. fn(function (err) {
  8982. var args = Array.prototype.slice.call(arguments, 1);
  8983. if (args.length <= 1) {
  8984. args = args[0];
  8985. }
  8986. callback.call(null, err, args);
  8987. });
  8988. }
  8989. }, callback);
  8990. }
  8991. else {
  8992. var results = {};
  8993. eachfn.each(_keys(tasks), function (k, callback) {
  8994. tasks[k](function (err) {
  8995. var args = Array.prototype.slice.call(arguments, 1);
  8996. if (args.length <= 1) {
  8997. args = args[0];
  8998. }
  8999. results[k] = args;
  9000. callback(err);
  9001. });
  9002. }, function (err) {
  9003. callback(err, results);
  9004. });
  9005. }
  9006. };
  9007. async.parallel = function (tasks, callback) {
  9008. _parallel({ map: async.map, each: async.each }, tasks, callback);
  9009. };
  9010. async.parallelLimit = function(tasks, limit, callback) {
  9011. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  9012. };
  9013. async.series = function (tasks, callback) {
  9014. callback = callback || function () {};
  9015. if (_isArray(tasks)) {
  9016. async.mapSeries(tasks, function (fn, callback) {
  9017. if (fn) {
  9018. fn(function (err) {
  9019. var args = Array.prototype.slice.call(arguments, 1);
  9020. if (args.length <= 1) {
  9021. args = args[0];
  9022. }
  9023. callback.call(null, err, args);
  9024. });
  9025. }
  9026. }, callback);
  9027. }
  9028. else {
  9029. var results = {};
  9030. async.eachSeries(_keys(tasks), function (k, callback) {
  9031. tasks[k](function (err) {
  9032. var args = Array.prototype.slice.call(arguments, 1);
  9033. if (args.length <= 1) {
  9034. args = args[0];
  9035. }
  9036. results[k] = args;
  9037. callback(err);
  9038. });
  9039. }, function (err) {
  9040. callback(err, results);
  9041. });
  9042. }
  9043. };
  9044. async.iterator = function (tasks) {
  9045. var makeCallback = function (index) {
  9046. var fn = function () {
  9047. if (tasks.length) {
  9048. tasks[index].apply(null, arguments);
  9049. }
  9050. return fn.next();
  9051. };
  9052. fn.next = function () {
  9053. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  9054. };
  9055. return fn;
  9056. };
  9057. return makeCallback(0);
  9058. };
  9059. async.apply = function (fn) {
  9060. var args = Array.prototype.slice.call(arguments, 1);
  9061. return function () {
  9062. return fn.apply(
  9063. null, args.concat(Array.prototype.slice.call(arguments))
  9064. );
  9065. };
  9066. };
  9067. var _concat = function (eachfn, arr, fn, callback) {
  9068. var r = [];
  9069. eachfn(arr, function (x, cb) {
  9070. fn(x, function (err, y) {
  9071. r = r.concat(y || []);
  9072. cb(err);
  9073. });
  9074. }, function (err) {
  9075. callback(err, r);
  9076. });
  9077. };
  9078. async.concat = doParallel(_concat);
  9079. async.concatSeries = doSeries(_concat);
  9080. async.whilst = function (test, iterator, callback) {
  9081. if (test()) {
  9082. iterator(function (err) {
  9083. if (err) {
  9084. return callback(err);
  9085. }
  9086. async.whilst(test, iterator, callback);
  9087. });
  9088. }
  9089. else {
  9090. callback();
  9091. }
  9092. };
  9093. async.doWhilst = function (iterator, test, callback) {
  9094. iterator(function (err) {
  9095. if (err) {
  9096. return callback(err);
  9097. }
  9098. var args = Array.prototype.slice.call(arguments, 1);
  9099. if (test.apply(null, args)) {
  9100. async.doWhilst(iterator, test, callback);
  9101. }
  9102. else {
  9103. callback();
  9104. }
  9105. });
  9106. };
  9107. async.until = function (test, iterator, callback) {
  9108. if (!test()) {
  9109. iterator(function (err) {
  9110. if (err) {
  9111. return callback(err);
  9112. }
  9113. async.until(test, iterator, callback);
  9114. });
  9115. }
  9116. else {
  9117. callback();
  9118. }
  9119. };
  9120. async.doUntil = function (iterator, test, callback) {
  9121. iterator(function (err) {
  9122. if (err) {
  9123. return callback(err);
  9124. }
  9125. var args = Array.prototype.slice.call(arguments, 1);
  9126. if (!test.apply(null, args)) {
  9127. async.doUntil(iterator, test, callback);
  9128. }
  9129. else {
  9130. callback();
  9131. }
  9132. });
  9133. };
  9134. async.queue = function (worker, concurrency) {
  9135. if (concurrency === undefined) {
  9136. concurrency = 1;
  9137. }
  9138. function _insert(q, data, pos, callback) {
  9139. if (!q.started){
  9140. q.started = true;
  9141. }
  9142. if (!_isArray(data)) {
  9143. data = [data];
  9144. }
  9145. if(data.length == 0) {
  9146. // call drain immediately if there are no tasks
  9147. return async.setImmediate(function() {
  9148. if (q.drain) {
  9149. q.drain();
  9150. }
  9151. });
  9152. }
  9153. _each(data, function(task) {
  9154. var item = {
  9155. data: task,
  9156. callback: typeof callback === 'function' ? callback : null
  9157. };
  9158. if (pos) {
  9159. q.tasks.unshift(item);
  9160. } else {
  9161. q.tasks.push(item);
  9162. }
  9163. if (q.saturated && q.tasks.length === q.concurrency) {
  9164. q.saturated();
  9165. }
  9166. async.setImmediate(q.process);
  9167. });
  9168. }
  9169. var workers = 0;
  9170. var q = {
  9171. tasks: [],
  9172. concurrency: concurrency,
  9173. saturated: null,
  9174. empty: null,
  9175. drain: null,
  9176. started: false,
  9177. paused: false,
  9178. push: function (data, callback) {
  9179. _insert(q, data, false, callback);
  9180. },
  9181. kill: function () {
  9182. q.drain = null;
  9183. q.tasks = [];
  9184. },
  9185. unshift: function (data, callback) {
  9186. _insert(q, data, true, callback);
  9187. },
  9188. process: function () {
  9189. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  9190. var task = q.tasks.shift();
  9191. if (q.empty && q.tasks.length === 0) {
  9192. q.empty();
  9193. }
  9194. workers += 1;
  9195. var next = function () {
  9196. workers -= 1;
  9197. if (task.callback) {
  9198. task.callback.apply(task, arguments);
  9199. }
  9200. if (q.drain && q.tasks.length + workers === 0) {
  9201. q.drain();
  9202. }
  9203. q.process();
  9204. };
  9205. var cb = only_once(next);
  9206. worker(task.data, cb);
  9207. }
  9208. },
  9209. length: function () {
  9210. return q.tasks.length;
  9211. },
  9212. running: function () {
  9213. return workers;
  9214. },
  9215. idle: function() {
  9216. return q.tasks.length + workers === 0;
  9217. },
  9218. pause: function () {
  9219. if (q.paused === true) { return; }
  9220. q.paused = true;
  9221. q.process();
  9222. },
  9223. resume: function () {
  9224. if (q.paused === false) { return; }
  9225. q.paused = false;
  9226. q.process();
  9227. }
  9228. };
  9229. return q;
  9230. };
  9231. async.priorityQueue = function (worker, concurrency) {
  9232. function _compareTasks(a, b){
  9233. return a.priority - b.priority;
  9234. };
  9235. function _binarySearch(sequence, item, compare) {
  9236. var beg = -1,
  9237. end = sequence.length - 1;
  9238. while (beg < end) {
  9239. var mid = beg + ((end - beg + 1) >>> 1);
  9240. if (compare(item, sequence[mid]) >= 0) {
  9241. beg = mid;
  9242. } else {
  9243. end = mid - 1;
  9244. }
  9245. }
  9246. return beg;
  9247. }
  9248. function _insert(q, data, priority, callback) {
  9249. if (!q.started){
  9250. q.started = true;
  9251. }
  9252. if (!_isArray(data)) {
  9253. data = [data];
  9254. }
  9255. if(data.length == 0) {
  9256. // call drain immediately if there are no tasks
  9257. return async.setImmediate(function() {
  9258. if (q.drain) {
  9259. q.drain();
  9260. }
  9261. });
  9262. }
  9263. _each(data, function(task) {
  9264. var item = {
  9265. data: task,
  9266. priority: priority,
  9267. callback: typeof callback === 'function' ? callback : null
  9268. };
  9269. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  9270. if (q.saturated && q.tasks.length === q.concurrency) {
  9271. q.saturated();
  9272. }
  9273. async.setImmediate(q.process);
  9274. });
  9275. }
  9276. // Start with a normal queue
  9277. var q = async.queue(worker, concurrency);
  9278. // Override push to accept second parameter representing priority
  9279. q.push = function (data, priority, callback) {
  9280. _insert(q, data, priority, callback);
  9281. };
  9282. // Remove unshift function
  9283. delete q.unshift;
  9284. return q;
  9285. };
  9286. async.cargo = function (worker, payload) {
  9287. var working = false,
  9288. tasks = [];
  9289. var cargo = {
  9290. tasks: tasks,
  9291. payload: payload,
  9292. saturated: null,
  9293. empty: null,
  9294. drain: null,
  9295. drained: true,
  9296. push: function (data, callback) {
  9297. if (!_isArray(data)) {
  9298. data = [data];
  9299. }
  9300. _each(data, function(task) {
  9301. tasks.push({
  9302. data: task,
  9303. callback: typeof callback === 'function' ? callback : null
  9304. });
  9305. cargo.drained = false;
  9306. if (cargo.saturated && tasks.length === payload) {
  9307. cargo.saturated();
  9308. }
  9309. });
  9310. async.setImmediate(cargo.process);
  9311. },
  9312. process: function process() {
  9313. if (working) return;
  9314. if (tasks.length === 0) {
  9315. if(cargo.drain && !cargo.drained) cargo.drain();
  9316. cargo.drained = true;
  9317. return;
  9318. }
  9319. var ts = typeof payload === 'number'
  9320. ? tasks.splice(0, payload)
  9321. : tasks.splice(0, tasks.length);
  9322. var ds = _map(ts, function (task) {
  9323. return task.data;
  9324. });
  9325. if(cargo.empty) cargo.empty();
  9326. working = true;
  9327. worker(ds, function () {
  9328. working = false;
  9329. var args = arguments;
  9330. _each(ts, function (data) {
  9331. if (data.callback) {
  9332. data.callback.apply(null, args);
  9333. }
  9334. });
  9335. process();
  9336. });
  9337. },
  9338. length: function () {
  9339. return tasks.length;
  9340. },
  9341. running: function () {
  9342. return working;
  9343. }
  9344. };
  9345. return cargo;
  9346. };
  9347. var _console_fn = function (name) {
  9348. return function (fn) {
  9349. var args = Array.prototype.slice.call(arguments, 1);
  9350. fn.apply(null, args.concat([function (err) {
  9351. var args = Array.prototype.slice.call(arguments, 1);
  9352. if (typeof console !== 'undefined') {
  9353. if (err) {
  9354. if (console.error) {
  9355. console.error(err);
  9356. }
  9357. }
  9358. else if (console[name]) {
  9359. _each(args, function (x) {
  9360. console[name](x);
  9361. });
  9362. }
  9363. }
  9364. }]));
  9365. };
  9366. };
  9367. async.log = _console_fn('log');
  9368. async.dir = _console_fn('dir');
  9369. /*async.info = _console_fn('info');
  9370. async.warn = _console_fn('warn');
  9371. async.error = _console_fn('error');*/
  9372. async.memoize = function (fn, hasher) {
  9373. var memo = {};
  9374. var queues = {};
  9375. hasher = hasher || function (x) {
  9376. return x;
  9377. };
  9378. var memoized = function () {
  9379. var args = Array.prototype.slice.call(arguments);
  9380. var callback = args.pop();
  9381. var key = hasher.apply(null, args);
  9382. if (key in memo) {
  9383. async.nextTick(function () {
  9384. callback.apply(null, memo[key]);
  9385. });
  9386. }
  9387. else if (key in queues) {
  9388. queues[key].push(callback);
  9389. }
  9390. else {
  9391. queues[key] = [callback];
  9392. fn.apply(null, args.concat([function () {
  9393. memo[key] = arguments;
  9394. var q = queues[key];
  9395. delete queues[key];
  9396. for (var i = 0, l = q.length; i < l; i++) {
  9397. q[i].apply(null, arguments);
  9398. }
  9399. }]));
  9400. }
  9401. };
  9402. memoized.memo = memo;
  9403. memoized.unmemoized = fn;
  9404. return memoized;
  9405. };
  9406. async.unmemoize = function (fn) {
  9407. return function () {
  9408. return (fn.unmemoized || fn).apply(null, arguments);
  9409. };
  9410. };
  9411. async.times = function (count, iterator, callback) {
  9412. var counter = [];
  9413. for (var i = 0; i < count; i++) {
  9414. counter.push(i);
  9415. }
  9416. return async.map(counter, iterator, callback);
  9417. };
  9418. async.timesSeries = function (count, iterator, callback) {
  9419. var counter = [];
  9420. for (var i = 0; i < count; i++) {
  9421. counter.push(i);
  9422. }
  9423. return async.mapSeries(counter, iterator, callback);
  9424. };
  9425. async.seq = function (/* functions... */) {
  9426. var fns = arguments;
  9427. return function () {
  9428. var that = this;
  9429. var args = Array.prototype.slice.call(arguments);
  9430. var callback = args.pop();
  9431. async.reduce(fns, args, function (newargs, fn, cb) {
  9432. fn.apply(that, newargs.concat([function () {
  9433. var err = arguments[0];
  9434. var nextargs = Array.prototype.slice.call(arguments, 1);
  9435. cb(err, nextargs);
  9436. }]))
  9437. },
  9438. function (err, results) {
  9439. callback.apply(that, [err].concat(results));
  9440. });
  9441. };
  9442. };
  9443. async.compose = function (/* functions... */) {
  9444. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  9445. };
  9446. var _applyEach = function (eachfn, fns /*args...*/) {
  9447. var go = function () {
  9448. var that = this;
  9449. var args = Array.prototype.slice.call(arguments);
  9450. var callback = args.pop();
  9451. return eachfn(fns, function (fn, cb) {
  9452. fn.apply(that, args.concat([cb]));
  9453. },
  9454. callback);
  9455. };
  9456. if (arguments.length > 2) {
  9457. var args = Array.prototype.slice.call(arguments, 2);
  9458. return go.apply(this, args);
  9459. }
  9460. else {
  9461. return go;
  9462. }
  9463. };
  9464. async.applyEach = doParallel(_applyEach);
  9465. async.applyEachSeries = doSeries(_applyEach);
  9466. async.forever = function (fn, callback) {
  9467. function next(err) {
  9468. if (err) {
  9469. if (callback) {
  9470. return callback(err);
  9471. }
  9472. throw err;
  9473. }
  9474. fn(next);
  9475. }
  9476. next();
  9477. };
  9478. // Node.js
  9479. if (typeof module !== 'undefined' && module.exports) {
  9480. module.exports = async;
  9481. }
  9482. // AMD / RequireJS
  9483. else if (typeof define !== 'undefined' && define.amd) {
  9484. define([], function () {
  9485. return async;
  9486. });
  9487. }
  9488. // included directly via <script> tag
  9489. else {
  9490. root.async = async;
  9491. }
  9492. }());
  9493. }).call(this,require('_process'))
  9494. },{"_process":78}],35:[function(require,module,exports){
  9495. (function (process,global){
  9496. /*!
  9497. * @overview es6-promise - a tiny implementation of Promises/A+.
  9498. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  9499. * @license Licensed under MIT license
  9500. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  9501. * @version 3.0.2
  9502. */
  9503. (function() {
  9504. "use strict";
  9505. function lib$es6$promise$utils$$objectOrFunction(x) {
  9506. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  9507. }
  9508. function lib$es6$promise$utils$$isFunction(x) {
  9509. return typeof x === 'function';
  9510. }
  9511. function lib$es6$promise$utils$$isMaybeThenable(x) {
  9512. return typeof x === 'object' && x !== null;
  9513. }
  9514. var lib$es6$promise$utils$$_isArray;
  9515. if (!Array.isArray) {
  9516. lib$es6$promise$utils$$_isArray = function (x) {
  9517. return Object.prototype.toString.call(x) === '[object Array]';
  9518. };
  9519. } else {
  9520. lib$es6$promise$utils$$_isArray = Array.isArray;
  9521. }
  9522. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  9523. var lib$es6$promise$asap$$len = 0;
  9524. var lib$es6$promise$asap$$toString = {}.toString;
  9525. var lib$es6$promise$asap$$vertxNext;
  9526. var lib$es6$promise$asap$$customSchedulerFn;
  9527. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  9528. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  9529. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  9530. lib$es6$promise$asap$$len += 2;
  9531. if (lib$es6$promise$asap$$len === 2) {
  9532. // If len is 2, that means that we need to schedule an async flush.
  9533. // If additional callbacks are queued before the queue is flushed, they
  9534. // will be processed by this flush that we are scheduling.
  9535. if (lib$es6$promise$asap$$customSchedulerFn) {
  9536. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  9537. } else {
  9538. lib$es6$promise$asap$$scheduleFlush();
  9539. }
  9540. }
  9541. }
  9542. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  9543. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  9544. }
  9545. function lib$es6$promise$asap$$setAsap(asapFn) {
  9546. lib$es6$promise$asap$$asap = asapFn;
  9547. }
  9548. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  9549. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  9550. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  9551. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  9552. // test for web worker but not in IE10
  9553. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  9554. typeof importScripts !== 'undefined' &&
  9555. typeof MessageChannel !== 'undefined';
  9556. // node
  9557. function lib$es6$promise$asap$$useNextTick() {
  9558. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  9559. // see https://github.com/cujojs/when/issues/410 for details
  9560. return function() {
  9561. process.nextTick(lib$es6$promise$asap$$flush);
  9562. };
  9563. }
  9564. // vertx
  9565. function lib$es6$promise$asap$$useVertxTimer() {
  9566. return function() {
  9567. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  9568. };
  9569. }
  9570. function lib$es6$promise$asap$$useMutationObserver() {
  9571. var iterations = 0;
  9572. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  9573. var node = document.createTextNode('');
  9574. observer.observe(node, { characterData: true });
  9575. return function() {
  9576. node.data = (iterations = ++iterations % 2);
  9577. };
  9578. }
  9579. // web worker
  9580. function lib$es6$promise$asap$$useMessageChannel() {
  9581. var channel = new MessageChannel();
  9582. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  9583. return function () {
  9584. channel.port2.postMessage(0);
  9585. };
  9586. }
  9587. function lib$es6$promise$asap$$useSetTimeout() {
  9588. return function() {
  9589. setTimeout(lib$es6$promise$asap$$flush, 1);
  9590. };
  9591. }
  9592. var lib$es6$promise$asap$$queue = new Array(1000);
  9593. function lib$es6$promise$asap$$flush() {
  9594. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  9595. var callback = lib$es6$promise$asap$$queue[i];
  9596. var arg = lib$es6$promise$asap$$queue[i+1];
  9597. callback(arg);
  9598. lib$es6$promise$asap$$queue[i] = undefined;
  9599. lib$es6$promise$asap$$queue[i+1] = undefined;
  9600. }
  9601. lib$es6$promise$asap$$len = 0;
  9602. }
  9603. function lib$es6$promise$asap$$attemptVertx() {
  9604. try {
  9605. var r = require;
  9606. var vertx = r('vertx');
  9607. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  9608. return lib$es6$promise$asap$$useVertxTimer();
  9609. } catch(e) {
  9610. return lib$es6$promise$asap$$useSetTimeout();
  9611. }
  9612. }
  9613. var lib$es6$promise$asap$$scheduleFlush;
  9614. // Decide what async method to use to triggering processing of queued callbacks:
  9615. if (lib$es6$promise$asap$$isNode) {
  9616. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  9617. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  9618. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  9619. } else if (lib$es6$promise$asap$$isWorker) {
  9620. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  9621. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  9622. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  9623. } else {
  9624. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  9625. }
  9626. function lib$es6$promise$$internal$$noop() {}
  9627. var lib$es6$promise$$internal$$PENDING = void 0;
  9628. var lib$es6$promise$$internal$$FULFILLED = 1;
  9629. var lib$es6$promise$$internal$$REJECTED = 2;
  9630. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  9631. function lib$es6$promise$$internal$$selfFulfillment() {
  9632. return new TypeError("You cannot resolve a promise with itself");
  9633. }
  9634. function lib$es6$promise$$internal$$cannotReturnOwn() {
  9635. return new TypeError('A promises callback cannot return that same promise.');
  9636. }
  9637. function lib$es6$promise$$internal$$getThen(promise) {
  9638. try {
  9639. return promise.then;
  9640. } catch(error) {
  9641. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  9642. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  9643. }
  9644. }
  9645. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  9646. try {
  9647. then.call(value, fulfillmentHandler, rejectionHandler);
  9648. } catch(e) {
  9649. return e;
  9650. }
  9651. }
  9652. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  9653. lib$es6$promise$asap$$asap(function(promise) {
  9654. var sealed = false;
  9655. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  9656. if (sealed) { return; }
  9657. sealed = true;
  9658. if (thenable !== value) {
  9659. lib$es6$promise$$internal$$resolve(promise, value);
  9660. } else {
  9661. lib$es6$promise$$internal$$fulfill(promise, value);
  9662. }
  9663. }, function(reason) {
  9664. if (sealed) { return; }
  9665. sealed = true;
  9666. lib$es6$promise$$internal$$reject(promise, reason);
  9667. }, 'Settle: ' + (promise._label || ' unknown promise'));
  9668. if (!sealed && error) {
  9669. sealed = true;
  9670. lib$es6$promise$$internal$$reject(promise, error);
  9671. }
  9672. }, promise);
  9673. }
  9674. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  9675. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  9676. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  9677. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  9678. lib$es6$promise$$internal$$reject(promise, thenable._result);
  9679. } else {
  9680. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  9681. lib$es6$promise$$internal$$resolve(promise, value);
  9682. }, function(reason) {
  9683. lib$es6$promise$$internal$$reject(promise, reason);
  9684. });
  9685. }
  9686. }
  9687. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  9688. if (maybeThenable.constructor === promise.constructor) {
  9689. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  9690. } else {
  9691. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  9692. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  9693. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  9694. } else if (then === undefined) {
  9695. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  9696. } else if (lib$es6$promise$utils$$isFunction(then)) {
  9697. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  9698. } else {
  9699. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  9700. }
  9701. }
  9702. }
  9703. function lib$es6$promise$$internal$$resolve(promise, value) {
  9704. if (promise === value) {
  9705. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  9706. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  9707. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  9708. } else {
  9709. lib$es6$promise$$internal$$fulfill(promise, value);
  9710. }
  9711. }
  9712. function lib$es6$promise$$internal$$publishRejection(promise) {
  9713. if (promise._onerror) {
  9714. promise._onerror(promise._result);
  9715. }
  9716. lib$es6$promise$$internal$$publish(promise);
  9717. }
  9718. function lib$es6$promise$$internal$$fulfill(promise, value) {
  9719. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  9720. promise._result = value;
  9721. promise._state = lib$es6$promise$$internal$$FULFILLED;
  9722. if (promise._subscribers.length !== 0) {
  9723. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  9724. }
  9725. }
  9726. function lib$es6$promise$$internal$$reject(promise, reason) {
  9727. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  9728. promise._state = lib$es6$promise$$internal$$REJECTED;
  9729. promise._result = reason;
  9730. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  9731. }
  9732. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  9733. var subscribers = parent._subscribers;
  9734. var length = subscribers.length;
  9735. parent._onerror = null;
  9736. subscribers[length] = child;
  9737. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  9738. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  9739. if (length === 0 && parent._state) {
  9740. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  9741. }
  9742. }
  9743. function lib$es6$promise$$internal$$publish(promise) {
  9744. var subscribers = promise._subscribers;
  9745. var settled = promise._state;
  9746. if (subscribers.length === 0) { return; }
  9747. var child, callback, detail = promise._result;
  9748. for (var i = 0; i < subscribers.length; i += 3) {
  9749. child = subscribers[i];
  9750. callback = subscribers[i + settled];
  9751. if (child) {
  9752. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  9753. } else {
  9754. callback(detail);
  9755. }
  9756. }
  9757. promise._subscribers.length = 0;
  9758. }
  9759. function lib$es6$promise$$internal$$ErrorObject() {
  9760. this.error = null;
  9761. }
  9762. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  9763. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  9764. try {
  9765. return callback(detail);
  9766. } catch(e) {
  9767. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  9768. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  9769. }
  9770. }
  9771. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  9772. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  9773. value, error, succeeded, failed;
  9774. if (hasCallback) {
  9775. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  9776. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  9777. failed = true;
  9778. error = value.error;
  9779. value = null;
  9780. } else {
  9781. succeeded = true;
  9782. }
  9783. if (promise === value) {
  9784. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  9785. return;
  9786. }
  9787. } else {
  9788. value = detail;
  9789. succeeded = true;
  9790. }
  9791. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  9792. // noop
  9793. } else if (hasCallback && succeeded) {
  9794. lib$es6$promise$$internal$$resolve(promise, value);
  9795. } else if (failed) {
  9796. lib$es6$promise$$internal$$reject(promise, error);
  9797. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  9798. lib$es6$promise$$internal$$fulfill(promise, value);
  9799. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  9800. lib$es6$promise$$internal$$reject(promise, value);
  9801. }
  9802. }
  9803. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  9804. try {
  9805. resolver(function resolvePromise(value){
  9806. lib$es6$promise$$internal$$resolve(promise, value);
  9807. }, function rejectPromise(reason) {
  9808. lib$es6$promise$$internal$$reject(promise, reason);
  9809. });
  9810. } catch(e) {
  9811. lib$es6$promise$$internal$$reject(promise, e);
  9812. }
  9813. }
  9814. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  9815. var enumerator = this;
  9816. enumerator._instanceConstructor = Constructor;
  9817. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  9818. if (enumerator._validateInput(input)) {
  9819. enumerator._input = input;
  9820. enumerator.length = input.length;
  9821. enumerator._remaining = input.length;
  9822. enumerator._init();
  9823. if (enumerator.length === 0) {
  9824. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  9825. } else {
  9826. enumerator.length = enumerator.length || 0;
  9827. enumerator._enumerate();
  9828. if (enumerator._remaining === 0) {
  9829. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  9830. }
  9831. }
  9832. } else {
  9833. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  9834. }
  9835. }
  9836. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  9837. return lib$es6$promise$utils$$isArray(input);
  9838. };
  9839. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  9840. return new Error('Array Methods must be provided an Array');
  9841. };
  9842. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  9843. this._result = new Array(this.length);
  9844. };
  9845. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  9846. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  9847. var enumerator = this;
  9848. var length = enumerator.length;
  9849. var promise = enumerator.promise;
  9850. var input = enumerator._input;
  9851. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  9852. enumerator._eachEntry(input[i], i);
  9853. }
  9854. };
  9855. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  9856. var enumerator = this;
  9857. var c = enumerator._instanceConstructor;
  9858. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  9859. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  9860. entry._onerror = null;
  9861. enumerator._settledAt(entry._state, i, entry._result);
  9862. } else {
  9863. enumerator._willSettleAt(c.resolve(entry), i);
  9864. }
  9865. } else {
  9866. enumerator._remaining--;
  9867. enumerator._result[i] = entry;
  9868. }
  9869. };
  9870. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  9871. var enumerator = this;
  9872. var promise = enumerator.promise;
  9873. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  9874. enumerator._remaining--;
  9875. if (state === lib$es6$promise$$internal$$REJECTED) {
  9876. lib$es6$promise$$internal$$reject(promise, value);
  9877. } else {
  9878. enumerator._result[i] = value;
  9879. }
  9880. }
  9881. if (enumerator._remaining === 0) {
  9882. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  9883. }
  9884. };
  9885. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  9886. var enumerator = this;
  9887. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  9888. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  9889. }, function(reason) {
  9890. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  9891. });
  9892. };
  9893. function lib$es6$promise$promise$all$$all(entries) {
  9894. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  9895. }
  9896. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  9897. function lib$es6$promise$promise$race$$race(entries) {
  9898. /*jshint validthis:true */
  9899. var Constructor = this;
  9900. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  9901. if (!lib$es6$promise$utils$$isArray(entries)) {
  9902. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  9903. return promise;
  9904. }
  9905. var length = entries.length;
  9906. function onFulfillment(value) {
  9907. lib$es6$promise$$internal$$resolve(promise, value);
  9908. }
  9909. function onRejection(reason) {
  9910. lib$es6$promise$$internal$$reject(promise, reason);
  9911. }
  9912. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  9913. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  9914. }
  9915. return promise;
  9916. }
  9917. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  9918. function lib$es6$promise$promise$resolve$$resolve(object) {
  9919. /*jshint validthis:true */
  9920. var Constructor = this;
  9921. if (object && typeof object === 'object' && object.constructor === Constructor) {
  9922. return object;
  9923. }
  9924. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  9925. lib$es6$promise$$internal$$resolve(promise, object);
  9926. return promise;
  9927. }
  9928. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  9929. function lib$es6$promise$promise$reject$$reject(reason) {
  9930. /*jshint validthis:true */
  9931. var Constructor = this;
  9932. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  9933. lib$es6$promise$$internal$$reject(promise, reason);
  9934. return promise;
  9935. }
  9936. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  9937. var lib$es6$promise$promise$$counter = 0;
  9938. function lib$es6$promise$promise$$needsResolver() {
  9939. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  9940. }
  9941. function lib$es6$promise$promise$$needsNew() {
  9942. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  9943. }
  9944. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  9945. /**
  9946. Promise objects represent the eventual result of an asynchronous operation. The
  9947. primary way of interacting with a promise is through its `then` method, which
  9948. registers callbacks to receive either a promise's eventual value or the reason
  9949. why the promise cannot be fulfilled.
  9950. Terminology
  9951. -----------
  9952. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  9953. - `thenable` is an object or function that defines a `then` method.
  9954. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  9955. - `exception` is a value that is thrown using the throw statement.
  9956. - `reason` is a value that indicates why a promise was rejected.
  9957. - `settled` the final resting state of a promise, fulfilled or rejected.
  9958. A promise can be in one of three states: pending, fulfilled, or rejected.
  9959. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  9960. state. Promises that are rejected have a rejection reason and are in the
  9961. rejected state. A fulfillment value is never a thenable.
  9962. Promises can also be said to *resolve* a value. If this value is also a
  9963. promise, then the original promise's settled state will match the value's
  9964. settled state. So a promise that *resolves* a promise that rejects will
  9965. itself reject, and a promise that *resolves* a promise that fulfills will
  9966. itself fulfill.
  9967. Basic Usage:
  9968. ------------
  9969. ```js
  9970. var promise = new Promise(function(resolve, reject) {
  9971. // on success
  9972. resolve(value);
  9973. // on failure
  9974. reject(reason);
  9975. });
  9976. promise.then(function(value) {
  9977. // on fulfillment
  9978. }, function(reason) {
  9979. // on rejection
  9980. });
  9981. ```
  9982. Advanced Usage:
  9983. ---------------
  9984. Promises shine when abstracting away asynchronous interactions such as
  9985. `XMLHttpRequest`s.
  9986. ```js
  9987. function getJSON(url) {
  9988. return new Promise(function(resolve, reject){
  9989. var xhr = new XMLHttpRequest();
  9990. xhr.open('GET', url);
  9991. xhr.onreadystatechange = handler;
  9992. xhr.responseType = 'json';
  9993. xhr.setRequestHeader('Accept', 'application/json');
  9994. xhr.send();
  9995. function handler() {
  9996. if (this.readyState === this.DONE) {
  9997. if (this.status === 200) {
  9998. resolve(this.response);
  9999. } else {
  10000. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  10001. }
  10002. }
  10003. };
  10004. });
  10005. }
  10006. getJSON('/posts.json').then(function(json) {
  10007. // on fulfillment
  10008. }, function(reason) {
  10009. // on rejection
  10010. });
  10011. ```
  10012. Unlike callbacks, promises are great composable primitives.
  10013. ```js
  10014. Promise.all([
  10015. getJSON('/posts'),
  10016. getJSON('/comments')
  10017. ]).then(function(values){
  10018. values[0] // => postsJSON
  10019. values[1] // => commentsJSON
  10020. return values;
  10021. });
  10022. ```
  10023. @class Promise
  10024. @param {function} resolver
  10025. Useful for tooling.
  10026. @constructor
  10027. */
  10028. function lib$es6$promise$promise$$Promise(resolver) {
  10029. this._id = lib$es6$promise$promise$$counter++;
  10030. this._state = undefined;
  10031. this._result = undefined;
  10032. this._subscribers = [];
  10033. if (lib$es6$promise$$internal$$noop !== resolver) {
  10034. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  10035. lib$es6$promise$promise$$needsResolver();
  10036. }
  10037. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  10038. lib$es6$promise$promise$$needsNew();
  10039. }
  10040. lib$es6$promise$$internal$$initializePromise(this, resolver);
  10041. }
  10042. }
  10043. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  10044. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  10045. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  10046. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  10047. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  10048. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  10049. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  10050. lib$es6$promise$promise$$Promise.prototype = {
  10051. constructor: lib$es6$promise$promise$$Promise,
  10052. /**
  10053. The primary way of interacting with a promise is through its `then` method,
  10054. which registers callbacks to receive either a promise's eventual value or the
  10055. reason why the promise cannot be fulfilled.
  10056. ```js
  10057. findUser().then(function(user){
  10058. // user is available
  10059. }, function(reason){
  10060. // user is unavailable, and you are given the reason why
  10061. });
  10062. ```
  10063. Chaining
  10064. --------
  10065. The return value of `then` is itself a promise. This second, 'downstream'
  10066. promise is resolved with the return value of the first promise's fulfillment
  10067. or rejection handler, or rejected if the handler throws an exception.
  10068. ```js
  10069. findUser().then(function (user) {
  10070. return user.name;
  10071. }, function (reason) {
  10072. return 'default name';
  10073. }).then(function (userName) {
  10074. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  10075. // will be `'default name'`
  10076. });
  10077. findUser().then(function (user) {
  10078. throw new Error('Found user, but still unhappy');
  10079. }, function (reason) {
  10080. throw new Error('`findUser` rejected and we're unhappy');
  10081. }).then(function (value) {
  10082. // never reached
  10083. }, function (reason) {
  10084. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  10085. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  10086. });
  10087. ```
  10088. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  10089. ```js
  10090. findUser().then(function (user) {
  10091. throw new PedagogicalException('Upstream error');
  10092. }).then(function (value) {
  10093. // never reached
  10094. }).then(function (value) {
  10095. // never reached
  10096. }, function (reason) {
  10097. // The `PedgagocialException` is propagated all the way down to here
  10098. });
  10099. ```
  10100. Assimilation
  10101. ------------
  10102. Sometimes the value you want to propagate to a downstream promise can only be
  10103. retrieved asynchronously. This can be achieved by returning a promise in the
  10104. fulfillment or rejection handler. The downstream promise will then be pending
  10105. until the returned promise is settled. This is called *assimilation*.
  10106. ```js
  10107. findUser().then(function (user) {
  10108. return findCommentsByAuthor(user);
  10109. }).then(function (comments) {
  10110. // The user's comments are now available
  10111. });
  10112. ```
  10113. If the assimliated promise rejects, then the downstream promise will also reject.
  10114. ```js
  10115. findUser().then(function (user) {
  10116. return findCommentsByAuthor(user);
  10117. }).then(function (comments) {
  10118. // If `findCommentsByAuthor` fulfills, we'll have the value here
  10119. }, function (reason) {
  10120. // If `findCommentsByAuthor` rejects, we'll have the reason here
  10121. });
  10122. ```
  10123. Simple Example
  10124. --------------
  10125. Synchronous Example
  10126. ```javascript
  10127. var result;
  10128. try {
  10129. result = findResult();
  10130. // success
  10131. } catch(reason) {
  10132. // failure
  10133. }
  10134. ```
  10135. Errback Example
  10136. ```js
  10137. findResult(function(result, err){
  10138. if (err) {
  10139. // failure
  10140. } else {
  10141. // success
  10142. }
  10143. });
  10144. ```
  10145. Promise Example;
  10146. ```javascript
  10147. findResult().then(function(result){
  10148. // success
  10149. }, function(reason){
  10150. // failure
  10151. });
  10152. ```
  10153. Advanced Example
  10154. --------------
  10155. Synchronous Example
  10156. ```javascript
  10157. var author, books;
  10158. try {
  10159. author = findAuthor();
  10160. books = findBooksByAuthor(author);
  10161. // success
  10162. } catch(reason) {
  10163. // failure
  10164. }
  10165. ```
  10166. Errback Example
  10167. ```js
  10168. function foundBooks(books) {
  10169. }
  10170. function failure(reason) {
  10171. }
  10172. findAuthor(function(author, err){
  10173. if (err) {
  10174. failure(err);
  10175. // failure
  10176. } else {
  10177. try {
  10178. findBoooksByAuthor(author, function(books, err) {
  10179. if (err) {
  10180. failure(err);
  10181. } else {
  10182. try {
  10183. foundBooks(books);
  10184. } catch(reason) {
  10185. failure(reason);
  10186. }
  10187. }
  10188. });
  10189. } catch(error) {
  10190. failure(err);
  10191. }
  10192. // success
  10193. }
  10194. });
  10195. ```
  10196. Promise Example;
  10197. ```javascript
  10198. findAuthor().
  10199. then(findBooksByAuthor).
  10200. then(function(books){
  10201. // found books
  10202. }).catch(function(reason){
  10203. // something went wrong
  10204. });
  10205. ```
  10206. @method then
  10207. @param {Function} onFulfilled
  10208. @param {Function} onRejected
  10209. Useful for tooling.
  10210. @return {Promise}
  10211. */
  10212. then: function(onFulfillment, onRejection) {
  10213. var parent = this;
  10214. var state = parent._state;
  10215. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  10216. return this;
  10217. }
  10218. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  10219. var result = parent._result;
  10220. if (state) {
  10221. var callback = arguments[state - 1];
  10222. lib$es6$promise$asap$$asap(function(){
  10223. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  10224. });
  10225. } else {
  10226. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  10227. }
  10228. return child;
  10229. },
  10230. /**
  10231. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  10232. as the catch block of a try/catch statement.
  10233. ```js
  10234. function findAuthor(){
  10235. throw new Error('couldn't find that author');
  10236. }
  10237. // synchronous
  10238. try {
  10239. findAuthor();
  10240. } catch(reason) {
  10241. // something went wrong
  10242. }
  10243. // async with promises
  10244. findAuthor().catch(function(reason){
  10245. // something went wrong
  10246. });
  10247. ```
  10248. @method catch
  10249. @param {Function} onRejection
  10250. Useful for tooling.
  10251. @return {Promise}
  10252. */
  10253. 'catch': function(onRejection) {
  10254. return this.then(null, onRejection);
  10255. }
  10256. };
  10257. function lib$es6$promise$polyfill$$polyfill() {
  10258. var local;
  10259. if (typeof global !== 'undefined') {
  10260. local = global;
  10261. } else if (typeof self !== 'undefined') {
  10262. local = self;
  10263. } else {
  10264. try {
  10265. local = Function('return this')();
  10266. } catch (e) {
  10267. throw new Error('polyfill failed because global object is unavailable in this environment');
  10268. }
  10269. }
  10270. var P = local.Promise;
  10271. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  10272. return;
  10273. }
  10274. local.Promise = lib$es6$promise$promise$$default;
  10275. }
  10276. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  10277. var lib$es6$promise$umd$$ES6Promise = {
  10278. 'Promise': lib$es6$promise$promise$$default,
  10279. 'polyfill': lib$es6$promise$polyfill$$default
  10280. };
  10281. /* global define:true module:true window: true */
  10282. if (typeof define === 'function' && define['amd']) {
  10283. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  10284. } else if (typeof module !== 'undefined' && module['exports']) {
  10285. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  10286. } else if (typeof this !== 'undefined') {
  10287. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  10288. }
  10289. lib$es6$promise$polyfill$$default();
  10290. }).call(this);
  10291. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  10292. },{"_process":78}],36:[function(require,module,exports){
  10293. // Top level file is just a mixin of submodules & constants
  10294. 'use strict';
  10295. var assign = require('./lib/utils/common').assign;
  10296. var deflate = require('./lib/deflate');
  10297. var inflate = require('./lib/inflate');
  10298. var constants = require('./lib/zlib/constants');
  10299. var pako = {};
  10300. assign(pako, deflate, inflate, constants);
  10301. module.exports = pako;
  10302. },{"./lib/deflate":37,"./lib/inflate":38,"./lib/utils/common":39,"./lib/zlib/constants":42}],37:[function(require,module,exports){
  10303. 'use strict';
  10304. var zlib_deflate = require('./zlib/deflate.js');
  10305. var utils = require('./utils/common');
  10306. var strings = require('./utils/strings');
  10307. var msg = require('./zlib/messages');
  10308. var zstream = require('./zlib/zstream');
  10309. var toString = Object.prototype.toString;
  10310. /* Public constants ==========================================================*/
  10311. /* ===========================================================================*/
  10312. var Z_NO_FLUSH = 0;
  10313. var Z_FINISH = 4;
  10314. var Z_OK = 0;
  10315. var Z_STREAM_END = 1;
  10316. var Z_SYNC_FLUSH = 2;
  10317. var Z_DEFAULT_COMPRESSION = -1;
  10318. var Z_DEFAULT_STRATEGY = 0;
  10319. var Z_DEFLATED = 8;
  10320. /* ===========================================================================*/
  10321. /**
  10322. * class Deflate
  10323. *
  10324. * Generic JS-style wrapper for zlib calls. If you don't need
  10325. * streaming behaviour - use more simple functions: [[deflate]],
  10326. * [[deflateRaw]] and [[gzip]].
  10327. **/
  10328. /* internal
  10329. * Deflate.chunks -> Array
  10330. *
  10331. * Chunks of output data, if [[Deflate#onData]] not overriden.
  10332. **/
  10333. /**
  10334. * Deflate.result -> Uint8Array|Array
  10335. *
  10336. * Compressed result, generated by default [[Deflate#onData]]
  10337. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  10338. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  10339. * push a chunk with explicit flush (call [[Deflate#push]] with
  10340. * `Z_SYNC_FLUSH` param).
  10341. **/
  10342. /**
  10343. * Deflate.err -> Number
  10344. *
  10345. * Error code after deflate finished. 0 (Z_OK) on success.
  10346. * You will not need it in real life, because deflate errors
  10347. * are possible only on wrong options or bad `onData` / `onEnd`
  10348. * custom handlers.
  10349. **/
  10350. /**
  10351. * Deflate.msg -> String
  10352. *
  10353. * Error message, if [[Deflate.err]] != 0
  10354. **/
  10355. /**
  10356. * new Deflate(options)
  10357. * - options (Object): zlib deflate options.
  10358. *
  10359. * Creates new deflator instance with specified params. Throws exception
  10360. * on bad params. Supported options:
  10361. *
  10362. * - `level`
  10363. * - `windowBits`
  10364. * - `memLevel`
  10365. * - `strategy`
  10366. *
  10367. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  10368. * for more information on these.
  10369. *
  10370. * Additional options, for internal needs:
  10371. *
  10372. * - `chunkSize` - size of generated data chunks (16K by default)
  10373. * - `raw` (Boolean) - do raw deflate
  10374. * - `gzip` (Boolean) - create gzip wrapper
  10375. * - `to` (String) - if equal to 'string', then result will be "binary string"
  10376. * (each char code [0..255])
  10377. * - `header` (Object) - custom header for gzip
  10378. * - `text` (Boolean) - true if compressed data believed to be text
  10379. * - `time` (Number) - modification time, unix timestamp
  10380. * - `os` (Number) - operation system code
  10381. * - `extra` (Array) - array of bytes with extra data (max 65536)
  10382. * - `name` (String) - file name (binary string)
  10383. * - `comment` (String) - comment (binary string)
  10384. * - `hcrc` (Boolean) - true if header crc should be added
  10385. *
  10386. * ##### Example:
  10387. *
  10388. * ```javascript
  10389. * var pako = require('pako')
  10390. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  10391. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  10392. *
  10393. * var deflate = new pako.Deflate({ level: 3});
  10394. *
  10395. * deflate.push(chunk1, false);
  10396. * deflate.push(chunk2, true); // true -> last chunk
  10397. *
  10398. * if (deflate.err) { throw new Error(deflate.err); }
  10399. *
  10400. * console.log(deflate.result);
  10401. * ```
  10402. **/
  10403. var Deflate = function(options) {
  10404. this.options = utils.assign({
  10405. level: Z_DEFAULT_COMPRESSION,
  10406. method: Z_DEFLATED,
  10407. chunkSize: 16384,
  10408. windowBits: 15,
  10409. memLevel: 8,
  10410. strategy: Z_DEFAULT_STRATEGY,
  10411. to: ''
  10412. }, options || {});
  10413. var opt = this.options;
  10414. if (opt.raw && (opt.windowBits > 0)) {
  10415. opt.windowBits = -opt.windowBits;
  10416. }
  10417. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  10418. opt.windowBits += 16;
  10419. }
  10420. this.err = 0; // error code, if happens (0 = Z_OK)
  10421. this.msg = ''; // error message
  10422. this.ended = false; // used to avoid multiple onEnd() calls
  10423. this.chunks = []; // chunks of compressed data
  10424. this.strm = new zstream();
  10425. this.strm.avail_out = 0;
  10426. var status = zlib_deflate.deflateInit2(
  10427. this.strm,
  10428. opt.level,
  10429. opt.method,
  10430. opt.windowBits,
  10431. opt.memLevel,
  10432. opt.strategy
  10433. );
  10434. if (status !== Z_OK) {
  10435. throw new Error(msg[status]);
  10436. }
  10437. if (opt.header) {
  10438. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  10439. }
  10440. };
  10441. /**
  10442. * Deflate#push(data[, mode]) -> Boolean
  10443. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  10444. * converted to utf8 byte sequence.
  10445. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  10446. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  10447. *
  10448. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  10449. * new compressed chunks. Returns `true` on success. The last data block must have
  10450. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  10451. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  10452. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  10453. *
  10454. * On fail call [[Deflate#onEnd]] with error code and return false.
  10455. *
  10456. * We strongly recommend to use `Uint8Array` on input for best speed (output
  10457. * array format is detected automatically). Also, don't skip last param and always
  10458. * use the same type in your code (boolean or number). That will improve JS speed.
  10459. *
  10460. * For regular `Array`-s make sure all elements are [0..255].
  10461. *
  10462. * ##### Example
  10463. *
  10464. * ```javascript
  10465. * push(chunk, false); // push one of data chunks
  10466. * ...
  10467. * push(chunk, true); // push last chunk
  10468. * ```
  10469. **/
  10470. Deflate.prototype.push = function(data, mode) {
  10471. var strm = this.strm;
  10472. var chunkSize = this.options.chunkSize;
  10473. var status, _mode;
  10474. if (this.ended) { return false; }
  10475. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  10476. // Convert data if needed
  10477. if (typeof data === 'string') {
  10478. // If we need to compress text, change encoding to utf8.
  10479. strm.input = strings.string2buf(data);
  10480. } else if (toString.call(data) === '[object ArrayBuffer]') {
  10481. strm.input = new Uint8Array(data);
  10482. } else {
  10483. strm.input = data;
  10484. }
  10485. strm.next_in = 0;
  10486. strm.avail_in = strm.input.length;
  10487. do {
  10488. if (strm.avail_out === 0) {
  10489. strm.output = new utils.Buf8(chunkSize);
  10490. strm.next_out = 0;
  10491. strm.avail_out = chunkSize;
  10492. }
  10493. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  10494. if (status !== Z_STREAM_END && status !== Z_OK) {
  10495. this.onEnd(status);
  10496. this.ended = true;
  10497. return false;
  10498. }
  10499. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  10500. if (this.options.to === 'string') {
  10501. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  10502. } else {
  10503. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  10504. }
  10505. }
  10506. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  10507. // Finalize on the last chunk.
  10508. if (_mode === Z_FINISH) {
  10509. status = zlib_deflate.deflateEnd(this.strm);
  10510. this.onEnd(status);
  10511. this.ended = true;
  10512. return status === Z_OK;
  10513. }
  10514. // callback interim results if Z_SYNC_FLUSH.
  10515. if (_mode === Z_SYNC_FLUSH) {
  10516. this.onEnd(Z_OK);
  10517. strm.avail_out = 0;
  10518. return true;
  10519. }
  10520. return true;
  10521. };
  10522. /**
  10523. * Deflate#onData(chunk) -> Void
  10524. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  10525. * on js engine support. When string output requested, each chunk
  10526. * will be string.
  10527. *
  10528. * By default, stores data blocks in `chunks[]` property and glue
  10529. * those in `onEnd`. Override this handler, if you need another behaviour.
  10530. **/
  10531. Deflate.prototype.onData = function(chunk) {
  10532. this.chunks.push(chunk);
  10533. };
  10534. /**
  10535. * Deflate#onEnd(status) -> Void
  10536. * - status (Number): deflate status. 0 (Z_OK) on success,
  10537. * other if not.
  10538. *
  10539. * Called once after you tell deflate that the input stream is
  10540. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  10541. * or if an error happened. By default - join collected chunks,
  10542. * free memory and fill `results` / `err` properties.
  10543. **/
  10544. Deflate.prototype.onEnd = function(status) {
  10545. // On success - join
  10546. if (status === Z_OK) {
  10547. if (this.options.to === 'string') {
  10548. this.result = this.chunks.join('');
  10549. } else {
  10550. this.result = utils.flattenChunks(this.chunks);
  10551. }
  10552. }
  10553. this.chunks = [];
  10554. this.err = status;
  10555. this.msg = this.strm.msg;
  10556. };
  10557. /**
  10558. * deflate(data[, options]) -> Uint8Array|Array|String
  10559. * - data (Uint8Array|Array|String): input data to compress.
  10560. * - options (Object): zlib deflate options.
  10561. *
  10562. * Compress `data` with deflate alrorythm and `options`.
  10563. *
  10564. * Supported options are:
  10565. *
  10566. * - level
  10567. * - windowBits
  10568. * - memLevel
  10569. * - strategy
  10570. *
  10571. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  10572. * for more information on these.
  10573. *
  10574. * Sugar (options):
  10575. *
  10576. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  10577. * negative windowBits implicitly.
  10578. * - `to` (String) - if equal to 'string', then result will be "binary string"
  10579. * (each char code [0..255])
  10580. *
  10581. * ##### Example:
  10582. *
  10583. * ```javascript
  10584. * var pako = require('pako')
  10585. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  10586. *
  10587. * console.log(pako.deflate(data));
  10588. * ```
  10589. **/
  10590. function deflate(input, options) {
  10591. var deflator = new Deflate(options);
  10592. deflator.push(input, true);
  10593. // That will never happens, if you don't cheat with options :)
  10594. if (deflator.err) { throw deflator.msg; }
  10595. return deflator.result;
  10596. }
  10597. /**
  10598. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  10599. * - data (Uint8Array|Array|String): input data to compress.
  10600. * - options (Object): zlib deflate options.
  10601. *
  10602. * The same as [[deflate]], but creates raw data, without wrapper
  10603. * (header and adler32 crc).
  10604. **/
  10605. function deflateRaw(input, options) {
  10606. options = options || {};
  10607. options.raw = true;
  10608. return deflate(input, options);
  10609. }
  10610. /**
  10611. * gzip(data[, options]) -> Uint8Array|Array|String
  10612. * - data (Uint8Array|Array|String): input data to compress.
  10613. * - options (Object): zlib deflate options.
  10614. *
  10615. * The same as [[deflate]], but create gzip wrapper instead of
  10616. * deflate one.
  10617. **/
  10618. function gzip(input, options) {
  10619. options = options || {};
  10620. options.gzip = true;
  10621. return deflate(input, options);
  10622. }
  10623. exports.Deflate = Deflate;
  10624. exports.deflate = deflate;
  10625. exports.deflateRaw = deflateRaw;
  10626. exports.gzip = gzip;
  10627. },{"./utils/common":39,"./utils/strings":40,"./zlib/deflate.js":44,"./zlib/messages":49,"./zlib/zstream":51}],38:[function(require,module,exports){
  10628. 'use strict';
  10629. var zlib_inflate = require('./zlib/inflate.js');
  10630. var utils = require('./utils/common');
  10631. var strings = require('./utils/strings');
  10632. var c = require('./zlib/constants');
  10633. var msg = require('./zlib/messages');
  10634. var zstream = require('./zlib/zstream');
  10635. var gzheader = require('./zlib/gzheader');
  10636. var toString = Object.prototype.toString;
  10637. /**
  10638. * class Inflate
  10639. *
  10640. * Generic JS-style wrapper for zlib calls. If you don't need
  10641. * streaming behaviour - use more simple functions: [[inflate]]
  10642. * and [[inflateRaw]].
  10643. **/
  10644. /* internal
  10645. * inflate.chunks -> Array
  10646. *
  10647. * Chunks of output data, if [[Inflate#onData]] not overriden.
  10648. **/
  10649. /**
  10650. * Inflate.result -> Uint8Array|Array|String
  10651. *
  10652. * Uncompressed result, generated by default [[Inflate#onData]]
  10653. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  10654. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  10655. * push a chunk with explicit flush (call [[Inflate#push]] with
  10656. * `Z_SYNC_FLUSH` param).
  10657. **/
  10658. /**
  10659. * Inflate.err -> Number
  10660. *
  10661. * Error code after inflate finished. 0 (Z_OK) on success.
  10662. * Should be checked if broken data possible.
  10663. **/
  10664. /**
  10665. * Inflate.msg -> String
  10666. *
  10667. * Error message, if [[Inflate.err]] != 0
  10668. **/
  10669. /**
  10670. * new Inflate(options)
  10671. * - options (Object): zlib inflate options.
  10672. *
  10673. * Creates new inflator instance with specified params. Throws exception
  10674. * on bad params. Supported options:
  10675. *
  10676. * - `windowBits`
  10677. *
  10678. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  10679. * for more information on these.
  10680. *
  10681. * Additional options, for internal needs:
  10682. *
  10683. * - `chunkSize` - size of generated data chunks (16K by default)
  10684. * - `raw` (Boolean) - do raw inflate
  10685. * - `to` (String) - if equal to 'string', then result will be converted
  10686. * from utf8 to utf16 (javascript) string. When string output requested,
  10687. * chunk length can differ from `chunkSize`, depending on content.
  10688. *
  10689. * By default, when no options set, autodetect deflate/gzip data format via
  10690. * wrapper header.
  10691. *
  10692. * ##### Example:
  10693. *
  10694. * ```javascript
  10695. * var pako = require('pako')
  10696. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  10697. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  10698. *
  10699. * var inflate = new pako.Inflate({ level: 3});
  10700. *
  10701. * inflate.push(chunk1, false);
  10702. * inflate.push(chunk2, true); // true -> last chunk
  10703. *
  10704. * if (inflate.err) { throw new Error(inflate.err); }
  10705. *
  10706. * console.log(inflate.result);
  10707. * ```
  10708. **/
  10709. var Inflate = function(options) {
  10710. this.options = utils.assign({
  10711. chunkSize: 16384,
  10712. windowBits: 0,
  10713. to: ''
  10714. }, options || {});
  10715. var opt = this.options;
  10716. // Force window size for `raw` data, if not set directly,
  10717. // because we have no header for autodetect.
  10718. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  10719. opt.windowBits = -opt.windowBits;
  10720. if (opt.windowBits === 0) { opt.windowBits = -15; }
  10721. }
  10722. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  10723. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  10724. !(options && options.windowBits)) {
  10725. opt.windowBits += 32;
  10726. }
  10727. // Gzip header has no info about windows size, we can do autodetect only
  10728. // for deflate. So, if window size not set, force it to max when gzip possible
  10729. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  10730. // bit 3 (16) -> gzipped data
  10731. // bit 4 (32) -> autodetect gzip/deflate
  10732. if ((opt.windowBits & 15) === 0) {
  10733. opt.windowBits |= 15;
  10734. }
  10735. }
  10736. this.err = 0; // error code, if happens (0 = Z_OK)
  10737. this.msg = ''; // error message
  10738. this.ended = false; // used to avoid multiple onEnd() calls
  10739. this.chunks = []; // chunks of compressed data
  10740. this.strm = new zstream();
  10741. this.strm.avail_out = 0;
  10742. var status = zlib_inflate.inflateInit2(
  10743. this.strm,
  10744. opt.windowBits
  10745. );
  10746. if (status !== c.Z_OK) {
  10747. throw new Error(msg[status]);
  10748. }
  10749. this.header = new gzheader();
  10750. zlib_inflate.inflateGetHeader(this.strm, this.header);
  10751. };
  10752. /**
  10753. * Inflate#push(data[, mode]) -> Boolean
  10754. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  10755. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  10756. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  10757. *
  10758. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  10759. * new output chunks. Returns `true` on success. The last data block must have
  10760. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  10761. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  10762. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  10763. *
  10764. * On fail call [[Inflate#onEnd]] with error code and return false.
  10765. *
  10766. * We strongly recommend to use `Uint8Array` on input for best speed (output
  10767. * format is detected automatically). Also, don't skip last param and always
  10768. * use the same type in your code (boolean or number). That will improve JS speed.
  10769. *
  10770. * For regular `Array`-s make sure all elements are [0..255].
  10771. *
  10772. * ##### Example
  10773. *
  10774. * ```javascript
  10775. * push(chunk, false); // push one of data chunks
  10776. * ...
  10777. * push(chunk, true); // push last chunk
  10778. * ```
  10779. **/
  10780. Inflate.prototype.push = function(data, mode) {
  10781. var strm = this.strm;
  10782. var chunkSize = this.options.chunkSize;
  10783. var status, _mode;
  10784. var next_out_utf8, tail, utf8str;
  10785. if (this.ended) { return false; }
  10786. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  10787. // Convert data if needed
  10788. if (typeof data === 'string') {
  10789. // Only binary strings can be decompressed on practice
  10790. strm.input = strings.binstring2buf(data);
  10791. } else if (toString.call(data) === '[object ArrayBuffer]') {
  10792. strm.input = new Uint8Array(data);
  10793. } else {
  10794. strm.input = data;
  10795. }
  10796. strm.next_in = 0;
  10797. strm.avail_in = strm.input.length;
  10798. do {
  10799. if (strm.avail_out === 0) {
  10800. strm.output = new utils.Buf8(chunkSize);
  10801. strm.next_out = 0;
  10802. strm.avail_out = chunkSize;
  10803. }
  10804. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  10805. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  10806. this.onEnd(status);
  10807. this.ended = true;
  10808. return false;
  10809. }
  10810. if (strm.next_out) {
  10811. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  10812. if (this.options.to === 'string') {
  10813. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  10814. tail = strm.next_out - next_out_utf8;
  10815. utf8str = strings.buf2string(strm.output, next_out_utf8);
  10816. // move tail
  10817. strm.next_out = tail;
  10818. strm.avail_out = chunkSize - tail;
  10819. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  10820. this.onData(utf8str);
  10821. } else {
  10822. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  10823. }
  10824. }
  10825. }
  10826. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  10827. if (status === c.Z_STREAM_END) {
  10828. _mode = c.Z_FINISH;
  10829. }
  10830. // Finalize on the last chunk.
  10831. if (_mode === c.Z_FINISH) {
  10832. status = zlib_inflate.inflateEnd(this.strm);
  10833. this.onEnd(status);
  10834. this.ended = true;
  10835. return status === c.Z_OK;
  10836. }
  10837. // callback interim results if Z_SYNC_FLUSH.
  10838. if (_mode === c.Z_SYNC_FLUSH) {
  10839. this.onEnd(c.Z_OK);
  10840. strm.avail_out = 0;
  10841. return true;
  10842. }
  10843. return true;
  10844. };
  10845. /**
  10846. * Inflate#onData(chunk) -> Void
  10847. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  10848. * on js engine support. When string output requested, each chunk
  10849. * will be string.
  10850. *
  10851. * By default, stores data blocks in `chunks[]` property and glue
  10852. * those in `onEnd`. Override this handler, if you need another behaviour.
  10853. **/
  10854. Inflate.prototype.onData = function(chunk) {
  10855. this.chunks.push(chunk);
  10856. };
  10857. /**
  10858. * Inflate#onEnd(status) -> Void
  10859. * - status (Number): inflate status. 0 (Z_OK) on success,
  10860. * other if not.
  10861. *
  10862. * Called either after you tell inflate that the input stream is
  10863. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  10864. * or if an error happened. By default - join collected chunks,
  10865. * free memory and fill `results` / `err` properties.
  10866. **/
  10867. Inflate.prototype.onEnd = function(status) {
  10868. // On success - join
  10869. if (status === c.Z_OK) {
  10870. if (this.options.to === 'string') {
  10871. // Glue & convert here, until we teach pako to send
  10872. // utf8 alligned strings to onData
  10873. this.result = this.chunks.join('');
  10874. } else {
  10875. this.result = utils.flattenChunks(this.chunks);
  10876. }
  10877. }
  10878. this.chunks = [];
  10879. this.err = status;
  10880. this.msg = this.strm.msg;
  10881. };
  10882. /**
  10883. * inflate(data[, options]) -> Uint8Array|Array|String
  10884. * - data (Uint8Array|Array|String): input data to decompress.
  10885. * - options (Object): zlib inflate options.
  10886. *
  10887. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  10888. * format via wrapper header by default. That's why we don't provide
  10889. * separate `ungzip` method.
  10890. *
  10891. * Supported options are:
  10892. *
  10893. * - windowBits
  10894. *
  10895. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  10896. * for more information.
  10897. *
  10898. * Sugar (options):
  10899. *
  10900. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  10901. * negative windowBits implicitly.
  10902. * - `to` (String) - if equal to 'string', then result will be converted
  10903. * from utf8 to utf16 (javascript) string. When string output requested,
  10904. * chunk length can differ from `chunkSize`, depending on content.
  10905. *
  10906. *
  10907. * ##### Example:
  10908. *
  10909. * ```javascript
  10910. * var pako = require('pako')
  10911. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  10912. * , output;
  10913. *
  10914. * try {
  10915. * output = pako.inflate(input);
  10916. * } catch (err)
  10917. * console.log(err);
  10918. * }
  10919. * ```
  10920. **/
  10921. function inflate(input, options) {
  10922. var inflator = new Inflate(options);
  10923. inflator.push(input, true);
  10924. // That will never happens, if you don't cheat with options :)
  10925. if (inflator.err) { throw inflator.msg; }
  10926. return inflator.result;
  10927. }
  10928. /**
  10929. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  10930. * - data (Uint8Array|Array|String): input data to decompress.
  10931. * - options (Object): zlib inflate options.
  10932. *
  10933. * The same as [[inflate]], but creates raw data, without wrapper
  10934. * (header and adler32 crc).
  10935. **/
  10936. function inflateRaw(input, options) {
  10937. options = options || {};
  10938. options.raw = true;
  10939. return inflate(input, options);
  10940. }
  10941. /**
  10942. * ungzip(data[, options]) -> Uint8Array|Array|String
  10943. * - data (Uint8Array|Array|String): input data to decompress.
  10944. * - options (Object): zlib inflate options.
  10945. *
  10946. * Just shortcut to [[inflate]], because it autodetects format
  10947. * by header.content. Done for convenience.
  10948. **/
  10949. exports.Inflate = Inflate;
  10950. exports.inflate = inflate;
  10951. exports.inflateRaw = inflateRaw;
  10952. exports.ungzip = inflate;
  10953. },{"./utils/common":39,"./utils/strings":40,"./zlib/constants":42,"./zlib/gzheader":45,"./zlib/inflate.js":47,"./zlib/messages":49,"./zlib/zstream":51}],39:[function(require,module,exports){
  10954. 'use strict';
  10955. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  10956. (typeof Uint16Array !== 'undefined') &&
  10957. (typeof Int32Array !== 'undefined');
  10958. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  10959. var sources = Array.prototype.slice.call(arguments, 1);
  10960. while (sources.length) {
  10961. var source = sources.shift();
  10962. if (!source) { continue; }
  10963. if (typeof source !== 'object') {
  10964. throw new TypeError(source + 'must be non-object');
  10965. }
  10966. for (var p in source) {
  10967. if (source.hasOwnProperty(p)) {
  10968. obj[p] = source[p];
  10969. }
  10970. }
  10971. }
  10972. return obj;
  10973. };
  10974. // reduce buffer size, avoiding mem copy
  10975. exports.shrinkBuf = function (buf, size) {
  10976. if (buf.length === size) { return buf; }
  10977. if (buf.subarray) { return buf.subarray(0, size); }
  10978. buf.length = size;
  10979. return buf;
  10980. };
  10981. var fnTyped = {
  10982. arraySet: function (dest, src, src_offs, len, dest_offs) {
  10983. if (src.subarray && dest.subarray) {
  10984. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  10985. return;
  10986. }
  10987. // Fallback to ordinary array
  10988. for (var i=0; i<len; i++) {
  10989. dest[dest_offs + i] = src[src_offs + i];
  10990. }
  10991. },
  10992. // Join array of chunks to single array.
  10993. flattenChunks: function(chunks) {
  10994. var i, l, len, pos, chunk, result;
  10995. // calculate data length
  10996. len = 0;
  10997. for (i=0, l=chunks.length; i<l; i++) {
  10998. len += chunks[i].length;
  10999. }
  11000. // join chunks
  11001. result = new Uint8Array(len);
  11002. pos = 0;
  11003. for (i=0, l=chunks.length; i<l; i++) {
  11004. chunk = chunks[i];
  11005. result.set(chunk, pos);
  11006. pos += chunk.length;
  11007. }
  11008. return result;
  11009. }
  11010. };
  11011. var fnUntyped = {
  11012. arraySet: function (dest, src, src_offs, len, dest_offs) {
  11013. for (var i=0; i<len; i++) {
  11014. dest[dest_offs + i] = src[src_offs + i];
  11015. }
  11016. },
  11017. // Join array of chunks to single array.
  11018. flattenChunks: function(chunks) {
  11019. return [].concat.apply([], chunks);
  11020. }
  11021. };
  11022. // Enable/Disable typed arrays use, for testing
  11023. //
  11024. exports.setTyped = function (on) {
  11025. if (on) {
  11026. exports.Buf8 = Uint8Array;
  11027. exports.Buf16 = Uint16Array;
  11028. exports.Buf32 = Int32Array;
  11029. exports.assign(exports, fnTyped);
  11030. } else {
  11031. exports.Buf8 = Array;
  11032. exports.Buf16 = Array;
  11033. exports.Buf32 = Array;
  11034. exports.assign(exports, fnUntyped);
  11035. }
  11036. };
  11037. exports.setTyped(TYPED_OK);
  11038. },{}],40:[function(require,module,exports){
  11039. // String encode/decode helpers
  11040. 'use strict';
  11041. var utils = require('./common');
  11042. // Quick check if we can use fast array to bin string conversion
  11043. //
  11044. // - apply(Array) can fail on Android 2.2
  11045. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  11046. //
  11047. var STR_APPLY_OK = true;
  11048. var STR_APPLY_UIA_OK = true;
  11049. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  11050. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  11051. // Table with utf8 lengths (calculated by first byte of sequence)
  11052. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  11053. // because max possible codepoint is 0x10ffff
  11054. var _utf8len = new utils.Buf8(256);
  11055. for (var q=0; q<256; q++) {
  11056. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  11057. }
  11058. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  11059. // convert string to array (typed, when possible)
  11060. exports.string2buf = function (str) {
  11061. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  11062. // count binary size
  11063. for (m_pos = 0; m_pos < str_len; m_pos++) {
  11064. c = str.charCodeAt(m_pos);
  11065. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  11066. c2 = str.charCodeAt(m_pos+1);
  11067. if ((c2 & 0xfc00) === 0xdc00) {
  11068. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  11069. m_pos++;
  11070. }
  11071. }
  11072. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  11073. }
  11074. // allocate buffer
  11075. buf = new utils.Buf8(buf_len);
  11076. // convert
  11077. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  11078. c = str.charCodeAt(m_pos);
  11079. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  11080. c2 = str.charCodeAt(m_pos+1);
  11081. if ((c2 & 0xfc00) === 0xdc00) {
  11082. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  11083. m_pos++;
  11084. }
  11085. }
  11086. if (c < 0x80) {
  11087. /* one byte */
  11088. buf[i++] = c;
  11089. } else if (c < 0x800) {
  11090. /* two bytes */
  11091. buf[i++] = 0xC0 | (c >>> 6);
  11092. buf[i++] = 0x80 | (c & 0x3f);
  11093. } else if (c < 0x10000) {
  11094. /* three bytes */
  11095. buf[i++] = 0xE0 | (c >>> 12);
  11096. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  11097. buf[i++] = 0x80 | (c & 0x3f);
  11098. } else {
  11099. /* four bytes */
  11100. buf[i++] = 0xf0 | (c >>> 18);
  11101. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  11102. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  11103. buf[i++] = 0x80 | (c & 0x3f);
  11104. }
  11105. }
  11106. return buf;
  11107. };
  11108. // Helper (used in 2 places)
  11109. function buf2binstring(buf, len) {
  11110. // use fallback for big arrays to avoid stack overflow
  11111. if (len < 65537) {
  11112. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  11113. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  11114. }
  11115. }
  11116. var result = '';
  11117. for (var i=0; i < len; i++) {
  11118. result += String.fromCharCode(buf[i]);
  11119. }
  11120. return result;
  11121. }
  11122. // Convert byte array to binary string
  11123. exports.buf2binstring = function(buf) {
  11124. return buf2binstring(buf, buf.length);
  11125. };
  11126. // Convert binary string (typed, when possible)
  11127. exports.binstring2buf = function(str) {
  11128. var buf = new utils.Buf8(str.length);
  11129. for (var i=0, len=buf.length; i < len; i++) {
  11130. buf[i] = str.charCodeAt(i);
  11131. }
  11132. return buf;
  11133. };
  11134. // convert array to string
  11135. exports.buf2string = function (buf, max) {
  11136. var i, out, c, c_len;
  11137. var len = max || buf.length;
  11138. // Reserve max possible length (2 words per char)
  11139. // NB: by unknown reasons, Array is significantly faster for
  11140. // String.fromCharCode.apply than Uint16Array.
  11141. var utf16buf = new Array(len*2);
  11142. for (out=0, i=0; i<len;) {
  11143. c = buf[i++];
  11144. // quick process ascii
  11145. if (c < 0x80) { utf16buf[out++] = c; continue; }
  11146. c_len = _utf8len[c];
  11147. // skip 5 & 6 byte codes
  11148. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  11149. // apply mask on first byte
  11150. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  11151. // join the rest
  11152. while (c_len > 1 && i < len) {
  11153. c = (c << 6) | (buf[i++] & 0x3f);
  11154. c_len--;
  11155. }
  11156. // terminated by end of string?
  11157. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  11158. if (c < 0x10000) {
  11159. utf16buf[out++] = c;
  11160. } else {
  11161. c -= 0x10000;
  11162. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  11163. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  11164. }
  11165. }
  11166. return buf2binstring(utf16buf, out);
  11167. };
  11168. // Calculate max possible position in utf8 buffer,
  11169. // that will not break sequence. If that's not possible
  11170. // - (very small limits) return max size as is.
  11171. //
  11172. // buf[] - utf8 bytes array
  11173. // max - length limit (mandatory);
  11174. exports.utf8border = function(buf, max) {
  11175. var pos;
  11176. max = max || buf.length;
  11177. if (max > buf.length) { max = buf.length; }
  11178. // go back from last position, until start of sequence found
  11179. pos = max-1;
  11180. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  11181. // Fuckup - very small and broken sequence,
  11182. // return max, because we should return something anyway.
  11183. if (pos < 0) { return max; }
  11184. // If we came to start of buffer - that means vuffer is too small,
  11185. // return max too.
  11186. if (pos === 0) { return max; }
  11187. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  11188. };
  11189. },{"./common":39}],41:[function(require,module,exports){
  11190. 'use strict';
  11191. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  11192. // It doesn't worth to make additional optimizationa as in original.
  11193. // Small size is preferable.
  11194. function adler32(adler, buf, len, pos) {
  11195. var s1 = (adler & 0xffff) |0,
  11196. s2 = ((adler >>> 16) & 0xffff) |0,
  11197. n = 0;
  11198. while (len !== 0) {
  11199. // Set limit ~ twice less than 5552, to keep
  11200. // s2 in 31-bits, because we force signed ints.
  11201. // in other case %= will fail.
  11202. n = len > 2000 ? 2000 : len;
  11203. len -= n;
  11204. do {
  11205. s1 = (s1 + buf[pos++]) |0;
  11206. s2 = (s2 + s1) |0;
  11207. } while (--n);
  11208. s1 %= 65521;
  11209. s2 %= 65521;
  11210. }
  11211. return (s1 | (s2 << 16)) |0;
  11212. }
  11213. module.exports = adler32;
  11214. },{}],42:[function(require,module,exports){
  11215. module.exports = {
  11216. /* Allowed flush values; see deflate() and inflate() below for details */
  11217. Z_NO_FLUSH: 0,
  11218. Z_PARTIAL_FLUSH: 1,
  11219. Z_SYNC_FLUSH: 2,
  11220. Z_FULL_FLUSH: 3,
  11221. Z_FINISH: 4,
  11222. Z_BLOCK: 5,
  11223. Z_TREES: 6,
  11224. /* Return codes for the compression/decompression functions. Negative values
  11225. * are errors, positive values are used for special but normal events.
  11226. */
  11227. Z_OK: 0,
  11228. Z_STREAM_END: 1,
  11229. Z_NEED_DICT: 2,
  11230. Z_ERRNO: -1,
  11231. Z_STREAM_ERROR: -2,
  11232. Z_DATA_ERROR: -3,
  11233. //Z_MEM_ERROR: -4,
  11234. Z_BUF_ERROR: -5,
  11235. //Z_VERSION_ERROR: -6,
  11236. /* compression levels */
  11237. Z_NO_COMPRESSION: 0,
  11238. Z_BEST_SPEED: 1,
  11239. Z_BEST_COMPRESSION: 9,
  11240. Z_DEFAULT_COMPRESSION: -1,
  11241. Z_FILTERED: 1,
  11242. Z_HUFFMAN_ONLY: 2,
  11243. Z_RLE: 3,
  11244. Z_FIXED: 4,
  11245. Z_DEFAULT_STRATEGY: 0,
  11246. /* Possible values of the data_type field (though see inflate()) */
  11247. Z_BINARY: 0,
  11248. Z_TEXT: 1,
  11249. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  11250. Z_UNKNOWN: 2,
  11251. /* The deflate compression method */
  11252. Z_DEFLATED: 8
  11253. //Z_NULL: null // Use -1 or null inline, depending on var type
  11254. };
  11255. },{}],43:[function(require,module,exports){
  11256. 'use strict';
  11257. // Note: we can't get significant speed boost here.
  11258. // So write code to minimize size - no pregenerated tables
  11259. // and array tools dependencies.
  11260. // Use ordinary array, since untyped makes no boost here
  11261. function makeTable() {
  11262. var c, table = [];
  11263. for (var n =0; n < 256; n++) {
  11264. c = n;
  11265. for (var k =0; k < 8; k++) {
  11266. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  11267. }
  11268. table[n] = c;
  11269. }
  11270. return table;
  11271. }
  11272. // Create table on load. Just 255 signed longs. Not a problem.
  11273. var crcTable = makeTable();
  11274. function crc32(crc, buf, len, pos) {
  11275. var t = crcTable,
  11276. end = pos + len;
  11277. crc = crc ^ (-1);
  11278. for (var i = pos; i < end; i++) {
  11279. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  11280. }
  11281. return (crc ^ (-1)); // >>> 0;
  11282. }
  11283. module.exports = crc32;
  11284. },{}],44:[function(require,module,exports){
  11285. 'use strict';
  11286. var utils = require('../utils/common');
  11287. var trees = require('./trees');
  11288. var adler32 = require('./adler32');
  11289. var crc32 = require('./crc32');
  11290. var msg = require('./messages');
  11291. /* Public constants ==========================================================*/
  11292. /* ===========================================================================*/
  11293. /* Allowed flush values; see deflate() and inflate() below for details */
  11294. var Z_NO_FLUSH = 0;
  11295. var Z_PARTIAL_FLUSH = 1;
  11296. //var Z_SYNC_FLUSH = 2;
  11297. var Z_FULL_FLUSH = 3;
  11298. var Z_FINISH = 4;
  11299. var Z_BLOCK = 5;
  11300. //var Z_TREES = 6;
  11301. /* Return codes for the compression/decompression functions. Negative values
  11302. * are errors, positive values are used for special but normal events.
  11303. */
  11304. var Z_OK = 0;
  11305. var Z_STREAM_END = 1;
  11306. //var Z_NEED_DICT = 2;
  11307. //var Z_ERRNO = -1;
  11308. var Z_STREAM_ERROR = -2;
  11309. var Z_DATA_ERROR = -3;
  11310. //var Z_MEM_ERROR = -4;
  11311. var Z_BUF_ERROR = -5;
  11312. //var Z_VERSION_ERROR = -6;
  11313. /* compression levels */
  11314. //var Z_NO_COMPRESSION = 0;
  11315. //var Z_BEST_SPEED = 1;
  11316. //var Z_BEST_COMPRESSION = 9;
  11317. var Z_DEFAULT_COMPRESSION = -1;
  11318. var Z_FILTERED = 1;
  11319. var Z_HUFFMAN_ONLY = 2;
  11320. var Z_RLE = 3;
  11321. var Z_FIXED = 4;
  11322. var Z_DEFAULT_STRATEGY = 0;
  11323. /* Possible values of the data_type field (though see inflate()) */
  11324. //var Z_BINARY = 0;
  11325. //var Z_TEXT = 1;
  11326. //var Z_ASCII = 1; // = Z_TEXT
  11327. var Z_UNKNOWN = 2;
  11328. /* The deflate compression method */
  11329. var Z_DEFLATED = 8;
  11330. /*============================================================================*/
  11331. var MAX_MEM_LEVEL = 9;
  11332. /* Maximum value for memLevel in deflateInit2 */
  11333. var MAX_WBITS = 15;
  11334. /* 32K LZ77 window */
  11335. var DEF_MEM_LEVEL = 8;
  11336. var LENGTH_CODES = 29;
  11337. /* number of length codes, not counting the special END_BLOCK code */
  11338. var LITERALS = 256;
  11339. /* number of literal bytes 0..255 */
  11340. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  11341. /* number of Literal or Length codes, including the END_BLOCK code */
  11342. var D_CODES = 30;
  11343. /* number of distance codes */
  11344. var BL_CODES = 19;
  11345. /* number of codes used to transfer the bit lengths */
  11346. var HEAP_SIZE = 2*L_CODES + 1;
  11347. /* maximum heap size */
  11348. var MAX_BITS = 15;
  11349. /* All codes must not exceed MAX_BITS bits */
  11350. var MIN_MATCH = 3;
  11351. var MAX_MATCH = 258;
  11352. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  11353. var PRESET_DICT = 0x20;
  11354. var INIT_STATE = 42;
  11355. var EXTRA_STATE = 69;
  11356. var NAME_STATE = 73;
  11357. var COMMENT_STATE = 91;
  11358. var HCRC_STATE = 103;
  11359. var BUSY_STATE = 113;
  11360. var FINISH_STATE = 666;
  11361. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  11362. var BS_BLOCK_DONE = 2; /* block flush performed */
  11363. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  11364. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  11365. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  11366. function err(strm, errorCode) {
  11367. strm.msg = msg[errorCode];
  11368. return errorCode;
  11369. }
  11370. function rank(f) {
  11371. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  11372. }
  11373. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  11374. /* =========================================================================
  11375. * Flush as much pending output as possible. All deflate() output goes
  11376. * through this function so some applications may wish to modify it
  11377. * to avoid allocating a large strm->output buffer and copying into it.
  11378. * (See also read_buf()).
  11379. */
  11380. function flush_pending(strm) {
  11381. var s = strm.state;
  11382. //_tr_flush_bits(s);
  11383. var len = s.pending;
  11384. if (len > strm.avail_out) {
  11385. len = strm.avail_out;
  11386. }
  11387. if (len === 0) { return; }
  11388. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  11389. strm.next_out += len;
  11390. s.pending_out += len;
  11391. strm.total_out += len;
  11392. strm.avail_out -= len;
  11393. s.pending -= len;
  11394. if (s.pending === 0) {
  11395. s.pending_out = 0;
  11396. }
  11397. }
  11398. function flush_block_only (s, last) {
  11399. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  11400. s.block_start = s.strstart;
  11401. flush_pending(s.strm);
  11402. }
  11403. function put_byte(s, b) {
  11404. s.pending_buf[s.pending++] = b;
  11405. }
  11406. /* =========================================================================
  11407. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  11408. * IN assertion: the stream state is correct and there is enough room in
  11409. * pending_buf.
  11410. */
  11411. function putShortMSB(s, b) {
  11412. // put_byte(s, (Byte)(b >> 8));
  11413. // put_byte(s, (Byte)(b & 0xff));
  11414. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  11415. s.pending_buf[s.pending++] = b & 0xff;
  11416. }
  11417. /* ===========================================================================
  11418. * Read a new buffer from the current input stream, update the adler32
  11419. * and total number of bytes read. All deflate() input goes through
  11420. * this function so some applications may wish to modify it to avoid
  11421. * allocating a large strm->input buffer and copying from it.
  11422. * (See also flush_pending()).
  11423. */
  11424. function read_buf(strm, buf, start, size) {
  11425. var len = strm.avail_in;
  11426. if (len > size) { len = size; }
  11427. if (len === 0) { return 0; }
  11428. strm.avail_in -= len;
  11429. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  11430. if (strm.state.wrap === 1) {
  11431. strm.adler = adler32(strm.adler, buf, len, start);
  11432. }
  11433. else if (strm.state.wrap === 2) {
  11434. strm.adler = crc32(strm.adler, buf, len, start);
  11435. }
  11436. strm.next_in += len;
  11437. strm.total_in += len;
  11438. return len;
  11439. }
  11440. /* ===========================================================================
  11441. * Set match_start to the longest match starting at the given string and
  11442. * return its length. Matches shorter or equal to prev_length are discarded,
  11443. * in which case the result is equal to prev_length and match_start is
  11444. * garbage.
  11445. * IN assertions: cur_match is the head of the hash chain for the current
  11446. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  11447. * OUT assertion: the match length is not greater than s->lookahead.
  11448. */
  11449. function longest_match(s, cur_match) {
  11450. var chain_length = s.max_chain_length; /* max hash chain length */
  11451. var scan = s.strstart; /* current string */
  11452. var match; /* matched string */
  11453. var len; /* length of current match */
  11454. var best_len = s.prev_length; /* best match length so far */
  11455. var nice_match = s.nice_match; /* stop if match long enough */
  11456. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  11457. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  11458. var _win = s.window; // shortcut
  11459. var wmask = s.w_mask;
  11460. var prev = s.prev;
  11461. /* Stop when cur_match becomes <= limit. To simplify the code,
  11462. * we prevent matches with the string of window index 0.
  11463. */
  11464. var strend = s.strstart + MAX_MATCH;
  11465. var scan_end1 = _win[scan + best_len - 1];
  11466. var scan_end = _win[scan + best_len];
  11467. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  11468. * It is easy to get rid of this optimization if necessary.
  11469. */
  11470. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  11471. /* Do not waste too much time if we already have a good match: */
  11472. if (s.prev_length >= s.good_match) {
  11473. chain_length >>= 2;
  11474. }
  11475. /* Do not look for matches beyond the end of the input. This is necessary
  11476. * to make deflate deterministic.
  11477. */
  11478. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  11479. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  11480. do {
  11481. // Assert(cur_match < s->strstart, "no future");
  11482. match = cur_match;
  11483. /* Skip to next match if the match length cannot increase
  11484. * or if the match length is less than 2. Note that the checks below
  11485. * for insufficient lookahead only occur occasionally for performance
  11486. * reasons. Therefore uninitialized memory will be accessed, and
  11487. * conditional jumps will be made that depend on those values.
  11488. * However the length of the match is limited to the lookahead, so
  11489. * the output of deflate is not affected by the uninitialized values.
  11490. */
  11491. if (_win[match + best_len] !== scan_end ||
  11492. _win[match + best_len - 1] !== scan_end1 ||
  11493. _win[match] !== _win[scan] ||
  11494. _win[++match] !== _win[scan + 1]) {
  11495. continue;
  11496. }
  11497. /* The check at best_len-1 can be removed because it will be made
  11498. * again later. (This heuristic is not always a win.)
  11499. * It is not necessary to compare scan[2] and match[2] since they
  11500. * are always equal when the other bytes match, given that
  11501. * the hash keys are equal and that HASH_BITS >= 8.
  11502. */
  11503. scan += 2;
  11504. match++;
  11505. // Assert(*scan == *match, "match[2]?");
  11506. /* We check for insufficient lookahead only every 8th comparison;
  11507. * the 256th check will be made at strstart+258.
  11508. */
  11509. do {
  11510. /*jshint noempty:false*/
  11511. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  11512. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  11513. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  11514. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  11515. scan < strend);
  11516. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  11517. len = MAX_MATCH - (strend - scan);
  11518. scan = strend - MAX_MATCH;
  11519. if (len > best_len) {
  11520. s.match_start = cur_match;
  11521. best_len = len;
  11522. if (len >= nice_match) {
  11523. break;
  11524. }
  11525. scan_end1 = _win[scan + best_len - 1];
  11526. scan_end = _win[scan + best_len];
  11527. }
  11528. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  11529. if (best_len <= s.lookahead) {
  11530. return best_len;
  11531. }
  11532. return s.lookahead;
  11533. }
  11534. /* ===========================================================================
  11535. * Fill the window when the lookahead becomes insufficient.
  11536. * Updates strstart and lookahead.
  11537. *
  11538. * IN assertion: lookahead < MIN_LOOKAHEAD
  11539. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  11540. * At least one byte has been read, or avail_in == 0; reads are
  11541. * performed for at least two bytes (required for the zip translate_eol
  11542. * option -- not supported here).
  11543. */
  11544. function fill_window(s) {
  11545. var _w_size = s.w_size;
  11546. var p, n, m, more, str;
  11547. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  11548. do {
  11549. more = s.window_size - s.lookahead - s.strstart;
  11550. // JS ints have 32 bit, block below not needed
  11551. /* Deal with !@#$% 64K limit: */
  11552. //if (sizeof(int) <= 2) {
  11553. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  11554. // more = wsize;
  11555. //
  11556. // } else if (more == (unsigned)(-1)) {
  11557. // /* Very unlikely, but possible on 16 bit machine if
  11558. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  11559. // */
  11560. // more--;
  11561. // }
  11562. //}
  11563. /* If the window is almost full and there is insufficient lookahead,
  11564. * move the upper half to the lower one to make room in the upper half.
  11565. */
  11566. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  11567. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  11568. s.match_start -= _w_size;
  11569. s.strstart -= _w_size;
  11570. /* we now have strstart >= MAX_DIST */
  11571. s.block_start -= _w_size;
  11572. /* Slide the hash table (could be avoided with 32 bit values
  11573. at the expense of memory usage). We slide even when level == 0
  11574. to keep the hash table consistent if we switch back to level > 0
  11575. later. (Using level 0 permanently is not an optimal usage of
  11576. zlib, so we don't care about this pathological case.)
  11577. */
  11578. n = s.hash_size;
  11579. p = n;
  11580. do {
  11581. m = s.head[--p];
  11582. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  11583. } while (--n);
  11584. n = _w_size;
  11585. p = n;
  11586. do {
  11587. m = s.prev[--p];
  11588. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  11589. /* If n is not on any hash chain, prev[n] is garbage but
  11590. * its value will never be used.
  11591. */
  11592. } while (--n);
  11593. more += _w_size;
  11594. }
  11595. if (s.strm.avail_in === 0) {
  11596. break;
  11597. }
  11598. /* If there was no sliding:
  11599. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  11600. * more == window_size - lookahead - strstart
  11601. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  11602. * => more >= window_size - 2*WSIZE + 2
  11603. * In the BIG_MEM or MMAP case (not yet supported),
  11604. * window_size == input_size + MIN_LOOKAHEAD &&
  11605. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  11606. * Otherwise, window_size == 2*WSIZE so more >= 2.
  11607. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  11608. */
  11609. //Assert(more >= 2, "more < 2");
  11610. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  11611. s.lookahead += n;
  11612. /* Initialize the hash value now that we have some input: */
  11613. if (s.lookahead + s.insert >= MIN_MATCH) {
  11614. str = s.strstart - s.insert;
  11615. s.ins_h = s.window[str];
  11616. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  11617. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  11618. //#if MIN_MATCH != 3
  11619. // Call update_hash() MIN_MATCH-3 more times
  11620. //#endif
  11621. while (s.insert) {
  11622. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  11623. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  11624. s.prev[str & s.w_mask] = s.head[s.ins_h];
  11625. s.head[s.ins_h] = str;
  11626. str++;
  11627. s.insert--;
  11628. if (s.lookahead + s.insert < MIN_MATCH) {
  11629. break;
  11630. }
  11631. }
  11632. }
  11633. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  11634. * but this is not important since only literal bytes will be emitted.
  11635. */
  11636. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  11637. /* If the WIN_INIT bytes after the end of the current data have never been
  11638. * written, then zero those bytes in order to avoid memory check reports of
  11639. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  11640. * the longest match routines. Update the high water mark for the next
  11641. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  11642. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  11643. */
  11644. // if (s.high_water < s.window_size) {
  11645. // var curr = s.strstart + s.lookahead;
  11646. // var init = 0;
  11647. //
  11648. // if (s.high_water < curr) {
  11649. // /* Previous high water mark below current data -- zero WIN_INIT
  11650. // * bytes or up to end of window, whichever is less.
  11651. // */
  11652. // init = s.window_size - curr;
  11653. // if (init > WIN_INIT)
  11654. // init = WIN_INIT;
  11655. // zmemzero(s->window + curr, (unsigned)init);
  11656. // s->high_water = curr + init;
  11657. // }
  11658. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  11659. // /* High water mark at or above current data, but below current data
  11660. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  11661. // * to end of window, whichever is less.
  11662. // */
  11663. // init = (ulg)curr + WIN_INIT - s->high_water;
  11664. // if (init > s->window_size - s->high_water)
  11665. // init = s->window_size - s->high_water;
  11666. // zmemzero(s->window + s->high_water, (unsigned)init);
  11667. // s->high_water += init;
  11668. // }
  11669. // }
  11670. //
  11671. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  11672. // "not enough room for search");
  11673. }
  11674. /* ===========================================================================
  11675. * Copy without compression as much as possible from the input stream, return
  11676. * the current block state.
  11677. * This function does not insert new strings in the dictionary since
  11678. * uncompressible data is probably not useful. This function is used
  11679. * only for the level=0 compression option.
  11680. * NOTE: this function should be optimized to avoid extra copying from
  11681. * window to pending_buf.
  11682. */
  11683. function deflate_stored(s, flush) {
  11684. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  11685. * to pending_buf_size, and each stored block has a 5 byte header:
  11686. */
  11687. var max_block_size = 0xffff;
  11688. if (max_block_size > s.pending_buf_size - 5) {
  11689. max_block_size = s.pending_buf_size - 5;
  11690. }
  11691. /* Copy as much as possible from input to output: */
  11692. for (;;) {
  11693. /* Fill the window as much as possible: */
  11694. if (s.lookahead <= 1) {
  11695. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  11696. // s->block_start >= (long)s->w_size, "slide too late");
  11697. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  11698. // s.block_start >= s.w_size)) {
  11699. // throw new Error("slide too late");
  11700. // }
  11701. fill_window(s);
  11702. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  11703. return BS_NEED_MORE;
  11704. }
  11705. if (s.lookahead === 0) {
  11706. break;
  11707. }
  11708. /* flush the current block */
  11709. }
  11710. //Assert(s->block_start >= 0L, "block gone");
  11711. // if (s.block_start < 0) throw new Error("block gone");
  11712. s.strstart += s.lookahead;
  11713. s.lookahead = 0;
  11714. /* Emit a stored block if pending_buf will be full: */
  11715. var max_start = s.block_start + max_block_size;
  11716. if (s.strstart === 0 || s.strstart >= max_start) {
  11717. /* strstart == 0 is possible when wraparound on 16-bit machine */
  11718. s.lookahead = s.strstart - max_start;
  11719. s.strstart = max_start;
  11720. /*** FLUSH_BLOCK(s, 0); ***/
  11721. flush_block_only(s, false);
  11722. if (s.strm.avail_out === 0) {
  11723. return BS_NEED_MORE;
  11724. }
  11725. /***/
  11726. }
  11727. /* Flush if we may have to slide, otherwise block_start may become
  11728. * negative and the data will be gone:
  11729. */
  11730. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  11731. /*** FLUSH_BLOCK(s, 0); ***/
  11732. flush_block_only(s, false);
  11733. if (s.strm.avail_out === 0) {
  11734. return BS_NEED_MORE;
  11735. }
  11736. /***/
  11737. }
  11738. }
  11739. s.insert = 0;
  11740. if (flush === Z_FINISH) {
  11741. /*** FLUSH_BLOCK(s, 1); ***/
  11742. flush_block_only(s, true);
  11743. if (s.strm.avail_out === 0) {
  11744. return BS_FINISH_STARTED;
  11745. }
  11746. /***/
  11747. return BS_FINISH_DONE;
  11748. }
  11749. if (s.strstart > s.block_start) {
  11750. /*** FLUSH_BLOCK(s, 0); ***/
  11751. flush_block_only(s, false);
  11752. if (s.strm.avail_out === 0) {
  11753. return BS_NEED_MORE;
  11754. }
  11755. /***/
  11756. }
  11757. return BS_NEED_MORE;
  11758. }
  11759. /* ===========================================================================
  11760. * Compress as much as possible from the input stream, return the current
  11761. * block state.
  11762. * This function does not perform lazy evaluation of matches and inserts
  11763. * new strings in the dictionary only for unmatched strings or for short
  11764. * matches. It is used only for the fast compression options.
  11765. */
  11766. function deflate_fast(s, flush) {
  11767. var hash_head; /* head of the hash chain */
  11768. var bflush; /* set if current block must be flushed */
  11769. for (;;) {
  11770. /* Make sure that we always have enough lookahead, except
  11771. * at the end of the input file. We need MAX_MATCH bytes
  11772. * for the next match, plus MIN_MATCH bytes to insert the
  11773. * string following the next match.
  11774. */
  11775. if (s.lookahead < MIN_LOOKAHEAD) {
  11776. fill_window(s);
  11777. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  11778. return BS_NEED_MORE;
  11779. }
  11780. if (s.lookahead === 0) {
  11781. break; /* flush the current block */
  11782. }
  11783. }
  11784. /* Insert the string window[strstart .. strstart+2] in the
  11785. * dictionary, and set hash_head to the head of the hash chain:
  11786. */
  11787. hash_head = 0/*NIL*/;
  11788. if (s.lookahead >= MIN_MATCH) {
  11789. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  11790. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  11791. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  11792. s.head[s.ins_h] = s.strstart;
  11793. /***/
  11794. }
  11795. /* Find the longest match, discarding those <= prev_length.
  11796. * At this point we have always match_length < MIN_MATCH
  11797. */
  11798. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  11799. /* To simplify the code, we prevent matches with the string
  11800. * of window index 0 (in particular we have to avoid a match
  11801. * of the string with itself at the start of the input file).
  11802. */
  11803. s.match_length = longest_match(s, hash_head);
  11804. /* longest_match() sets match_start */
  11805. }
  11806. if (s.match_length >= MIN_MATCH) {
  11807. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  11808. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  11809. s.match_length - MIN_MATCH, bflush); ***/
  11810. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  11811. s.lookahead -= s.match_length;
  11812. /* Insert new strings in the hash table only if the match length
  11813. * is not too large. This saves time but degrades compression.
  11814. */
  11815. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  11816. s.match_length--; /* string at strstart already in table */
  11817. do {
  11818. s.strstart++;
  11819. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  11820. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  11821. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  11822. s.head[s.ins_h] = s.strstart;
  11823. /***/
  11824. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  11825. * always MIN_MATCH bytes ahead.
  11826. */
  11827. } while (--s.match_length !== 0);
  11828. s.strstart++;
  11829. } else
  11830. {
  11831. s.strstart += s.match_length;
  11832. s.match_length = 0;
  11833. s.ins_h = s.window[s.strstart];
  11834. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  11835. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  11836. //#if MIN_MATCH != 3
  11837. // Call UPDATE_HASH() MIN_MATCH-3 more times
  11838. //#endif
  11839. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  11840. * matter since it will be recomputed at next deflate call.
  11841. */
  11842. }
  11843. } else {
  11844. /* No match, output a literal byte */
  11845. //Tracevv((stderr,"%c", s.window[s.strstart]));
  11846. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  11847. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  11848. s.lookahead--;
  11849. s.strstart++;
  11850. }
  11851. if (bflush) {
  11852. /*** FLUSH_BLOCK(s, 0); ***/
  11853. flush_block_only(s, false);
  11854. if (s.strm.avail_out === 0) {
  11855. return BS_NEED_MORE;
  11856. }
  11857. /***/
  11858. }
  11859. }
  11860. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  11861. if (flush === Z_FINISH) {
  11862. /*** FLUSH_BLOCK(s, 1); ***/
  11863. flush_block_only(s, true);
  11864. if (s.strm.avail_out === 0) {
  11865. return BS_FINISH_STARTED;
  11866. }
  11867. /***/
  11868. return BS_FINISH_DONE;
  11869. }
  11870. if (s.last_lit) {
  11871. /*** FLUSH_BLOCK(s, 0); ***/
  11872. flush_block_only(s, false);
  11873. if (s.strm.avail_out === 0) {
  11874. return BS_NEED_MORE;
  11875. }
  11876. /***/
  11877. }
  11878. return BS_BLOCK_DONE;
  11879. }
  11880. /* ===========================================================================
  11881. * Same as above, but achieves better compression. We use a lazy
  11882. * evaluation for matches: a match is finally adopted only if there is
  11883. * no better match at the next window position.
  11884. */
  11885. function deflate_slow(s, flush) {
  11886. var hash_head; /* head of hash chain */
  11887. var bflush; /* set if current block must be flushed */
  11888. var max_insert;
  11889. /* Process the input block. */
  11890. for (;;) {
  11891. /* Make sure that we always have enough lookahead, except
  11892. * at the end of the input file. We need MAX_MATCH bytes
  11893. * for the next match, plus MIN_MATCH bytes to insert the
  11894. * string following the next match.
  11895. */
  11896. if (s.lookahead < MIN_LOOKAHEAD) {
  11897. fill_window(s);
  11898. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  11899. return BS_NEED_MORE;
  11900. }
  11901. if (s.lookahead === 0) { break; } /* flush the current block */
  11902. }
  11903. /* Insert the string window[strstart .. strstart+2] in the
  11904. * dictionary, and set hash_head to the head of the hash chain:
  11905. */
  11906. hash_head = 0/*NIL*/;
  11907. if (s.lookahead >= MIN_MATCH) {
  11908. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  11909. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  11910. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  11911. s.head[s.ins_h] = s.strstart;
  11912. /***/
  11913. }
  11914. /* Find the longest match, discarding those <= prev_length.
  11915. */
  11916. s.prev_length = s.match_length;
  11917. s.prev_match = s.match_start;
  11918. s.match_length = MIN_MATCH-1;
  11919. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  11920. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  11921. /* To simplify the code, we prevent matches with the string
  11922. * of window index 0 (in particular we have to avoid a match
  11923. * of the string with itself at the start of the input file).
  11924. */
  11925. s.match_length = longest_match(s, hash_head);
  11926. /* longest_match() sets match_start */
  11927. if (s.match_length <= 5 &&
  11928. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  11929. /* If prev_match is also MIN_MATCH, match_start is garbage
  11930. * but we will ignore the current match anyway.
  11931. */
  11932. s.match_length = MIN_MATCH-1;
  11933. }
  11934. }
  11935. /* If there was a match at the previous step and the current
  11936. * match is not better, output the previous match:
  11937. */
  11938. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  11939. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  11940. /* Do not insert strings in hash table beyond this. */
  11941. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  11942. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  11943. s.prev_length - MIN_MATCH, bflush);***/
  11944. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  11945. /* Insert in hash table all strings up to the end of the match.
  11946. * strstart-1 and strstart are already inserted. If there is not
  11947. * enough lookahead, the last two strings are not inserted in
  11948. * the hash table.
  11949. */
  11950. s.lookahead -= s.prev_length-1;
  11951. s.prev_length -= 2;
  11952. do {
  11953. if (++s.strstart <= max_insert) {
  11954. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  11955. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  11956. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  11957. s.head[s.ins_h] = s.strstart;
  11958. /***/
  11959. }
  11960. } while (--s.prev_length !== 0);
  11961. s.match_available = 0;
  11962. s.match_length = MIN_MATCH-1;
  11963. s.strstart++;
  11964. if (bflush) {
  11965. /*** FLUSH_BLOCK(s, 0); ***/
  11966. flush_block_only(s, false);
  11967. if (s.strm.avail_out === 0) {
  11968. return BS_NEED_MORE;
  11969. }
  11970. /***/
  11971. }
  11972. } else if (s.match_available) {
  11973. /* If there was no match at the previous position, output a
  11974. * single literal. If there was a match but the current match
  11975. * is longer, truncate the previous match to a single literal.
  11976. */
  11977. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  11978. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  11979. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  11980. if (bflush) {
  11981. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  11982. flush_block_only(s, false);
  11983. /***/
  11984. }
  11985. s.strstart++;
  11986. s.lookahead--;
  11987. if (s.strm.avail_out === 0) {
  11988. return BS_NEED_MORE;
  11989. }
  11990. } else {
  11991. /* There is no previous match to compare with, wait for
  11992. * the next step to decide.
  11993. */
  11994. s.match_available = 1;
  11995. s.strstart++;
  11996. s.lookahead--;
  11997. }
  11998. }
  11999. //Assert (flush != Z_NO_FLUSH, "no flush?");
  12000. if (s.match_available) {
  12001. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  12002. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  12003. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  12004. s.match_available = 0;
  12005. }
  12006. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  12007. if (flush === Z_FINISH) {
  12008. /*** FLUSH_BLOCK(s, 1); ***/
  12009. flush_block_only(s, true);
  12010. if (s.strm.avail_out === 0) {
  12011. return BS_FINISH_STARTED;
  12012. }
  12013. /***/
  12014. return BS_FINISH_DONE;
  12015. }
  12016. if (s.last_lit) {
  12017. /*** FLUSH_BLOCK(s, 0); ***/
  12018. flush_block_only(s, false);
  12019. if (s.strm.avail_out === 0) {
  12020. return BS_NEED_MORE;
  12021. }
  12022. /***/
  12023. }
  12024. return BS_BLOCK_DONE;
  12025. }
  12026. /* ===========================================================================
  12027. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  12028. * one. Do not maintain a hash table. (It will be regenerated if this run of
  12029. * deflate switches away from Z_RLE.)
  12030. */
  12031. function deflate_rle(s, flush) {
  12032. var bflush; /* set if current block must be flushed */
  12033. var prev; /* byte at distance one to match */
  12034. var scan, strend; /* scan goes up to strend for length of run */
  12035. var _win = s.window;
  12036. for (;;) {
  12037. /* Make sure that we always have enough lookahead, except
  12038. * at the end of the input file. We need MAX_MATCH bytes
  12039. * for the longest run, plus one for the unrolled loop.
  12040. */
  12041. if (s.lookahead <= MAX_MATCH) {
  12042. fill_window(s);
  12043. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  12044. return BS_NEED_MORE;
  12045. }
  12046. if (s.lookahead === 0) { break; } /* flush the current block */
  12047. }
  12048. /* See how many times the previous byte repeats */
  12049. s.match_length = 0;
  12050. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  12051. scan = s.strstart - 1;
  12052. prev = _win[scan];
  12053. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  12054. strend = s.strstart + MAX_MATCH;
  12055. do {
  12056. /*jshint noempty:false*/
  12057. } while (prev === _win[++scan] && prev === _win[++scan] &&
  12058. prev === _win[++scan] && prev === _win[++scan] &&
  12059. prev === _win[++scan] && prev === _win[++scan] &&
  12060. prev === _win[++scan] && prev === _win[++scan] &&
  12061. scan < strend);
  12062. s.match_length = MAX_MATCH - (strend - scan);
  12063. if (s.match_length > s.lookahead) {
  12064. s.match_length = s.lookahead;
  12065. }
  12066. }
  12067. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  12068. }
  12069. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  12070. if (s.match_length >= MIN_MATCH) {
  12071. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  12072. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  12073. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  12074. s.lookahead -= s.match_length;
  12075. s.strstart += s.match_length;
  12076. s.match_length = 0;
  12077. } else {
  12078. /* No match, output a literal byte */
  12079. //Tracevv((stderr,"%c", s->window[s->strstart]));
  12080. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  12081. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  12082. s.lookahead--;
  12083. s.strstart++;
  12084. }
  12085. if (bflush) {
  12086. /*** FLUSH_BLOCK(s, 0); ***/
  12087. flush_block_only(s, false);
  12088. if (s.strm.avail_out === 0) {
  12089. return BS_NEED_MORE;
  12090. }
  12091. /***/
  12092. }
  12093. }
  12094. s.insert = 0;
  12095. if (flush === Z_FINISH) {
  12096. /*** FLUSH_BLOCK(s, 1); ***/
  12097. flush_block_only(s, true);
  12098. if (s.strm.avail_out === 0) {
  12099. return BS_FINISH_STARTED;
  12100. }
  12101. /***/
  12102. return BS_FINISH_DONE;
  12103. }
  12104. if (s.last_lit) {
  12105. /*** FLUSH_BLOCK(s, 0); ***/
  12106. flush_block_only(s, false);
  12107. if (s.strm.avail_out === 0) {
  12108. return BS_NEED_MORE;
  12109. }
  12110. /***/
  12111. }
  12112. return BS_BLOCK_DONE;
  12113. }
  12114. /* ===========================================================================
  12115. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  12116. * (It will be regenerated if this run of deflate switches away from Huffman.)
  12117. */
  12118. function deflate_huff(s, flush) {
  12119. var bflush; /* set if current block must be flushed */
  12120. for (;;) {
  12121. /* Make sure that we have a literal to write. */
  12122. if (s.lookahead === 0) {
  12123. fill_window(s);
  12124. if (s.lookahead === 0) {
  12125. if (flush === Z_NO_FLUSH) {
  12126. return BS_NEED_MORE;
  12127. }
  12128. break; /* flush the current block */
  12129. }
  12130. }
  12131. /* Output a literal byte */
  12132. s.match_length = 0;
  12133. //Tracevv((stderr,"%c", s->window[s->strstart]));
  12134. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  12135. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  12136. s.lookahead--;
  12137. s.strstart++;
  12138. if (bflush) {
  12139. /*** FLUSH_BLOCK(s, 0); ***/
  12140. flush_block_only(s, false);
  12141. if (s.strm.avail_out === 0) {
  12142. return BS_NEED_MORE;
  12143. }
  12144. /***/
  12145. }
  12146. }
  12147. s.insert = 0;
  12148. if (flush === Z_FINISH) {
  12149. /*** FLUSH_BLOCK(s, 1); ***/
  12150. flush_block_only(s, true);
  12151. if (s.strm.avail_out === 0) {
  12152. return BS_FINISH_STARTED;
  12153. }
  12154. /***/
  12155. return BS_FINISH_DONE;
  12156. }
  12157. if (s.last_lit) {
  12158. /*** FLUSH_BLOCK(s, 0); ***/
  12159. flush_block_only(s, false);
  12160. if (s.strm.avail_out === 0) {
  12161. return BS_NEED_MORE;
  12162. }
  12163. /***/
  12164. }
  12165. return BS_BLOCK_DONE;
  12166. }
  12167. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  12168. * the desired pack level (0..9). The values given below have been tuned to
  12169. * exclude worst case performance for pathological files. Better values may be
  12170. * found for specific files.
  12171. */
  12172. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  12173. this.good_length = good_length;
  12174. this.max_lazy = max_lazy;
  12175. this.nice_length = nice_length;
  12176. this.max_chain = max_chain;
  12177. this.func = func;
  12178. };
  12179. var configuration_table;
  12180. configuration_table = [
  12181. /* good lazy nice chain */
  12182. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  12183. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  12184. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  12185. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  12186. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  12187. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  12188. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  12189. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  12190. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  12191. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  12192. ];
  12193. /* ===========================================================================
  12194. * Initialize the "longest match" routines for a new zlib stream
  12195. */
  12196. function lm_init(s) {
  12197. s.window_size = 2 * s.w_size;
  12198. /*** CLEAR_HASH(s); ***/
  12199. zero(s.head); // Fill with NIL (= 0);
  12200. /* Set the default configuration parameters:
  12201. */
  12202. s.max_lazy_match = configuration_table[s.level].max_lazy;
  12203. s.good_match = configuration_table[s.level].good_length;
  12204. s.nice_match = configuration_table[s.level].nice_length;
  12205. s.max_chain_length = configuration_table[s.level].max_chain;
  12206. s.strstart = 0;
  12207. s.block_start = 0;
  12208. s.lookahead = 0;
  12209. s.insert = 0;
  12210. s.match_length = s.prev_length = MIN_MATCH - 1;
  12211. s.match_available = 0;
  12212. s.ins_h = 0;
  12213. }
  12214. function DeflateState() {
  12215. this.strm = null; /* pointer back to this zlib stream */
  12216. this.status = 0; /* as the name implies */
  12217. this.pending_buf = null; /* output still pending */
  12218. this.pending_buf_size = 0; /* size of pending_buf */
  12219. this.pending_out = 0; /* next pending byte to output to the stream */
  12220. this.pending = 0; /* nb of bytes in the pending buffer */
  12221. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  12222. this.gzhead = null; /* gzip header information to write */
  12223. this.gzindex = 0; /* where in extra, name, or comment */
  12224. this.method = Z_DEFLATED; /* can only be DEFLATED */
  12225. this.last_flush = -1; /* value of flush param for previous deflate call */
  12226. this.w_size = 0; /* LZ77 window size (32K by default) */
  12227. this.w_bits = 0; /* log2(w_size) (8..16) */
  12228. this.w_mask = 0; /* w_size - 1 */
  12229. this.window = null;
  12230. /* Sliding window. Input bytes are read into the second half of the window,
  12231. * and move to the first half later to keep a dictionary of at least wSize
  12232. * bytes. With this organization, matches are limited to a distance of
  12233. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  12234. * performed with a length multiple of the block size.
  12235. */
  12236. this.window_size = 0;
  12237. /* Actual size of window: 2*wSize, except when the user input buffer
  12238. * is directly used as sliding window.
  12239. */
  12240. this.prev = null;
  12241. /* Link to older string with same hash index. To limit the size of this
  12242. * array to 64K, this link is maintained only for the last 32K strings.
  12243. * An index in this array is thus a window index modulo 32K.
  12244. */
  12245. this.head = null; /* Heads of the hash chains or NIL. */
  12246. this.ins_h = 0; /* hash index of string to be inserted */
  12247. this.hash_size = 0; /* number of elements in hash table */
  12248. this.hash_bits = 0; /* log2(hash_size) */
  12249. this.hash_mask = 0; /* hash_size-1 */
  12250. this.hash_shift = 0;
  12251. /* Number of bits by which ins_h must be shifted at each input
  12252. * step. It must be such that after MIN_MATCH steps, the oldest
  12253. * byte no longer takes part in the hash key, that is:
  12254. * hash_shift * MIN_MATCH >= hash_bits
  12255. */
  12256. this.block_start = 0;
  12257. /* Window position at the beginning of the current output block. Gets
  12258. * negative when the window is moved backwards.
  12259. */
  12260. this.match_length = 0; /* length of best match */
  12261. this.prev_match = 0; /* previous match */
  12262. this.match_available = 0; /* set if previous match exists */
  12263. this.strstart = 0; /* start of string to insert */
  12264. this.match_start = 0; /* start of matching string */
  12265. this.lookahead = 0; /* number of valid bytes ahead in window */
  12266. this.prev_length = 0;
  12267. /* Length of the best match at previous step. Matches not greater than this
  12268. * are discarded. This is used in the lazy match evaluation.
  12269. */
  12270. this.max_chain_length = 0;
  12271. /* To speed up deflation, hash chains are never searched beyond this
  12272. * length. A higher limit improves compression ratio but degrades the
  12273. * speed.
  12274. */
  12275. this.max_lazy_match = 0;
  12276. /* Attempt to find a better match only when the current match is strictly
  12277. * smaller than this value. This mechanism is used only for compression
  12278. * levels >= 4.
  12279. */
  12280. // That's alias to max_lazy_match, don't use directly
  12281. //this.max_insert_length = 0;
  12282. /* Insert new strings in the hash table only if the match length is not
  12283. * greater than this length. This saves time but degrades compression.
  12284. * max_insert_length is used only for compression levels <= 3.
  12285. */
  12286. this.level = 0; /* compression level (1..9) */
  12287. this.strategy = 0; /* favor or force Huffman coding*/
  12288. this.good_match = 0;
  12289. /* Use a faster search when the previous match is longer than this */
  12290. this.nice_match = 0; /* Stop searching when current match exceeds this */
  12291. /* used by trees.c: */
  12292. /* Didn't use ct_data typedef below to suppress compiler warning */
  12293. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  12294. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  12295. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  12296. // Use flat array of DOUBLE size, with interleaved fata,
  12297. // because JS does not support effective
  12298. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  12299. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  12300. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  12301. zero(this.dyn_ltree);
  12302. zero(this.dyn_dtree);
  12303. zero(this.bl_tree);
  12304. this.l_desc = null; /* desc. for literal tree */
  12305. this.d_desc = null; /* desc. for distance tree */
  12306. this.bl_desc = null; /* desc. for bit length tree */
  12307. //ush bl_count[MAX_BITS+1];
  12308. this.bl_count = new utils.Buf16(MAX_BITS+1);
  12309. /* number of codes at each bit length for an optimal tree */
  12310. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  12311. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  12312. zero(this.heap);
  12313. this.heap_len = 0; /* number of elements in the heap */
  12314. this.heap_max = 0; /* element of largest frequency */
  12315. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  12316. * The same heap array is used to build all trees.
  12317. */
  12318. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  12319. zero(this.depth);
  12320. /* Depth of each subtree used as tie breaker for trees of equal frequency
  12321. */
  12322. this.l_buf = 0; /* buffer index for literals or lengths */
  12323. this.lit_bufsize = 0;
  12324. /* Size of match buffer for literals/lengths. There are 4 reasons for
  12325. * limiting lit_bufsize to 64K:
  12326. * - frequencies can be kept in 16 bit counters
  12327. * - if compression is not successful for the first block, all input
  12328. * data is still in the window so we can still emit a stored block even
  12329. * when input comes from standard input. (This can also be done for
  12330. * all blocks if lit_bufsize is not greater than 32K.)
  12331. * - if compression is not successful for a file smaller than 64K, we can
  12332. * even emit a stored file instead of a stored block (saving 5 bytes).
  12333. * This is applicable only for zip (not gzip or zlib).
  12334. * - creating new Huffman trees less frequently may not provide fast
  12335. * adaptation to changes in the input data statistics. (Take for
  12336. * example a binary file with poorly compressible code followed by
  12337. * a highly compressible string table.) Smaller buffer sizes give
  12338. * fast adaptation but have of course the overhead of transmitting
  12339. * trees more frequently.
  12340. * - I can't count above 4
  12341. */
  12342. this.last_lit = 0; /* running index in l_buf */
  12343. this.d_buf = 0;
  12344. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  12345. * the same number of elements. To use different lengths, an extra flag
  12346. * array would be necessary.
  12347. */
  12348. this.opt_len = 0; /* bit length of current block with optimal trees */
  12349. this.static_len = 0; /* bit length of current block with static trees */
  12350. this.matches = 0; /* number of string matches in current block */
  12351. this.insert = 0; /* bytes at end of window left to insert */
  12352. this.bi_buf = 0;
  12353. /* Output buffer. bits are inserted starting at the bottom (least
  12354. * significant bits).
  12355. */
  12356. this.bi_valid = 0;
  12357. /* Number of valid bits in bi_buf. All bits above the last valid bit
  12358. * are always zero.
  12359. */
  12360. // Used for window memory init. We safely ignore it for JS. That makes
  12361. // sense only for pointers and memory check tools.
  12362. //this.high_water = 0;
  12363. /* High water mark offset in window for initialized bytes -- bytes above
  12364. * this are set to zero in order to avoid memory check warnings when
  12365. * longest match routines access bytes past the input. This is then
  12366. * updated to the new high water mark.
  12367. */
  12368. }
  12369. function deflateResetKeep(strm) {
  12370. var s;
  12371. if (!strm || !strm.state) {
  12372. return err(strm, Z_STREAM_ERROR);
  12373. }
  12374. strm.total_in = strm.total_out = 0;
  12375. strm.data_type = Z_UNKNOWN;
  12376. s = strm.state;
  12377. s.pending = 0;
  12378. s.pending_out = 0;
  12379. if (s.wrap < 0) {
  12380. s.wrap = -s.wrap;
  12381. /* was made negative by deflate(..., Z_FINISH); */
  12382. }
  12383. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  12384. strm.adler = (s.wrap === 2) ?
  12385. 0 // crc32(0, Z_NULL, 0)
  12386. :
  12387. 1; // adler32(0, Z_NULL, 0)
  12388. s.last_flush = Z_NO_FLUSH;
  12389. trees._tr_init(s);
  12390. return Z_OK;
  12391. }
  12392. function deflateReset(strm) {
  12393. var ret = deflateResetKeep(strm);
  12394. if (ret === Z_OK) {
  12395. lm_init(strm.state);
  12396. }
  12397. return ret;
  12398. }
  12399. function deflateSetHeader(strm, head) {
  12400. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  12401. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  12402. strm.state.gzhead = head;
  12403. return Z_OK;
  12404. }
  12405. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  12406. if (!strm) { // === Z_NULL
  12407. return Z_STREAM_ERROR;
  12408. }
  12409. var wrap = 1;
  12410. if (level === Z_DEFAULT_COMPRESSION) {
  12411. level = 6;
  12412. }
  12413. if (windowBits < 0) { /* suppress zlib wrapper */
  12414. wrap = 0;
  12415. windowBits = -windowBits;
  12416. }
  12417. else if (windowBits > 15) {
  12418. wrap = 2; /* write gzip wrapper instead */
  12419. windowBits -= 16;
  12420. }
  12421. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  12422. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  12423. strategy < 0 || strategy > Z_FIXED) {
  12424. return err(strm, Z_STREAM_ERROR);
  12425. }
  12426. if (windowBits === 8) {
  12427. windowBits = 9;
  12428. }
  12429. /* until 256-byte window bug fixed */
  12430. var s = new DeflateState();
  12431. strm.state = s;
  12432. s.strm = strm;
  12433. s.wrap = wrap;
  12434. s.gzhead = null;
  12435. s.w_bits = windowBits;
  12436. s.w_size = 1 << s.w_bits;
  12437. s.w_mask = s.w_size - 1;
  12438. s.hash_bits = memLevel + 7;
  12439. s.hash_size = 1 << s.hash_bits;
  12440. s.hash_mask = s.hash_size - 1;
  12441. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  12442. s.window = new utils.Buf8(s.w_size * 2);
  12443. s.head = new utils.Buf16(s.hash_size);
  12444. s.prev = new utils.Buf16(s.w_size);
  12445. // Don't need mem init magic for JS.
  12446. //s.high_water = 0; /* nothing written to s->window yet */
  12447. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  12448. s.pending_buf_size = s.lit_bufsize * 4;
  12449. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  12450. s.d_buf = s.lit_bufsize >> 1;
  12451. s.l_buf = (1 + 2) * s.lit_bufsize;
  12452. s.level = level;
  12453. s.strategy = strategy;
  12454. s.method = method;
  12455. return deflateReset(strm);
  12456. }
  12457. function deflateInit(strm, level) {
  12458. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  12459. }
  12460. function deflate(strm, flush) {
  12461. var old_flush, s;
  12462. var beg, val; // for gzip header write only
  12463. if (!strm || !strm.state ||
  12464. flush > Z_BLOCK || flush < 0) {
  12465. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  12466. }
  12467. s = strm.state;
  12468. if (!strm.output ||
  12469. (!strm.input && strm.avail_in !== 0) ||
  12470. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  12471. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  12472. }
  12473. s.strm = strm; /* just in case */
  12474. old_flush = s.last_flush;
  12475. s.last_flush = flush;
  12476. /* Write the header */
  12477. if (s.status === INIT_STATE) {
  12478. if (s.wrap === 2) { // GZIP header
  12479. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  12480. put_byte(s, 31);
  12481. put_byte(s, 139);
  12482. put_byte(s, 8);
  12483. if (!s.gzhead) { // s->gzhead == Z_NULL
  12484. put_byte(s, 0);
  12485. put_byte(s, 0);
  12486. put_byte(s, 0);
  12487. put_byte(s, 0);
  12488. put_byte(s, 0);
  12489. put_byte(s, s.level === 9 ? 2 :
  12490. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  12491. 4 : 0));
  12492. put_byte(s, OS_CODE);
  12493. s.status = BUSY_STATE;
  12494. }
  12495. else {
  12496. put_byte(s, (s.gzhead.text ? 1 : 0) +
  12497. (s.gzhead.hcrc ? 2 : 0) +
  12498. (!s.gzhead.extra ? 0 : 4) +
  12499. (!s.gzhead.name ? 0 : 8) +
  12500. (!s.gzhead.comment ? 0 : 16)
  12501. );
  12502. put_byte(s, s.gzhead.time & 0xff);
  12503. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  12504. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  12505. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  12506. put_byte(s, s.level === 9 ? 2 :
  12507. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  12508. 4 : 0));
  12509. put_byte(s, s.gzhead.os & 0xff);
  12510. if (s.gzhead.extra && s.gzhead.extra.length) {
  12511. put_byte(s, s.gzhead.extra.length & 0xff);
  12512. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  12513. }
  12514. if (s.gzhead.hcrc) {
  12515. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  12516. }
  12517. s.gzindex = 0;
  12518. s.status = EXTRA_STATE;
  12519. }
  12520. }
  12521. else // DEFLATE header
  12522. {
  12523. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  12524. var level_flags = -1;
  12525. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  12526. level_flags = 0;
  12527. } else if (s.level < 6) {
  12528. level_flags = 1;
  12529. } else if (s.level === 6) {
  12530. level_flags = 2;
  12531. } else {
  12532. level_flags = 3;
  12533. }
  12534. header |= (level_flags << 6);
  12535. if (s.strstart !== 0) { header |= PRESET_DICT; }
  12536. header += 31 - (header % 31);
  12537. s.status = BUSY_STATE;
  12538. putShortMSB(s, header);
  12539. /* Save the adler32 of the preset dictionary: */
  12540. if (s.strstart !== 0) {
  12541. putShortMSB(s, strm.adler >>> 16);
  12542. putShortMSB(s, strm.adler & 0xffff);
  12543. }
  12544. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  12545. }
  12546. }
  12547. //#ifdef GZIP
  12548. if (s.status === EXTRA_STATE) {
  12549. if (s.gzhead.extra/* != Z_NULL*/) {
  12550. beg = s.pending; /* start of bytes to update crc */
  12551. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  12552. if (s.pending === s.pending_buf_size) {
  12553. if (s.gzhead.hcrc && s.pending > beg) {
  12554. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12555. }
  12556. flush_pending(strm);
  12557. beg = s.pending;
  12558. if (s.pending === s.pending_buf_size) {
  12559. break;
  12560. }
  12561. }
  12562. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  12563. s.gzindex++;
  12564. }
  12565. if (s.gzhead.hcrc && s.pending > beg) {
  12566. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12567. }
  12568. if (s.gzindex === s.gzhead.extra.length) {
  12569. s.gzindex = 0;
  12570. s.status = NAME_STATE;
  12571. }
  12572. }
  12573. else {
  12574. s.status = NAME_STATE;
  12575. }
  12576. }
  12577. if (s.status === NAME_STATE) {
  12578. if (s.gzhead.name/* != Z_NULL*/) {
  12579. beg = s.pending; /* start of bytes to update crc */
  12580. //int val;
  12581. do {
  12582. if (s.pending === s.pending_buf_size) {
  12583. if (s.gzhead.hcrc && s.pending > beg) {
  12584. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12585. }
  12586. flush_pending(strm);
  12587. beg = s.pending;
  12588. if (s.pending === s.pending_buf_size) {
  12589. val = 1;
  12590. break;
  12591. }
  12592. }
  12593. // JS specific: little magic to add zero terminator to end of string
  12594. if (s.gzindex < s.gzhead.name.length) {
  12595. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  12596. } else {
  12597. val = 0;
  12598. }
  12599. put_byte(s, val);
  12600. } while (val !== 0);
  12601. if (s.gzhead.hcrc && s.pending > beg) {
  12602. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12603. }
  12604. if (val === 0) {
  12605. s.gzindex = 0;
  12606. s.status = COMMENT_STATE;
  12607. }
  12608. }
  12609. else {
  12610. s.status = COMMENT_STATE;
  12611. }
  12612. }
  12613. if (s.status === COMMENT_STATE) {
  12614. if (s.gzhead.comment/* != Z_NULL*/) {
  12615. beg = s.pending; /* start of bytes to update crc */
  12616. //int val;
  12617. do {
  12618. if (s.pending === s.pending_buf_size) {
  12619. if (s.gzhead.hcrc && s.pending > beg) {
  12620. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12621. }
  12622. flush_pending(strm);
  12623. beg = s.pending;
  12624. if (s.pending === s.pending_buf_size) {
  12625. val = 1;
  12626. break;
  12627. }
  12628. }
  12629. // JS specific: little magic to add zero terminator to end of string
  12630. if (s.gzindex < s.gzhead.comment.length) {
  12631. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  12632. } else {
  12633. val = 0;
  12634. }
  12635. put_byte(s, val);
  12636. } while (val !== 0);
  12637. if (s.gzhead.hcrc && s.pending > beg) {
  12638. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12639. }
  12640. if (val === 0) {
  12641. s.status = HCRC_STATE;
  12642. }
  12643. }
  12644. else {
  12645. s.status = HCRC_STATE;
  12646. }
  12647. }
  12648. if (s.status === HCRC_STATE) {
  12649. if (s.gzhead.hcrc) {
  12650. if (s.pending + 2 > s.pending_buf_size) {
  12651. flush_pending(strm);
  12652. }
  12653. if (s.pending + 2 <= s.pending_buf_size) {
  12654. put_byte(s, strm.adler & 0xff);
  12655. put_byte(s, (strm.adler >> 8) & 0xff);
  12656. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  12657. s.status = BUSY_STATE;
  12658. }
  12659. }
  12660. else {
  12661. s.status = BUSY_STATE;
  12662. }
  12663. }
  12664. //#endif
  12665. /* Flush as much pending output as possible */
  12666. if (s.pending !== 0) {
  12667. flush_pending(strm);
  12668. if (strm.avail_out === 0) {
  12669. /* Since avail_out is 0, deflate will be called again with
  12670. * more output space, but possibly with both pending and
  12671. * avail_in equal to zero. There won't be anything to do,
  12672. * but this is not an error situation so make sure we
  12673. * return OK instead of BUF_ERROR at next call of deflate:
  12674. */
  12675. s.last_flush = -1;
  12676. return Z_OK;
  12677. }
  12678. /* Make sure there is something to do and avoid duplicate consecutive
  12679. * flushes. For repeated and useless calls with Z_FINISH, we keep
  12680. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  12681. */
  12682. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  12683. flush !== Z_FINISH) {
  12684. return err(strm, Z_BUF_ERROR);
  12685. }
  12686. /* User must not provide more input after the first FINISH: */
  12687. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  12688. return err(strm, Z_BUF_ERROR);
  12689. }
  12690. /* Start a new block or continue the current one.
  12691. */
  12692. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  12693. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  12694. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  12695. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  12696. configuration_table[s.level].func(s, flush));
  12697. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  12698. s.status = FINISH_STATE;
  12699. }
  12700. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  12701. if (strm.avail_out === 0) {
  12702. s.last_flush = -1;
  12703. /* avoid BUF_ERROR next call, see above */
  12704. }
  12705. return Z_OK;
  12706. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  12707. * of deflate should use the same flush parameter to make sure
  12708. * that the flush is complete. So we don't have to output an
  12709. * empty block here, this will be done at next call. This also
  12710. * ensures that for a very small output buffer, we emit at most
  12711. * one empty block.
  12712. */
  12713. }
  12714. if (bstate === BS_BLOCK_DONE) {
  12715. if (flush === Z_PARTIAL_FLUSH) {
  12716. trees._tr_align(s);
  12717. }
  12718. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  12719. trees._tr_stored_block(s, 0, 0, false);
  12720. /* For a full flush, this empty block will be recognized
  12721. * as a special marker by inflate_sync().
  12722. */
  12723. if (flush === Z_FULL_FLUSH) {
  12724. /*** CLEAR_HASH(s); ***/ /* forget history */
  12725. zero(s.head); // Fill with NIL (= 0);
  12726. if (s.lookahead === 0) {
  12727. s.strstart = 0;
  12728. s.block_start = 0;
  12729. s.insert = 0;
  12730. }
  12731. }
  12732. }
  12733. flush_pending(strm);
  12734. if (strm.avail_out === 0) {
  12735. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  12736. return Z_OK;
  12737. }
  12738. }
  12739. }
  12740. //Assert(strm->avail_out > 0, "bug2");
  12741. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  12742. if (flush !== Z_FINISH) { return Z_OK; }
  12743. if (s.wrap <= 0) { return Z_STREAM_END; }
  12744. /* Write the trailer */
  12745. if (s.wrap === 2) {
  12746. put_byte(s, strm.adler & 0xff);
  12747. put_byte(s, (strm.adler >> 8) & 0xff);
  12748. put_byte(s, (strm.adler >> 16) & 0xff);
  12749. put_byte(s, (strm.adler >> 24) & 0xff);
  12750. put_byte(s, strm.total_in & 0xff);
  12751. put_byte(s, (strm.total_in >> 8) & 0xff);
  12752. put_byte(s, (strm.total_in >> 16) & 0xff);
  12753. put_byte(s, (strm.total_in >> 24) & 0xff);
  12754. }
  12755. else
  12756. {
  12757. putShortMSB(s, strm.adler >>> 16);
  12758. putShortMSB(s, strm.adler & 0xffff);
  12759. }
  12760. flush_pending(strm);
  12761. /* If avail_out is zero, the application will call deflate again
  12762. * to flush the rest.
  12763. */
  12764. if (s.wrap > 0) { s.wrap = -s.wrap; }
  12765. /* write the trailer only once! */
  12766. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  12767. }
  12768. function deflateEnd(strm) {
  12769. var status;
  12770. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  12771. return Z_STREAM_ERROR;
  12772. }
  12773. status = strm.state.status;
  12774. if (status !== INIT_STATE &&
  12775. status !== EXTRA_STATE &&
  12776. status !== NAME_STATE &&
  12777. status !== COMMENT_STATE &&
  12778. status !== HCRC_STATE &&
  12779. status !== BUSY_STATE &&
  12780. status !== FINISH_STATE
  12781. ) {
  12782. return err(strm, Z_STREAM_ERROR);
  12783. }
  12784. strm.state = null;
  12785. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  12786. }
  12787. /* =========================================================================
  12788. * Copy the source state to the destination state
  12789. */
  12790. //function deflateCopy(dest, source) {
  12791. //
  12792. //}
  12793. exports.deflateInit = deflateInit;
  12794. exports.deflateInit2 = deflateInit2;
  12795. exports.deflateReset = deflateReset;
  12796. exports.deflateResetKeep = deflateResetKeep;
  12797. exports.deflateSetHeader = deflateSetHeader;
  12798. exports.deflate = deflate;
  12799. exports.deflateEnd = deflateEnd;
  12800. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  12801. /* Not implemented
  12802. exports.deflateBound = deflateBound;
  12803. exports.deflateCopy = deflateCopy;
  12804. exports.deflateSetDictionary = deflateSetDictionary;
  12805. exports.deflateParams = deflateParams;
  12806. exports.deflatePending = deflatePending;
  12807. exports.deflatePrime = deflatePrime;
  12808. exports.deflateTune = deflateTune;
  12809. */
  12810. },{"../utils/common":39,"./adler32":41,"./crc32":43,"./messages":49,"./trees":50}],45:[function(require,module,exports){
  12811. 'use strict';
  12812. function GZheader() {
  12813. /* true if compressed data believed to be text */
  12814. this.text = 0;
  12815. /* modification time */
  12816. this.time = 0;
  12817. /* extra flags (not used when writing a gzip file) */
  12818. this.xflags = 0;
  12819. /* operating system */
  12820. this.os = 0;
  12821. /* pointer to extra field or Z_NULL if none */
  12822. this.extra = null;
  12823. /* extra field length (valid if extra != Z_NULL) */
  12824. this.extra_len = 0; // Actually, we don't need it in JS,
  12825. // but leave for few code modifications
  12826. //
  12827. // Setup limits is not necessary because in js we should not preallocate memory
  12828. // for inflate use constant limit in 65536 bytes
  12829. //
  12830. /* space at extra (only when reading header) */
  12831. // this.extra_max = 0;
  12832. /* pointer to zero-terminated file name or Z_NULL */
  12833. this.name = '';
  12834. /* space at name (only when reading header) */
  12835. // this.name_max = 0;
  12836. /* pointer to zero-terminated comment or Z_NULL */
  12837. this.comment = '';
  12838. /* space at comment (only when reading header) */
  12839. // this.comm_max = 0;
  12840. /* true if there was or will be a header crc */
  12841. this.hcrc = 0;
  12842. /* true when done reading gzip header (not used when writing a gzip file) */
  12843. this.done = false;
  12844. }
  12845. module.exports = GZheader;
  12846. },{}],46:[function(require,module,exports){
  12847. 'use strict';
  12848. // See state defs from inflate.js
  12849. var BAD = 30; /* got a data error -- remain here until reset */
  12850. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  12851. /*
  12852. Decode literal, length, and distance codes and write out the resulting
  12853. literal and match bytes until either not enough input or output is
  12854. available, an end-of-block is encountered, or a data error is encountered.
  12855. When large enough input and output buffers are supplied to inflate(), for
  12856. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  12857. inflate execution time is spent in this routine.
  12858. Entry assumptions:
  12859. state.mode === LEN
  12860. strm.avail_in >= 6
  12861. strm.avail_out >= 258
  12862. start >= strm.avail_out
  12863. state.bits < 8
  12864. On return, state.mode is one of:
  12865. LEN -- ran out of enough output space or enough available input
  12866. TYPE -- reached end of block code, inflate() to interpret next block
  12867. BAD -- error in block data
  12868. Notes:
  12869. - The maximum input bits used by a length/distance pair is 15 bits for the
  12870. length code, 5 bits for the length extra, 15 bits for the distance code,
  12871. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  12872. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  12873. checking for available input while decoding.
  12874. - The maximum bytes that a single length/distance pair can output is 258
  12875. bytes, which is the maximum length that can be coded. inflate_fast()
  12876. requires strm.avail_out >= 258 for each loop to avoid checking for
  12877. output space.
  12878. */
  12879. module.exports = function inflate_fast(strm, start) {
  12880. var state;
  12881. var _in; /* local strm.input */
  12882. var last; /* have enough input while in < last */
  12883. var _out; /* local strm.output */
  12884. var beg; /* inflate()'s initial strm.output */
  12885. var end; /* while out < end, enough space available */
  12886. //#ifdef INFLATE_STRICT
  12887. var dmax; /* maximum distance from zlib header */
  12888. //#endif
  12889. var wsize; /* window size or zero if not using window */
  12890. var whave; /* valid bytes in the window */
  12891. var wnext; /* window write index */
  12892. var window; /* allocated sliding window, if wsize != 0 */
  12893. var hold; /* local strm.hold */
  12894. var bits; /* local strm.bits */
  12895. var lcode; /* local strm.lencode */
  12896. var dcode; /* local strm.distcode */
  12897. var lmask; /* mask for first level of length codes */
  12898. var dmask; /* mask for first level of distance codes */
  12899. var here; /* retrieved table entry */
  12900. var op; /* code bits, operation, extra bits, or */
  12901. /* window position, window bytes to copy */
  12902. var len; /* match length, unused bytes */
  12903. var dist; /* match distance */
  12904. var from; /* where to copy match from */
  12905. var from_source;
  12906. var input, output; // JS specific, because we have no pointers
  12907. /* copy state to local variables */
  12908. state = strm.state;
  12909. //here = state.here;
  12910. _in = strm.next_in;
  12911. input = strm.input;
  12912. last = _in + (strm.avail_in - 5);
  12913. _out = strm.next_out;
  12914. output = strm.output;
  12915. beg = _out - (start - strm.avail_out);
  12916. end = _out + (strm.avail_out - 257);
  12917. //#ifdef INFLATE_STRICT
  12918. dmax = state.dmax;
  12919. //#endif
  12920. wsize = state.wsize;
  12921. whave = state.whave;
  12922. wnext = state.wnext;
  12923. window = state.window;
  12924. hold = state.hold;
  12925. bits = state.bits;
  12926. lcode = state.lencode;
  12927. dcode = state.distcode;
  12928. lmask = (1 << state.lenbits) - 1;
  12929. dmask = (1 << state.distbits) - 1;
  12930. /* decode literals and length/distances until end-of-block or not enough
  12931. input data or output space */
  12932. top:
  12933. do {
  12934. if (bits < 15) {
  12935. hold += input[_in++] << bits;
  12936. bits += 8;
  12937. hold += input[_in++] << bits;
  12938. bits += 8;
  12939. }
  12940. here = lcode[hold & lmask];
  12941. dolen:
  12942. for (;;) { // Goto emulation
  12943. op = here >>> 24/*here.bits*/;
  12944. hold >>>= op;
  12945. bits -= op;
  12946. op = (here >>> 16) & 0xff/*here.op*/;
  12947. if (op === 0) { /* literal */
  12948. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  12949. // "inflate: literal '%c'\n" :
  12950. // "inflate: literal 0x%02x\n", here.val));
  12951. output[_out++] = here & 0xffff/*here.val*/;
  12952. }
  12953. else if (op & 16) { /* length base */
  12954. len = here & 0xffff/*here.val*/;
  12955. op &= 15; /* number of extra bits */
  12956. if (op) {
  12957. if (bits < op) {
  12958. hold += input[_in++] << bits;
  12959. bits += 8;
  12960. }
  12961. len += hold & ((1 << op) - 1);
  12962. hold >>>= op;
  12963. bits -= op;
  12964. }
  12965. //Tracevv((stderr, "inflate: length %u\n", len));
  12966. if (bits < 15) {
  12967. hold += input[_in++] << bits;
  12968. bits += 8;
  12969. hold += input[_in++] << bits;
  12970. bits += 8;
  12971. }
  12972. here = dcode[hold & dmask];
  12973. dodist:
  12974. for (;;) { // goto emulation
  12975. op = here >>> 24/*here.bits*/;
  12976. hold >>>= op;
  12977. bits -= op;
  12978. op = (here >>> 16) & 0xff/*here.op*/;
  12979. if (op & 16) { /* distance base */
  12980. dist = here & 0xffff/*here.val*/;
  12981. op &= 15; /* number of extra bits */
  12982. if (bits < op) {
  12983. hold += input[_in++] << bits;
  12984. bits += 8;
  12985. if (bits < op) {
  12986. hold += input[_in++] << bits;
  12987. bits += 8;
  12988. }
  12989. }
  12990. dist += hold & ((1 << op) - 1);
  12991. //#ifdef INFLATE_STRICT
  12992. if (dist > dmax) {
  12993. strm.msg = 'invalid distance too far back';
  12994. state.mode = BAD;
  12995. break top;
  12996. }
  12997. //#endif
  12998. hold >>>= op;
  12999. bits -= op;
  13000. //Tracevv((stderr, "inflate: distance %u\n", dist));
  13001. op = _out - beg; /* max distance in output */
  13002. if (dist > op) { /* see if copy from window */
  13003. op = dist - op; /* distance back in window */
  13004. if (op > whave) {
  13005. if (state.sane) {
  13006. strm.msg = 'invalid distance too far back';
  13007. state.mode = BAD;
  13008. break top;
  13009. }
  13010. // (!) This block is disabled in zlib defailts,
  13011. // don't enable it for binary compatibility
  13012. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  13013. // if (len <= op - whave) {
  13014. // do {
  13015. // output[_out++] = 0;
  13016. // } while (--len);
  13017. // continue top;
  13018. // }
  13019. // len -= op - whave;
  13020. // do {
  13021. // output[_out++] = 0;
  13022. // } while (--op > whave);
  13023. // if (op === 0) {
  13024. // from = _out - dist;
  13025. // do {
  13026. // output[_out++] = output[from++];
  13027. // } while (--len);
  13028. // continue top;
  13029. // }
  13030. //#endif
  13031. }
  13032. from = 0; // window index
  13033. from_source = window;
  13034. if (wnext === 0) { /* very common case */
  13035. from += wsize - op;
  13036. if (op < len) { /* some from window */
  13037. len -= op;
  13038. do {
  13039. output[_out++] = window[from++];
  13040. } while (--op);
  13041. from = _out - dist; /* rest from output */
  13042. from_source = output;
  13043. }
  13044. }
  13045. else if (wnext < op) { /* wrap around window */
  13046. from += wsize + wnext - op;
  13047. op -= wnext;
  13048. if (op < len) { /* some from end of window */
  13049. len -= op;
  13050. do {
  13051. output[_out++] = window[from++];
  13052. } while (--op);
  13053. from = 0;
  13054. if (wnext < len) { /* some from start of window */
  13055. op = wnext;
  13056. len -= op;
  13057. do {
  13058. output[_out++] = window[from++];
  13059. } while (--op);
  13060. from = _out - dist; /* rest from output */
  13061. from_source = output;
  13062. }
  13063. }
  13064. }
  13065. else { /* contiguous in window */
  13066. from += wnext - op;
  13067. if (op < len) { /* some from window */
  13068. len -= op;
  13069. do {
  13070. output[_out++] = window[from++];
  13071. } while (--op);
  13072. from = _out - dist; /* rest from output */
  13073. from_source = output;
  13074. }
  13075. }
  13076. while (len > 2) {
  13077. output[_out++] = from_source[from++];
  13078. output[_out++] = from_source[from++];
  13079. output[_out++] = from_source[from++];
  13080. len -= 3;
  13081. }
  13082. if (len) {
  13083. output[_out++] = from_source[from++];
  13084. if (len > 1) {
  13085. output[_out++] = from_source[from++];
  13086. }
  13087. }
  13088. }
  13089. else {
  13090. from = _out - dist; /* copy direct from output */
  13091. do { /* minimum length is three */
  13092. output[_out++] = output[from++];
  13093. output[_out++] = output[from++];
  13094. output[_out++] = output[from++];
  13095. len -= 3;
  13096. } while (len > 2);
  13097. if (len) {
  13098. output[_out++] = output[from++];
  13099. if (len > 1) {
  13100. output[_out++] = output[from++];
  13101. }
  13102. }
  13103. }
  13104. }
  13105. else if ((op & 64) === 0) { /* 2nd level distance code */
  13106. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  13107. continue dodist;
  13108. }
  13109. else {
  13110. strm.msg = 'invalid distance code';
  13111. state.mode = BAD;
  13112. break top;
  13113. }
  13114. break; // need to emulate goto via "continue"
  13115. }
  13116. }
  13117. else if ((op & 64) === 0) { /* 2nd level length code */
  13118. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  13119. continue dolen;
  13120. }
  13121. else if (op & 32) { /* end-of-block */
  13122. //Tracevv((stderr, "inflate: end of block\n"));
  13123. state.mode = TYPE;
  13124. break top;
  13125. }
  13126. else {
  13127. strm.msg = 'invalid literal/length code';
  13128. state.mode = BAD;
  13129. break top;
  13130. }
  13131. break; // need to emulate goto via "continue"
  13132. }
  13133. } while (_in < last && _out < end);
  13134. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  13135. len = bits >> 3;
  13136. _in -= len;
  13137. bits -= len << 3;
  13138. hold &= (1 << bits) - 1;
  13139. /* update state and return */
  13140. strm.next_in = _in;
  13141. strm.next_out = _out;
  13142. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  13143. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  13144. state.hold = hold;
  13145. state.bits = bits;
  13146. return;
  13147. };
  13148. },{}],47:[function(require,module,exports){
  13149. 'use strict';
  13150. var utils = require('../utils/common');
  13151. var adler32 = require('./adler32');
  13152. var crc32 = require('./crc32');
  13153. var inflate_fast = require('./inffast');
  13154. var inflate_table = require('./inftrees');
  13155. var CODES = 0;
  13156. var LENS = 1;
  13157. var DISTS = 2;
  13158. /* Public constants ==========================================================*/
  13159. /* ===========================================================================*/
  13160. /* Allowed flush values; see deflate() and inflate() below for details */
  13161. //var Z_NO_FLUSH = 0;
  13162. //var Z_PARTIAL_FLUSH = 1;
  13163. //var Z_SYNC_FLUSH = 2;
  13164. //var Z_FULL_FLUSH = 3;
  13165. var Z_FINISH = 4;
  13166. var Z_BLOCK = 5;
  13167. var Z_TREES = 6;
  13168. /* Return codes for the compression/decompression functions. Negative values
  13169. * are errors, positive values are used for special but normal events.
  13170. */
  13171. var Z_OK = 0;
  13172. var Z_STREAM_END = 1;
  13173. var Z_NEED_DICT = 2;
  13174. //var Z_ERRNO = -1;
  13175. var Z_STREAM_ERROR = -2;
  13176. var Z_DATA_ERROR = -3;
  13177. var Z_MEM_ERROR = -4;
  13178. var Z_BUF_ERROR = -5;
  13179. //var Z_VERSION_ERROR = -6;
  13180. /* The deflate compression method */
  13181. var Z_DEFLATED = 8;
  13182. /* STATES ====================================================================*/
  13183. /* ===========================================================================*/
  13184. var HEAD = 1; /* i: waiting for magic header */
  13185. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  13186. var TIME = 3; /* i: waiting for modification time (gzip) */
  13187. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  13188. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  13189. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  13190. var NAME = 7; /* i: waiting for end of file name (gzip) */
  13191. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  13192. var HCRC = 9; /* i: waiting for header crc (gzip) */
  13193. var DICTID = 10; /* i: waiting for dictionary check value */
  13194. var DICT = 11; /* waiting for inflateSetDictionary() call */
  13195. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  13196. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  13197. var STORED = 14; /* i: waiting for stored size (length and complement) */
  13198. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  13199. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  13200. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  13201. var LENLENS = 18; /* i: waiting for code length code lengths */
  13202. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  13203. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  13204. var LEN = 21; /* i: waiting for length/lit/eob code */
  13205. var LENEXT = 22; /* i: waiting for length extra bits */
  13206. var DIST = 23; /* i: waiting for distance code */
  13207. var DISTEXT = 24; /* i: waiting for distance extra bits */
  13208. var MATCH = 25; /* o: waiting for output space to copy string */
  13209. var LIT = 26; /* o: waiting for output space to write literal */
  13210. var CHECK = 27; /* i: waiting for 32-bit check value */
  13211. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  13212. var DONE = 29; /* finished check, done -- remain here until reset */
  13213. var BAD = 30; /* got a data error -- remain here until reset */
  13214. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  13215. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  13216. /* ===========================================================================*/
  13217. var ENOUGH_LENS = 852;
  13218. var ENOUGH_DISTS = 592;
  13219. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  13220. var MAX_WBITS = 15;
  13221. /* 32K LZ77 window */
  13222. var DEF_WBITS = MAX_WBITS;
  13223. function ZSWAP32(q) {
  13224. return (((q >>> 24) & 0xff) +
  13225. ((q >>> 8) & 0xff00) +
  13226. ((q & 0xff00) << 8) +
  13227. ((q & 0xff) << 24));
  13228. }
  13229. function InflateState() {
  13230. this.mode = 0; /* current inflate mode */
  13231. this.last = false; /* true if processing last block */
  13232. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  13233. this.havedict = false; /* true if dictionary provided */
  13234. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  13235. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  13236. this.check = 0; /* protected copy of check value */
  13237. this.total = 0; /* protected copy of output count */
  13238. // TODO: may be {}
  13239. this.head = null; /* where to save gzip header information */
  13240. /* sliding window */
  13241. this.wbits = 0; /* log base 2 of requested window size */
  13242. this.wsize = 0; /* window size or zero if not using window */
  13243. this.whave = 0; /* valid bytes in the window */
  13244. this.wnext = 0; /* window write index */
  13245. this.window = null; /* allocated sliding window, if needed */
  13246. /* bit accumulator */
  13247. this.hold = 0; /* input bit accumulator */
  13248. this.bits = 0; /* number of bits in "in" */
  13249. /* for string and stored block copying */
  13250. this.length = 0; /* literal or length of data to copy */
  13251. this.offset = 0; /* distance back to copy string from */
  13252. /* for table and code decoding */
  13253. this.extra = 0; /* extra bits needed */
  13254. /* fixed and dynamic code tables */
  13255. this.lencode = null; /* starting table for length/literal codes */
  13256. this.distcode = null; /* starting table for distance codes */
  13257. this.lenbits = 0; /* index bits for lencode */
  13258. this.distbits = 0; /* index bits for distcode */
  13259. /* dynamic table building */
  13260. this.ncode = 0; /* number of code length code lengths */
  13261. this.nlen = 0; /* number of length code lengths */
  13262. this.ndist = 0; /* number of distance code lengths */
  13263. this.have = 0; /* number of code lengths in lens[] */
  13264. this.next = null; /* next available space in codes[] */
  13265. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  13266. this.work = new utils.Buf16(288); /* work area for code table building */
  13267. /*
  13268. because we don't have pointers in js, we use lencode and distcode directly
  13269. as buffers so we don't need codes
  13270. */
  13271. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  13272. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  13273. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  13274. this.sane = 0; /* if false, allow invalid distance too far */
  13275. this.back = 0; /* bits back of last unprocessed length/lit */
  13276. this.was = 0; /* initial length of match */
  13277. }
  13278. function inflateResetKeep(strm) {
  13279. var state;
  13280. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  13281. state = strm.state;
  13282. strm.total_in = strm.total_out = state.total = 0;
  13283. strm.msg = ''; /*Z_NULL*/
  13284. if (state.wrap) { /* to support ill-conceived Java test suite */
  13285. strm.adler = state.wrap & 1;
  13286. }
  13287. state.mode = HEAD;
  13288. state.last = 0;
  13289. state.havedict = 0;
  13290. state.dmax = 32768;
  13291. state.head = null/*Z_NULL*/;
  13292. state.hold = 0;
  13293. state.bits = 0;
  13294. //state.lencode = state.distcode = state.next = state.codes;
  13295. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  13296. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  13297. state.sane = 1;
  13298. state.back = -1;
  13299. //Tracev((stderr, "inflate: reset\n"));
  13300. return Z_OK;
  13301. }
  13302. function inflateReset(strm) {
  13303. var state;
  13304. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  13305. state = strm.state;
  13306. state.wsize = 0;
  13307. state.whave = 0;
  13308. state.wnext = 0;
  13309. return inflateResetKeep(strm);
  13310. }
  13311. function inflateReset2(strm, windowBits) {
  13312. var wrap;
  13313. var state;
  13314. /* get the state */
  13315. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  13316. state = strm.state;
  13317. /* extract wrap request from windowBits parameter */
  13318. if (windowBits < 0) {
  13319. wrap = 0;
  13320. windowBits = -windowBits;
  13321. }
  13322. else {
  13323. wrap = (windowBits >> 4) + 1;
  13324. if (windowBits < 48) {
  13325. windowBits &= 15;
  13326. }
  13327. }
  13328. /* set number of window bits, free window if different */
  13329. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  13330. return Z_STREAM_ERROR;
  13331. }
  13332. if (state.window !== null && state.wbits !== windowBits) {
  13333. state.window = null;
  13334. }
  13335. /* update state and reset the rest of it */
  13336. state.wrap = wrap;
  13337. state.wbits = windowBits;
  13338. return inflateReset(strm);
  13339. }
  13340. function inflateInit2(strm, windowBits) {
  13341. var ret;
  13342. var state;
  13343. if (!strm) { return Z_STREAM_ERROR; }
  13344. //strm.msg = Z_NULL; /* in case we return an error */
  13345. state = new InflateState();
  13346. //if (state === Z_NULL) return Z_MEM_ERROR;
  13347. //Tracev((stderr, "inflate: allocated\n"));
  13348. strm.state = state;
  13349. state.window = null/*Z_NULL*/;
  13350. ret = inflateReset2(strm, windowBits);
  13351. if (ret !== Z_OK) {
  13352. strm.state = null/*Z_NULL*/;
  13353. }
  13354. return ret;
  13355. }
  13356. function inflateInit(strm) {
  13357. return inflateInit2(strm, DEF_WBITS);
  13358. }
  13359. /*
  13360. Return state with length and distance decoding tables and index sizes set to
  13361. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  13362. If BUILDFIXED is defined, then instead this routine builds the tables the
  13363. first time it's called, and returns those tables the first time and
  13364. thereafter. This reduces the size of the code by about 2K bytes, in
  13365. exchange for a little execution time. However, BUILDFIXED should not be
  13366. used for threaded applications, since the rewriting of the tables and virgin
  13367. may not be thread-safe.
  13368. */
  13369. var virgin = true;
  13370. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  13371. function fixedtables(state) {
  13372. /* build fixed huffman tables if first call (may not be thread safe) */
  13373. if (virgin) {
  13374. var sym;
  13375. lenfix = new utils.Buf32(512);
  13376. distfix = new utils.Buf32(32);
  13377. /* literal/length table */
  13378. sym = 0;
  13379. while (sym < 144) { state.lens[sym++] = 8; }
  13380. while (sym < 256) { state.lens[sym++] = 9; }
  13381. while (sym < 280) { state.lens[sym++] = 7; }
  13382. while (sym < 288) { state.lens[sym++] = 8; }
  13383. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  13384. /* distance table */
  13385. sym = 0;
  13386. while (sym < 32) { state.lens[sym++] = 5; }
  13387. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  13388. /* do this just once */
  13389. virgin = false;
  13390. }
  13391. state.lencode = lenfix;
  13392. state.lenbits = 9;
  13393. state.distcode = distfix;
  13394. state.distbits = 5;
  13395. }
  13396. /*
  13397. Update the window with the last wsize (normally 32K) bytes written before
  13398. returning. If window does not exist yet, create it. This is only called
  13399. when a window is already in use, or when output has been written during this
  13400. inflate call, but the end of the deflate stream has not been reached yet.
  13401. It is also called to create a window for dictionary data when a dictionary
  13402. is loaded.
  13403. Providing output buffers larger than 32K to inflate() should provide a speed
  13404. advantage, since only the last 32K of output is copied to the sliding window
  13405. upon return from inflate(), and since all distances after the first 32K of
  13406. output will fall in the output data, making match copies simpler and faster.
  13407. The advantage may be dependent on the size of the processor's data caches.
  13408. */
  13409. function updatewindow(strm, src, end, copy) {
  13410. var dist;
  13411. var state = strm.state;
  13412. /* if it hasn't been done already, allocate space for the window */
  13413. if (state.window === null) {
  13414. state.wsize = 1 << state.wbits;
  13415. state.wnext = 0;
  13416. state.whave = 0;
  13417. state.window = new utils.Buf8(state.wsize);
  13418. }
  13419. /* copy state->wsize or less output bytes into the circular window */
  13420. if (copy >= state.wsize) {
  13421. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  13422. state.wnext = 0;
  13423. state.whave = state.wsize;
  13424. }
  13425. else {
  13426. dist = state.wsize - state.wnext;
  13427. if (dist > copy) {
  13428. dist = copy;
  13429. }
  13430. //zmemcpy(state->window + state->wnext, end - copy, dist);
  13431. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  13432. copy -= dist;
  13433. if (copy) {
  13434. //zmemcpy(state->window, end - copy, copy);
  13435. utils.arraySet(state.window,src, end - copy, copy, 0);
  13436. state.wnext = copy;
  13437. state.whave = state.wsize;
  13438. }
  13439. else {
  13440. state.wnext += dist;
  13441. if (state.wnext === state.wsize) { state.wnext = 0; }
  13442. if (state.whave < state.wsize) { state.whave += dist; }
  13443. }
  13444. }
  13445. return 0;
  13446. }
  13447. function inflate(strm, flush) {
  13448. var state;
  13449. var input, output; // input/output buffers
  13450. var next; /* next input INDEX */
  13451. var put; /* next output INDEX */
  13452. var have, left; /* available input and output */
  13453. var hold; /* bit buffer */
  13454. var bits; /* bits in bit buffer */
  13455. var _in, _out; /* save starting available input and output */
  13456. var copy; /* number of stored or match bytes to copy */
  13457. var from; /* where to copy match bytes from */
  13458. var from_source;
  13459. var here = 0; /* current decoding table entry */
  13460. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  13461. //var last; /* parent table entry */
  13462. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  13463. var len; /* length to copy for repeats, bits to drop */
  13464. var ret; /* return code */
  13465. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  13466. var opts;
  13467. var n; // temporary var for NEED_BITS
  13468. var order = /* permutation of code lengths */
  13469. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  13470. if (!strm || !strm.state || !strm.output ||
  13471. (!strm.input && strm.avail_in !== 0)) {
  13472. return Z_STREAM_ERROR;
  13473. }
  13474. state = strm.state;
  13475. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  13476. //--- LOAD() ---
  13477. put = strm.next_out;
  13478. output = strm.output;
  13479. left = strm.avail_out;
  13480. next = strm.next_in;
  13481. input = strm.input;
  13482. have = strm.avail_in;
  13483. hold = state.hold;
  13484. bits = state.bits;
  13485. //---
  13486. _in = have;
  13487. _out = left;
  13488. ret = Z_OK;
  13489. inf_leave: // goto emulation
  13490. for (;;) {
  13491. switch (state.mode) {
  13492. case HEAD:
  13493. if (state.wrap === 0) {
  13494. state.mode = TYPEDO;
  13495. break;
  13496. }
  13497. //=== NEEDBITS(16);
  13498. while (bits < 16) {
  13499. if (have === 0) { break inf_leave; }
  13500. have--;
  13501. hold += input[next++] << bits;
  13502. bits += 8;
  13503. }
  13504. //===//
  13505. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  13506. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  13507. //=== CRC2(state.check, hold);
  13508. hbuf[0] = hold & 0xff;
  13509. hbuf[1] = (hold >>> 8) & 0xff;
  13510. state.check = crc32(state.check, hbuf, 2, 0);
  13511. //===//
  13512. //=== INITBITS();
  13513. hold = 0;
  13514. bits = 0;
  13515. //===//
  13516. state.mode = FLAGS;
  13517. break;
  13518. }
  13519. state.flags = 0; /* expect zlib header */
  13520. if (state.head) {
  13521. state.head.done = false;
  13522. }
  13523. if (!(state.wrap & 1) || /* check if zlib header allowed */
  13524. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  13525. strm.msg = 'incorrect header check';
  13526. state.mode = BAD;
  13527. break;
  13528. }
  13529. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  13530. strm.msg = 'unknown compression method';
  13531. state.mode = BAD;
  13532. break;
  13533. }
  13534. //--- DROPBITS(4) ---//
  13535. hold >>>= 4;
  13536. bits -= 4;
  13537. //---//
  13538. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  13539. if (state.wbits === 0) {
  13540. state.wbits = len;
  13541. }
  13542. else if (len > state.wbits) {
  13543. strm.msg = 'invalid window size';
  13544. state.mode = BAD;
  13545. break;
  13546. }
  13547. state.dmax = 1 << len;
  13548. //Tracev((stderr, "inflate: zlib header ok\n"));
  13549. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  13550. state.mode = hold & 0x200 ? DICTID : TYPE;
  13551. //=== INITBITS();
  13552. hold = 0;
  13553. bits = 0;
  13554. //===//
  13555. break;
  13556. case FLAGS:
  13557. //=== NEEDBITS(16); */
  13558. while (bits < 16) {
  13559. if (have === 0) { break inf_leave; }
  13560. have--;
  13561. hold += input[next++] << bits;
  13562. bits += 8;
  13563. }
  13564. //===//
  13565. state.flags = hold;
  13566. if ((state.flags & 0xff) !== Z_DEFLATED) {
  13567. strm.msg = 'unknown compression method';
  13568. state.mode = BAD;
  13569. break;
  13570. }
  13571. if (state.flags & 0xe000) {
  13572. strm.msg = 'unknown header flags set';
  13573. state.mode = BAD;
  13574. break;
  13575. }
  13576. if (state.head) {
  13577. state.head.text = ((hold >> 8) & 1);
  13578. }
  13579. if (state.flags & 0x0200) {
  13580. //=== CRC2(state.check, hold);
  13581. hbuf[0] = hold & 0xff;
  13582. hbuf[1] = (hold >>> 8) & 0xff;
  13583. state.check = crc32(state.check, hbuf, 2, 0);
  13584. //===//
  13585. }
  13586. //=== INITBITS();
  13587. hold = 0;
  13588. bits = 0;
  13589. //===//
  13590. state.mode = TIME;
  13591. /* falls through */
  13592. case TIME:
  13593. //=== NEEDBITS(32); */
  13594. while (bits < 32) {
  13595. if (have === 0) { break inf_leave; }
  13596. have--;
  13597. hold += input[next++] << bits;
  13598. bits += 8;
  13599. }
  13600. //===//
  13601. if (state.head) {
  13602. state.head.time = hold;
  13603. }
  13604. if (state.flags & 0x0200) {
  13605. //=== CRC4(state.check, hold)
  13606. hbuf[0] = hold & 0xff;
  13607. hbuf[1] = (hold >>> 8) & 0xff;
  13608. hbuf[2] = (hold >>> 16) & 0xff;
  13609. hbuf[3] = (hold >>> 24) & 0xff;
  13610. state.check = crc32(state.check, hbuf, 4, 0);
  13611. //===
  13612. }
  13613. //=== INITBITS();
  13614. hold = 0;
  13615. bits = 0;
  13616. //===//
  13617. state.mode = OS;
  13618. /* falls through */
  13619. case OS:
  13620. //=== NEEDBITS(16); */
  13621. while (bits < 16) {
  13622. if (have === 0) { break inf_leave; }
  13623. have--;
  13624. hold += input[next++] << bits;
  13625. bits += 8;
  13626. }
  13627. //===//
  13628. if (state.head) {
  13629. state.head.xflags = (hold & 0xff);
  13630. state.head.os = (hold >> 8);
  13631. }
  13632. if (state.flags & 0x0200) {
  13633. //=== CRC2(state.check, hold);
  13634. hbuf[0] = hold & 0xff;
  13635. hbuf[1] = (hold >>> 8) & 0xff;
  13636. state.check = crc32(state.check, hbuf, 2, 0);
  13637. //===//
  13638. }
  13639. //=== INITBITS();
  13640. hold = 0;
  13641. bits = 0;
  13642. //===//
  13643. state.mode = EXLEN;
  13644. /* falls through */
  13645. case EXLEN:
  13646. if (state.flags & 0x0400) {
  13647. //=== NEEDBITS(16); */
  13648. while (bits < 16) {
  13649. if (have === 0) { break inf_leave; }
  13650. have--;
  13651. hold += input[next++] << bits;
  13652. bits += 8;
  13653. }
  13654. //===//
  13655. state.length = hold;
  13656. if (state.head) {
  13657. state.head.extra_len = hold;
  13658. }
  13659. if (state.flags & 0x0200) {
  13660. //=== CRC2(state.check, hold);
  13661. hbuf[0] = hold & 0xff;
  13662. hbuf[1] = (hold >>> 8) & 0xff;
  13663. state.check = crc32(state.check, hbuf, 2, 0);
  13664. //===//
  13665. }
  13666. //=== INITBITS();
  13667. hold = 0;
  13668. bits = 0;
  13669. //===//
  13670. }
  13671. else if (state.head) {
  13672. state.head.extra = null/*Z_NULL*/;
  13673. }
  13674. state.mode = EXTRA;
  13675. /* falls through */
  13676. case EXTRA:
  13677. if (state.flags & 0x0400) {
  13678. copy = state.length;
  13679. if (copy > have) { copy = have; }
  13680. if (copy) {
  13681. if (state.head) {
  13682. len = state.head.extra_len - state.length;
  13683. if (!state.head.extra) {
  13684. // Use untyped array for more conveniend processing later
  13685. state.head.extra = new Array(state.head.extra_len);
  13686. }
  13687. utils.arraySet(
  13688. state.head.extra,
  13689. input,
  13690. next,
  13691. // extra field is limited to 65536 bytes
  13692. // - no need for additional size check
  13693. copy,
  13694. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  13695. len
  13696. );
  13697. //zmemcpy(state.head.extra + len, next,
  13698. // len + copy > state.head.extra_max ?
  13699. // state.head.extra_max - len : copy);
  13700. }
  13701. if (state.flags & 0x0200) {
  13702. state.check = crc32(state.check, input, copy, next);
  13703. }
  13704. have -= copy;
  13705. next += copy;
  13706. state.length -= copy;
  13707. }
  13708. if (state.length) { break inf_leave; }
  13709. }
  13710. state.length = 0;
  13711. state.mode = NAME;
  13712. /* falls through */
  13713. case NAME:
  13714. if (state.flags & 0x0800) {
  13715. if (have === 0) { break inf_leave; }
  13716. copy = 0;
  13717. do {
  13718. // TODO: 2 or 1 bytes?
  13719. len = input[next + copy++];
  13720. /* use constant limit because in js we should not preallocate memory */
  13721. if (state.head && len &&
  13722. (state.length < 65536 /*state.head.name_max*/)) {
  13723. state.head.name += String.fromCharCode(len);
  13724. }
  13725. } while (len && copy < have);
  13726. if (state.flags & 0x0200) {
  13727. state.check = crc32(state.check, input, copy, next);
  13728. }
  13729. have -= copy;
  13730. next += copy;
  13731. if (len) { break inf_leave; }
  13732. }
  13733. else if (state.head) {
  13734. state.head.name = null;
  13735. }
  13736. state.length = 0;
  13737. state.mode = COMMENT;
  13738. /* falls through */
  13739. case COMMENT:
  13740. if (state.flags & 0x1000) {
  13741. if (have === 0) { break inf_leave; }
  13742. copy = 0;
  13743. do {
  13744. len = input[next + copy++];
  13745. /* use constant limit because in js we should not preallocate memory */
  13746. if (state.head && len &&
  13747. (state.length < 65536 /*state.head.comm_max*/)) {
  13748. state.head.comment += String.fromCharCode(len);
  13749. }
  13750. } while (len && copy < have);
  13751. if (state.flags & 0x0200) {
  13752. state.check = crc32(state.check, input, copy, next);
  13753. }
  13754. have -= copy;
  13755. next += copy;
  13756. if (len) { break inf_leave; }
  13757. }
  13758. else if (state.head) {
  13759. state.head.comment = null;
  13760. }
  13761. state.mode = HCRC;
  13762. /* falls through */
  13763. case HCRC:
  13764. if (state.flags & 0x0200) {
  13765. //=== NEEDBITS(16); */
  13766. while (bits < 16) {
  13767. if (have === 0) { break inf_leave; }
  13768. have--;
  13769. hold += input[next++] << bits;
  13770. bits += 8;
  13771. }
  13772. //===//
  13773. if (hold !== (state.check & 0xffff)) {
  13774. strm.msg = 'header crc mismatch';
  13775. state.mode = BAD;
  13776. break;
  13777. }
  13778. //=== INITBITS();
  13779. hold = 0;
  13780. bits = 0;
  13781. //===//
  13782. }
  13783. if (state.head) {
  13784. state.head.hcrc = ((state.flags >> 9) & 1);
  13785. state.head.done = true;
  13786. }
  13787. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  13788. state.mode = TYPE;
  13789. break;
  13790. case DICTID:
  13791. //=== NEEDBITS(32); */
  13792. while (bits < 32) {
  13793. if (have === 0) { break inf_leave; }
  13794. have--;
  13795. hold += input[next++] << bits;
  13796. bits += 8;
  13797. }
  13798. //===//
  13799. strm.adler = state.check = ZSWAP32(hold);
  13800. //=== INITBITS();
  13801. hold = 0;
  13802. bits = 0;
  13803. //===//
  13804. state.mode = DICT;
  13805. /* falls through */
  13806. case DICT:
  13807. if (state.havedict === 0) {
  13808. //--- RESTORE() ---
  13809. strm.next_out = put;
  13810. strm.avail_out = left;
  13811. strm.next_in = next;
  13812. strm.avail_in = have;
  13813. state.hold = hold;
  13814. state.bits = bits;
  13815. //---
  13816. return Z_NEED_DICT;
  13817. }
  13818. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  13819. state.mode = TYPE;
  13820. /* falls through */
  13821. case TYPE:
  13822. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  13823. /* falls through */
  13824. case TYPEDO:
  13825. if (state.last) {
  13826. //--- BYTEBITS() ---//
  13827. hold >>>= bits & 7;
  13828. bits -= bits & 7;
  13829. //---//
  13830. state.mode = CHECK;
  13831. break;
  13832. }
  13833. //=== NEEDBITS(3); */
  13834. while (bits < 3) {
  13835. if (have === 0) { break inf_leave; }
  13836. have--;
  13837. hold += input[next++] << bits;
  13838. bits += 8;
  13839. }
  13840. //===//
  13841. state.last = (hold & 0x01)/*BITS(1)*/;
  13842. //--- DROPBITS(1) ---//
  13843. hold >>>= 1;
  13844. bits -= 1;
  13845. //---//
  13846. switch ((hold & 0x03)/*BITS(2)*/) {
  13847. case 0: /* stored block */
  13848. //Tracev((stderr, "inflate: stored block%s\n",
  13849. // state.last ? " (last)" : ""));
  13850. state.mode = STORED;
  13851. break;
  13852. case 1: /* fixed block */
  13853. fixedtables(state);
  13854. //Tracev((stderr, "inflate: fixed codes block%s\n",
  13855. // state.last ? " (last)" : ""));
  13856. state.mode = LEN_; /* decode codes */
  13857. if (flush === Z_TREES) {
  13858. //--- DROPBITS(2) ---//
  13859. hold >>>= 2;
  13860. bits -= 2;
  13861. //---//
  13862. break inf_leave;
  13863. }
  13864. break;
  13865. case 2: /* dynamic block */
  13866. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  13867. // state.last ? " (last)" : ""));
  13868. state.mode = TABLE;
  13869. break;
  13870. case 3:
  13871. strm.msg = 'invalid block type';
  13872. state.mode = BAD;
  13873. }
  13874. //--- DROPBITS(2) ---//
  13875. hold >>>= 2;
  13876. bits -= 2;
  13877. //---//
  13878. break;
  13879. case STORED:
  13880. //--- BYTEBITS() ---// /* go to byte boundary */
  13881. hold >>>= bits & 7;
  13882. bits -= bits & 7;
  13883. //---//
  13884. //=== NEEDBITS(32); */
  13885. while (bits < 32) {
  13886. if (have === 0) { break inf_leave; }
  13887. have--;
  13888. hold += input[next++] << bits;
  13889. bits += 8;
  13890. }
  13891. //===//
  13892. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  13893. strm.msg = 'invalid stored block lengths';
  13894. state.mode = BAD;
  13895. break;
  13896. }
  13897. state.length = hold & 0xffff;
  13898. //Tracev((stderr, "inflate: stored length %u\n",
  13899. // state.length));
  13900. //=== INITBITS();
  13901. hold = 0;
  13902. bits = 0;
  13903. //===//
  13904. state.mode = COPY_;
  13905. if (flush === Z_TREES) { break inf_leave; }
  13906. /* falls through */
  13907. case COPY_:
  13908. state.mode = COPY;
  13909. /* falls through */
  13910. case COPY:
  13911. copy = state.length;
  13912. if (copy) {
  13913. if (copy > have) { copy = have; }
  13914. if (copy > left) { copy = left; }
  13915. if (copy === 0) { break inf_leave; }
  13916. //--- zmemcpy(put, next, copy); ---
  13917. utils.arraySet(output, input, next, copy, put);
  13918. //---//
  13919. have -= copy;
  13920. next += copy;
  13921. left -= copy;
  13922. put += copy;
  13923. state.length -= copy;
  13924. break;
  13925. }
  13926. //Tracev((stderr, "inflate: stored end\n"));
  13927. state.mode = TYPE;
  13928. break;
  13929. case TABLE:
  13930. //=== NEEDBITS(14); */
  13931. while (bits < 14) {
  13932. if (have === 0) { break inf_leave; }
  13933. have--;
  13934. hold += input[next++] << bits;
  13935. bits += 8;
  13936. }
  13937. //===//
  13938. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  13939. //--- DROPBITS(5) ---//
  13940. hold >>>= 5;
  13941. bits -= 5;
  13942. //---//
  13943. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  13944. //--- DROPBITS(5) ---//
  13945. hold >>>= 5;
  13946. bits -= 5;
  13947. //---//
  13948. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  13949. //--- DROPBITS(4) ---//
  13950. hold >>>= 4;
  13951. bits -= 4;
  13952. //---//
  13953. //#ifndef PKZIP_BUG_WORKAROUND
  13954. if (state.nlen > 286 || state.ndist > 30) {
  13955. strm.msg = 'too many length or distance symbols';
  13956. state.mode = BAD;
  13957. break;
  13958. }
  13959. //#endif
  13960. //Tracev((stderr, "inflate: table sizes ok\n"));
  13961. state.have = 0;
  13962. state.mode = LENLENS;
  13963. /* falls through */
  13964. case LENLENS:
  13965. while (state.have < state.ncode) {
  13966. //=== NEEDBITS(3);
  13967. while (bits < 3) {
  13968. if (have === 0) { break inf_leave; }
  13969. have--;
  13970. hold += input[next++] << bits;
  13971. bits += 8;
  13972. }
  13973. //===//
  13974. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  13975. //--- DROPBITS(3) ---//
  13976. hold >>>= 3;
  13977. bits -= 3;
  13978. //---//
  13979. }
  13980. while (state.have < 19) {
  13981. state.lens[order[state.have++]] = 0;
  13982. }
  13983. // We have separate tables & no pointers. 2 commented lines below not needed.
  13984. //state.next = state.codes;
  13985. //state.lencode = state.next;
  13986. // Switch to use dynamic table
  13987. state.lencode = state.lendyn;
  13988. state.lenbits = 7;
  13989. opts = {bits: state.lenbits};
  13990. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  13991. state.lenbits = opts.bits;
  13992. if (ret) {
  13993. strm.msg = 'invalid code lengths set';
  13994. state.mode = BAD;
  13995. break;
  13996. }
  13997. //Tracev((stderr, "inflate: code lengths ok\n"));
  13998. state.have = 0;
  13999. state.mode = CODELENS;
  14000. /* falls through */
  14001. case CODELENS:
  14002. while (state.have < state.nlen + state.ndist) {
  14003. for (;;) {
  14004. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  14005. here_bits = here >>> 24;
  14006. here_op = (here >>> 16) & 0xff;
  14007. here_val = here & 0xffff;
  14008. if ((here_bits) <= bits) { break; }
  14009. //--- PULLBYTE() ---//
  14010. if (have === 0) { break inf_leave; }
  14011. have--;
  14012. hold += input[next++] << bits;
  14013. bits += 8;
  14014. //---//
  14015. }
  14016. if (here_val < 16) {
  14017. //--- DROPBITS(here.bits) ---//
  14018. hold >>>= here_bits;
  14019. bits -= here_bits;
  14020. //---//
  14021. state.lens[state.have++] = here_val;
  14022. }
  14023. else {
  14024. if (here_val === 16) {
  14025. //=== NEEDBITS(here.bits + 2);
  14026. n = here_bits + 2;
  14027. while (bits < n) {
  14028. if (have === 0) { break inf_leave; }
  14029. have--;
  14030. hold += input[next++] << bits;
  14031. bits += 8;
  14032. }
  14033. //===//
  14034. //--- DROPBITS(here.bits) ---//
  14035. hold >>>= here_bits;
  14036. bits -= here_bits;
  14037. //---//
  14038. if (state.have === 0) {
  14039. strm.msg = 'invalid bit length repeat';
  14040. state.mode = BAD;
  14041. break;
  14042. }
  14043. len = state.lens[state.have - 1];
  14044. copy = 3 + (hold & 0x03);//BITS(2);
  14045. //--- DROPBITS(2) ---//
  14046. hold >>>= 2;
  14047. bits -= 2;
  14048. //---//
  14049. }
  14050. else if (here_val === 17) {
  14051. //=== NEEDBITS(here.bits + 3);
  14052. n = here_bits + 3;
  14053. while (bits < n) {
  14054. if (have === 0) { break inf_leave; }
  14055. have--;
  14056. hold += input[next++] << bits;
  14057. bits += 8;
  14058. }
  14059. //===//
  14060. //--- DROPBITS(here.bits) ---//
  14061. hold >>>= here_bits;
  14062. bits -= here_bits;
  14063. //---//
  14064. len = 0;
  14065. copy = 3 + (hold & 0x07);//BITS(3);
  14066. //--- DROPBITS(3) ---//
  14067. hold >>>= 3;
  14068. bits -= 3;
  14069. //---//
  14070. }
  14071. else {
  14072. //=== NEEDBITS(here.bits + 7);
  14073. n = here_bits + 7;
  14074. while (bits < n) {
  14075. if (have === 0) { break inf_leave; }
  14076. have--;
  14077. hold += input[next++] << bits;
  14078. bits += 8;
  14079. }
  14080. //===//
  14081. //--- DROPBITS(here.bits) ---//
  14082. hold >>>= here_bits;
  14083. bits -= here_bits;
  14084. //---//
  14085. len = 0;
  14086. copy = 11 + (hold & 0x7f);//BITS(7);
  14087. //--- DROPBITS(7) ---//
  14088. hold >>>= 7;
  14089. bits -= 7;
  14090. //---//
  14091. }
  14092. if (state.have + copy > state.nlen + state.ndist) {
  14093. strm.msg = 'invalid bit length repeat';
  14094. state.mode = BAD;
  14095. break;
  14096. }
  14097. while (copy--) {
  14098. state.lens[state.have++] = len;
  14099. }
  14100. }
  14101. }
  14102. /* handle error breaks in while */
  14103. if (state.mode === BAD) { break; }
  14104. /* check for end-of-block code (better have one) */
  14105. if (state.lens[256] === 0) {
  14106. strm.msg = 'invalid code -- missing end-of-block';
  14107. state.mode = BAD;
  14108. break;
  14109. }
  14110. /* build code tables -- note: do not change the lenbits or distbits
  14111. values here (9 and 6) without reading the comments in inftrees.h
  14112. concerning the ENOUGH constants, which depend on those values */
  14113. state.lenbits = 9;
  14114. opts = {bits: state.lenbits};
  14115. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  14116. // We have separate tables & no pointers. 2 commented lines below not needed.
  14117. // state.next_index = opts.table_index;
  14118. state.lenbits = opts.bits;
  14119. // state.lencode = state.next;
  14120. if (ret) {
  14121. strm.msg = 'invalid literal/lengths set';
  14122. state.mode = BAD;
  14123. break;
  14124. }
  14125. state.distbits = 6;
  14126. //state.distcode.copy(state.codes);
  14127. // Switch to use dynamic table
  14128. state.distcode = state.distdyn;
  14129. opts = {bits: state.distbits};
  14130. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  14131. // We have separate tables & no pointers. 2 commented lines below not needed.
  14132. // state.next_index = opts.table_index;
  14133. state.distbits = opts.bits;
  14134. // state.distcode = state.next;
  14135. if (ret) {
  14136. strm.msg = 'invalid distances set';
  14137. state.mode = BAD;
  14138. break;
  14139. }
  14140. //Tracev((stderr, 'inflate: codes ok\n'));
  14141. state.mode = LEN_;
  14142. if (flush === Z_TREES) { break inf_leave; }
  14143. /* falls through */
  14144. case LEN_:
  14145. state.mode = LEN;
  14146. /* falls through */
  14147. case LEN:
  14148. if (have >= 6 && left >= 258) {
  14149. //--- RESTORE() ---
  14150. strm.next_out = put;
  14151. strm.avail_out = left;
  14152. strm.next_in = next;
  14153. strm.avail_in = have;
  14154. state.hold = hold;
  14155. state.bits = bits;
  14156. //---
  14157. inflate_fast(strm, _out);
  14158. //--- LOAD() ---
  14159. put = strm.next_out;
  14160. output = strm.output;
  14161. left = strm.avail_out;
  14162. next = strm.next_in;
  14163. input = strm.input;
  14164. have = strm.avail_in;
  14165. hold = state.hold;
  14166. bits = state.bits;
  14167. //---
  14168. if (state.mode === TYPE) {
  14169. state.back = -1;
  14170. }
  14171. break;
  14172. }
  14173. state.back = 0;
  14174. for (;;) {
  14175. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  14176. here_bits = here >>> 24;
  14177. here_op = (here >>> 16) & 0xff;
  14178. here_val = here & 0xffff;
  14179. if (here_bits <= bits) { break; }
  14180. //--- PULLBYTE() ---//
  14181. if (have === 0) { break inf_leave; }
  14182. have--;
  14183. hold += input[next++] << bits;
  14184. bits += 8;
  14185. //---//
  14186. }
  14187. if (here_op && (here_op & 0xf0) === 0) {
  14188. last_bits = here_bits;
  14189. last_op = here_op;
  14190. last_val = here_val;
  14191. for (;;) {
  14192. here = state.lencode[last_val +
  14193. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  14194. here_bits = here >>> 24;
  14195. here_op = (here >>> 16) & 0xff;
  14196. here_val = here & 0xffff;
  14197. if ((last_bits + here_bits) <= bits) { break; }
  14198. //--- PULLBYTE() ---//
  14199. if (have === 0) { break inf_leave; }
  14200. have--;
  14201. hold += input[next++] << bits;
  14202. bits += 8;
  14203. //---//
  14204. }
  14205. //--- DROPBITS(last.bits) ---//
  14206. hold >>>= last_bits;
  14207. bits -= last_bits;
  14208. //---//
  14209. state.back += last_bits;
  14210. }
  14211. //--- DROPBITS(here.bits) ---//
  14212. hold >>>= here_bits;
  14213. bits -= here_bits;
  14214. //---//
  14215. state.back += here_bits;
  14216. state.length = here_val;
  14217. if (here_op === 0) {
  14218. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  14219. // "inflate: literal '%c'\n" :
  14220. // "inflate: literal 0x%02x\n", here.val));
  14221. state.mode = LIT;
  14222. break;
  14223. }
  14224. if (here_op & 32) {
  14225. //Tracevv((stderr, "inflate: end of block\n"));
  14226. state.back = -1;
  14227. state.mode = TYPE;
  14228. break;
  14229. }
  14230. if (here_op & 64) {
  14231. strm.msg = 'invalid literal/length code';
  14232. state.mode = BAD;
  14233. break;
  14234. }
  14235. state.extra = here_op & 15;
  14236. state.mode = LENEXT;
  14237. /* falls through */
  14238. case LENEXT:
  14239. if (state.extra) {
  14240. //=== NEEDBITS(state.extra);
  14241. n = state.extra;
  14242. while (bits < n) {
  14243. if (have === 0) { break inf_leave; }
  14244. have--;
  14245. hold += input[next++] << bits;
  14246. bits += 8;
  14247. }
  14248. //===//
  14249. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  14250. //--- DROPBITS(state.extra) ---//
  14251. hold >>>= state.extra;
  14252. bits -= state.extra;
  14253. //---//
  14254. state.back += state.extra;
  14255. }
  14256. //Tracevv((stderr, "inflate: length %u\n", state.length));
  14257. state.was = state.length;
  14258. state.mode = DIST;
  14259. /* falls through */
  14260. case DIST:
  14261. for (;;) {
  14262. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  14263. here_bits = here >>> 24;
  14264. here_op = (here >>> 16) & 0xff;
  14265. here_val = here & 0xffff;
  14266. if ((here_bits) <= bits) { break; }
  14267. //--- PULLBYTE() ---//
  14268. if (have === 0) { break inf_leave; }
  14269. have--;
  14270. hold += input[next++] << bits;
  14271. bits += 8;
  14272. //---//
  14273. }
  14274. if ((here_op & 0xf0) === 0) {
  14275. last_bits = here_bits;
  14276. last_op = here_op;
  14277. last_val = here_val;
  14278. for (;;) {
  14279. here = state.distcode[last_val +
  14280. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  14281. here_bits = here >>> 24;
  14282. here_op = (here >>> 16) & 0xff;
  14283. here_val = here & 0xffff;
  14284. if ((last_bits + here_bits) <= bits) { break; }
  14285. //--- PULLBYTE() ---//
  14286. if (have === 0) { break inf_leave; }
  14287. have--;
  14288. hold += input[next++] << bits;
  14289. bits += 8;
  14290. //---//
  14291. }
  14292. //--- DROPBITS(last.bits) ---//
  14293. hold >>>= last_bits;
  14294. bits -= last_bits;
  14295. //---//
  14296. state.back += last_bits;
  14297. }
  14298. //--- DROPBITS(here.bits) ---//
  14299. hold >>>= here_bits;
  14300. bits -= here_bits;
  14301. //---//
  14302. state.back += here_bits;
  14303. if (here_op & 64) {
  14304. strm.msg = 'invalid distance code';
  14305. state.mode = BAD;
  14306. break;
  14307. }
  14308. state.offset = here_val;
  14309. state.extra = (here_op) & 15;
  14310. state.mode = DISTEXT;
  14311. /* falls through */
  14312. case DISTEXT:
  14313. if (state.extra) {
  14314. //=== NEEDBITS(state.extra);
  14315. n = state.extra;
  14316. while (bits < n) {
  14317. if (have === 0) { break inf_leave; }
  14318. have--;
  14319. hold += input[next++] << bits;
  14320. bits += 8;
  14321. }
  14322. //===//
  14323. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  14324. //--- DROPBITS(state.extra) ---//
  14325. hold >>>= state.extra;
  14326. bits -= state.extra;
  14327. //---//
  14328. state.back += state.extra;
  14329. }
  14330. //#ifdef INFLATE_STRICT
  14331. if (state.offset > state.dmax) {
  14332. strm.msg = 'invalid distance too far back';
  14333. state.mode = BAD;
  14334. break;
  14335. }
  14336. //#endif
  14337. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  14338. state.mode = MATCH;
  14339. /* falls through */
  14340. case MATCH:
  14341. if (left === 0) { break inf_leave; }
  14342. copy = _out - left;
  14343. if (state.offset > copy) { /* copy from window */
  14344. copy = state.offset - copy;
  14345. if (copy > state.whave) {
  14346. if (state.sane) {
  14347. strm.msg = 'invalid distance too far back';
  14348. state.mode = BAD;
  14349. break;
  14350. }
  14351. // (!) This block is disabled in zlib defailts,
  14352. // don't enable it for binary compatibility
  14353. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  14354. // Trace((stderr, "inflate.c too far\n"));
  14355. // copy -= state.whave;
  14356. // if (copy > state.length) { copy = state.length; }
  14357. // if (copy > left) { copy = left; }
  14358. // left -= copy;
  14359. // state.length -= copy;
  14360. // do {
  14361. // output[put++] = 0;
  14362. // } while (--copy);
  14363. // if (state.length === 0) { state.mode = LEN; }
  14364. // break;
  14365. //#endif
  14366. }
  14367. if (copy > state.wnext) {
  14368. copy -= state.wnext;
  14369. from = state.wsize - copy;
  14370. }
  14371. else {
  14372. from = state.wnext - copy;
  14373. }
  14374. if (copy > state.length) { copy = state.length; }
  14375. from_source = state.window;
  14376. }
  14377. else { /* copy from output */
  14378. from_source = output;
  14379. from = put - state.offset;
  14380. copy = state.length;
  14381. }
  14382. if (copy > left) { copy = left; }
  14383. left -= copy;
  14384. state.length -= copy;
  14385. do {
  14386. output[put++] = from_source[from++];
  14387. } while (--copy);
  14388. if (state.length === 0) { state.mode = LEN; }
  14389. break;
  14390. case LIT:
  14391. if (left === 0) { break inf_leave; }
  14392. output[put++] = state.length;
  14393. left--;
  14394. state.mode = LEN;
  14395. break;
  14396. case CHECK:
  14397. if (state.wrap) {
  14398. //=== NEEDBITS(32);
  14399. while (bits < 32) {
  14400. if (have === 0) { break inf_leave; }
  14401. have--;
  14402. // Use '|' insdead of '+' to make sure that result is signed
  14403. hold |= input[next++] << bits;
  14404. bits += 8;
  14405. }
  14406. //===//
  14407. _out -= left;
  14408. strm.total_out += _out;
  14409. state.total += _out;
  14410. if (_out) {
  14411. strm.adler = state.check =
  14412. /*UPDATE(state.check, put - _out, _out);*/
  14413. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  14414. }
  14415. _out = left;
  14416. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  14417. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  14418. strm.msg = 'incorrect data check';
  14419. state.mode = BAD;
  14420. break;
  14421. }
  14422. //=== INITBITS();
  14423. hold = 0;
  14424. bits = 0;
  14425. //===//
  14426. //Tracev((stderr, "inflate: check matches trailer\n"));
  14427. }
  14428. state.mode = LENGTH;
  14429. /* falls through */
  14430. case LENGTH:
  14431. if (state.wrap && state.flags) {
  14432. //=== NEEDBITS(32);
  14433. while (bits < 32) {
  14434. if (have === 0) { break inf_leave; }
  14435. have--;
  14436. hold += input[next++] << bits;
  14437. bits += 8;
  14438. }
  14439. //===//
  14440. if (hold !== (state.total & 0xffffffff)) {
  14441. strm.msg = 'incorrect length check';
  14442. state.mode = BAD;
  14443. break;
  14444. }
  14445. //=== INITBITS();
  14446. hold = 0;
  14447. bits = 0;
  14448. //===//
  14449. //Tracev((stderr, "inflate: length matches trailer\n"));
  14450. }
  14451. state.mode = DONE;
  14452. /* falls through */
  14453. case DONE:
  14454. ret = Z_STREAM_END;
  14455. break inf_leave;
  14456. case BAD:
  14457. ret = Z_DATA_ERROR;
  14458. break inf_leave;
  14459. case MEM:
  14460. return Z_MEM_ERROR;
  14461. case SYNC:
  14462. /* falls through */
  14463. default:
  14464. return Z_STREAM_ERROR;
  14465. }
  14466. }
  14467. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  14468. /*
  14469. Return from inflate(), updating the total counts and the check value.
  14470. If there was no progress during the inflate() call, return a buffer
  14471. error. Call updatewindow() to create and/or update the window state.
  14472. Note: a memory error from inflate() is non-recoverable.
  14473. */
  14474. //--- RESTORE() ---
  14475. strm.next_out = put;
  14476. strm.avail_out = left;
  14477. strm.next_in = next;
  14478. strm.avail_in = have;
  14479. state.hold = hold;
  14480. state.bits = bits;
  14481. //---
  14482. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  14483. (state.mode < CHECK || flush !== Z_FINISH))) {
  14484. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  14485. state.mode = MEM;
  14486. return Z_MEM_ERROR;
  14487. }
  14488. }
  14489. _in -= strm.avail_in;
  14490. _out -= strm.avail_out;
  14491. strm.total_in += _in;
  14492. strm.total_out += _out;
  14493. state.total += _out;
  14494. if (state.wrap && _out) {
  14495. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  14496. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  14497. }
  14498. strm.data_type = state.bits + (state.last ? 64 : 0) +
  14499. (state.mode === TYPE ? 128 : 0) +
  14500. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  14501. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  14502. ret = Z_BUF_ERROR;
  14503. }
  14504. return ret;
  14505. }
  14506. function inflateEnd(strm) {
  14507. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  14508. return Z_STREAM_ERROR;
  14509. }
  14510. var state = strm.state;
  14511. if (state.window) {
  14512. state.window = null;
  14513. }
  14514. strm.state = null;
  14515. return Z_OK;
  14516. }
  14517. function inflateGetHeader(strm, head) {
  14518. var state;
  14519. /* check state */
  14520. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  14521. state = strm.state;
  14522. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  14523. /* save header structure */
  14524. state.head = head;
  14525. head.done = false;
  14526. return Z_OK;
  14527. }
  14528. exports.inflateReset = inflateReset;
  14529. exports.inflateReset2 = inflateReset2;
  14530. exports.inflateResetKeep = inflateResetKeep;
  14531. exports.inflateInit = inflateInit;
  14532. exports.inflateInit2 = inflateInit2;
  14533. exports.inflate = inflate;
  14534. exports.inflateEnd = inflateEnd;
  14535. exports.inflateGetHeader = inflateGetHeader;
  14536. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  14537. /* Not implemented
  14538. exports.inflateCopy = inflateCopy;
  14539. exports.inflateGetDictionary = inflateGetDictionary;
  14540. exports.inflateMark = inflateMark;
  14541. exports.inflatePrime = inflatePrime;
  14542. exports.inflateSetDictionary = inflateSetDictionary;
  14543. exports.inflateSync = inflateSync;
  14544. exports.inflateSyncPoint = inflateSyncPoint;
  14545. exports.inflateUndermine = inflateUndermine;
  14546. */
  14547. },{"../utils/common":39,"./adler32":41,"./crc32":43,"./inffast":46,"./inftrees":48}],48:[function(require,module,exports){
  14548. 'use strict';
  14549. var utils = require('../utils/common');
  14550. var MAXBITS = 15;
  14551. var ENOUGH_LENS = 852;
  14552. var ENOUGH_DISTS = 592;
  14553. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  14554. var CODES = 0;
  14555. var LENS = 1;
  14556. var DISTS = 2;
  14557. var lbase = [ /* Length codes 257..285 base */
  14558. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  14559. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  14560. ];
  14561. var lext = [ /* Length codes 257..285 extra */
  14562. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  14563. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  14564. ];
  14565. var dbase = [ /* Distance codes 0..29 base */
  14566. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  14567. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  14568. 8193, 12289, 16385, 24577, 0, 0
  14569. ];
  14570. var dext = [ /* Distance codes 0..29 extra */
  14571. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  14572. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  14573. 28, 28, 29, 29, 64, 64
  14574. ];
  14575. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  14576. {
  14577. var bits = opts.bits;
  14578. //here = opts.here; /* table entry for duplication */
  14579. var len = 0; /* a code's length in bits */
  14580. var sym = 0; /* index of code symbols */
  14581. var min = 0, max = 0; /* minimum and maximum code lengths */
  14582. var root = 0; /* number of index bits for root table */
  14583. var curr = 0; /* number of index bits for current table */
  14584. var drop = 0; /* code bits to drop for sub-table */
  14585. var left = 0; /* number of prefix codes available */
  14586. var used = 0; /* code entries in table used */
  14587. var huff = 0; /* Huffman code */
  14588. var incr; /* for incrementing code, index */
  14589. var fill; /* index for replicating entries */
  14590. var low; /* low bits for current root entry */
  14591. var mask; /* mask for low root bits */
  14592. var next; /* next available space in table */
  14593. var base = null; /* base value table to use */
  14594. var base_index = 0;
  14595. // var shoextra; /* extra bits table to use */
  14596. var end; /* use base and extra for symbol > end */
  14597. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  14598. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  14599. var extra = null;
  14600. var extra_index = 0;
  14601. var here_bits, here_op, here_val;
  14602. /*
  14603. Process a set of code lengths to create a canonical Huffman code. The
  14604. code lengths are lens[0..codes-1]. Each length corresponds to the
  14605. symbols 0..codes-1. The Huffman code is generated by first sorting the
  14606. symbols by length from short to long, and retaining the symbol order
  14607. for codes with equal lengths. Then the code starts with all zero bits
  14608. for the first code of the shortest length, and the codes are integer
  14609. increments for the same length, and zeros are appended as the length
  14610. increases. For the deflate format, these bits are stored backwards
  14611. from their more natural integer increment ordering, and so when the
  14612. decoding tables are built in the large loop below, the integer codes
  14613. are incremented backwards.
  14614. This routine assumes, but does not check, that all of the entries in
  14615. lens[] are in the range 0..MAXBITS. The caller must assure this.
  14616. 1..MAXBITS is interpreted as that code length. zero means that that
  14617. symbol does not occur in this code.
  14618. The codes are sorted by computing a count of codes for each length,
  14619. creating from that a table of starting indices for each length in the
  14620. sorted table, and then entering the symbols in order in the sorted
  14621. table. The sorted table is work[], with that space being provided by
  14622. the caller.
  14623. The length counts are used for other purposes as well, i.e. finding
  14624. the minimum and maximum length codes, determining if there are any
  14625. codes at all, checking for a valid set of lengths, and looking ahead
  14626. at length counts to determine sub-table sizes when building the
  14627. decoding tables.
  14628. */
  14629. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  14630. for (len = 0; len <= MAXBITS; len++) {
  14631. count[len] = 0;
  14632. }
  14633. for (sym = 0; sym < codes; sym++) {
  14634. count[lens[lens_index + sym]]++;
  14635. }
  14636. /* bound code lengths, force root to be within code lengths */
  14637. root = bits;
  14638. for (max = MAXBITS; max >= 1; max--) {
  14639. if (count[max] !== 0) { break; }
  14640. }
  14641. if (root > max) {
  14642. root = max;
  14643. }
  14644. if (max === 0) { /* no symbols to code at all */
  14645. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  14646. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  14647. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  14648. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  14649. //table.op[opts.table_index] = 64;
  14650. //table.bits[opts.table_index] = 1;
  14651. //table.val[opts.table_index++] = 0;
  14652. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  14653. opts.bits = 1;
  14654. return 0; /* no symbols, but wait for decoding to report error */
  14655. }
  14656. for (min = 1; min < max; min++) {
  14657. if (count[min] !== 0) { break; }
  14658. }
  14659. if (root < min) {
  14660. root = min;
  14661. }
  14662. /* check for an over-subscribed or incomplete set of lengths */
  14663. left = 1;
  14664. for (len = 1; len <= MAXBITS; len++) {
  14665. left <<= 1;
  14666. left -= count[len];
  14667. if (left < 0) {
  14668. return -1;
  14669. } /* over-subscribed */
  14670. }
  14671. if (left > 0 && (type === CODES || max !== 1)) {
  14672. return -1; /* incomplete set */
  14673. }
  14674. /* generate offsets into symbol table for each length for sorting */
  14675. offs[1] = 0;
  14676. for (len = 1; len < MAXBITS; len++) {
  14677. offs[len + 1] = offs[len] + count[len];
  14678. }
  14679. /* sort symbols by length, by symbol order within each length */
  14680. for (sym = 0; sym < codes; sym++) {
  14681. if (lens[lens_index + sym] !== 0) {
  14682. work[offs[lens[lens_index + sym]]++] = sym;
  14683. }
  14684. }
  14685. /*
  14686. Create and fill in decoding tables. In this loop, the table being
  14687. filled is at next and has curr index bits. The code being used is huff
  14688. with length len. That code is converted to an index by dropping drop
  14689. bits off of the bottom. For codes where len is less than drop + curr,
  14690. those top drop + curr - len bits are incremented through all values to
  14691. fill the table with replicated entries.
  14692. root is the number of index bits for the root table. When len exceeds
  14693. root, sub-tables are created pointed to by the root entry with an index
  14694. of the low root bits of huff. This is saved in low to check for when a
  14695. new sub-table should be started. drop is zero when the root table is
  14696. being filled, and drop is root when sub-tables are being filled.
  14697. When a new sub-table is needed, it is necessary to look ahead in the
  14698. code lengths to determine what size sub-table is needed. The length
  14699. counts are used for this, and so count[] is decremented as codes are
  14700. entered in the tables.
  14701. used keeps track of how many table entries have been allocated from the
  14702. provided *table space. It is checked for LENS and DIST tables against
  14703. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  14704. the initial root table size constants. See the comments in inftrees.h
  14705. for more information.
  14706. sym increments through all symbols, and the loop terminates when
  14707. all codes of length max, i.e. all codes, have been processed. This
  14708. routine permits incomplete codes, so another loop after this one fills
  14709. in the rest of the decoding tables with invalid code markers.
  14710. */
  14711. /* set up for code type */
  14712. // poor man optimization - use if-else instead of switch,
  14713. // to avoid deopts in old v8
  14714. if (type === CODES) {
  14715. base = extra = work; /* dummy value--not used */
  14716. end = 19;
  14717. } else if (type === LENS) {
  14718. base = lbase;
  14719. base_index -= 257;
  14720. extra = lext;
  14721. extra_index -= 257;
  14722. end = 256;
  14723. } else { /* DISTS */
  14724. base = dbase;
  14725. extra = dext;
  14726. end = -1;
  14727. }
  14728. /* initialize opts for loop */
  14729. huff = 0; /* starting code */
  14730. sym = 0; /* starting code symbol */
  14731. len = min; /* starting code length */
  14732. next = table_index; /* current table to fill in */
  14733. curr = root; /* current table index bits */
  14734. drop = 0; /* current bits to drop from code for index */
  14735. low = -1; /* trigger new sub-table when len > root */
  14736. used = 1 << root; /* use root table entries */
  14737. mask = used - 1; /* mask for comparing low */
  14738. /* check available table space */
  14739. if ((type === LENS && used > ENOUGH_LENS) ||
  14740. (type === DISTS && used > ENOUGH_DISTS)) {
  14741. return 1;
  14742. }
  14743. var i=0;
  14744. /* process all codes and make table entries */
  14745. for (;;) {
  14746. i++;
  14747. /* create table entry */
  14748. here_bits = len - drop;
  14749. if (work[sym] < end) {
  14750. here_op = 0;
  14751. here_val = work[sym];
  14752. }
  14753. else if (work[sym] > end) {
  14754. here_op = extra[extra_index + work[sym]];
  14755. here_val = base[base_index + work[sym]];
  14756. }
  14757. else {
  14758. here_op = 32 + 64; /* end of block */
  14759. here_val = 0;
  14760. }
  14761. /* replicate for those indices with low len bits equal to huff */
  14762. incr = 1 << (len - drop);
  14763. fill = 1 << curr;
  14764. min = fill; /* save offset to next table */
  14765. do {
  14766. fill -= incr;
  14767. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  14768. } while (fill !== 0);
  14769. /* backwards increment the len-bit code huff */
  14770. incr = 1 << (len - 1);
  14771. while (huff & incr) {
  14772. incr >>= 1;
  14773. }
  14774. if (incr !== 0) {
  14775. huff &= incr - 1;
  14776. huff += incr;
  14777. } else {
  14778. huff = 0;
  14779. }
  14780. /* go to next symbol, update count, len */
  14781. sym++;
  14782. if (--count[len] === 0) {
  14783. if (len === max) { break; }
  14784. len = lens[lens_index + work[sym]];
  14785. }
  14786. /* create new sub-table if needed */
  14787. if (len > root && (huff & mask) !== low) {
  14788. /* if first time, transition to sub-tables */
  14789. if (drop === 0) {
  14790. drop = root;
  14791. }
  14792. /* increment past last table */
  14793. next += min; /* here min is 1 << curr */
  14794. /* determine length of next table */
  14795. curr = len - drop;
  14796. left = 1 << curr;
  14797. while (curr + drop < max) {
  14798. left -= count[curr + drop];
  14799. if (left <= 0) { break; }
  14800. curr++;
  14801. left <<= 1;
  14802. }
  14803. /* check for enough space */
  14804. used += 1 << curr;
  14805. if ((type === LENS && used > ENOUGH_LENS) ||
  14806. (type === DISTS && used > ENOUGH_DISTS)) {
  14807. return 1;
  14808. }
  14809. /* point entry in root table to sub-table */
  14810. low = huff & mask;
  14811. /*table.op[low] = curr;
  14812. table.bits[low] = root;
  14813. table.val[low] = next - opts.table_index;*/
  14814. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  14815. }
  14816. }
  14817. /* fill in remaining table entry if code is incomplete (guaranteed to have
  14818. at most one remaining entry, since if the code is incomplete, the
  14819. maximum code length that was allowed to get this far is one bit) */
  14820. if (huff !== 0) {
  14821. //table.op[next + huff] = 64; /* invalid code marker */
  14822. //table.bits[next + huff] = len - drop;
  14823. //table.val[next + huff] = 0;
  14824. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  14825. }
  14826. /* set return parameters */
  14827. //opts.table_index += used;
  14828. opts.bits = root;
  14829. return 0;
  14830. };
  14831. },{"../utils/common":39}],49:[function(require,module,exports){
  14832. 'use strict';
  14833. module.exports = {
  14834. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  14835. '1': 'stream end', /* Z_STREAM_END 1 */
  14836. '0': '', /* Z_OK 0 */
  14837. '-1': 'file error', /* Z_ERRNO (-1) */
  14838. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  14839. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  14840. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  14841. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  14842. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  14843. };
  14844. },{}],50:[function(require,module,exports){
  14845. 'use strict';
  14846. var utils = require('../utils/common');
  14847. /* Public constants ==========================================================*/
  14848. /* ===========================================================================*/
  14849. //var Z_FILTERED = 1;
  14850. //var Z_HUFFMAN_ONLY = 2;
  14851. //var Z_RLE = 3;
  14852. var Z_FIXED = 4;
  14853. //var Z_DEFAULT_STRATEGY = 0;
  14854. /* Possible values of the data_type field (though see inflate()) */
  14855. var Z_BINARY = 0;
  14856. var Z_TEXT = 1;
  14857. //var Z_ASCII = 1; // = Z_TEXT
  14858. var Z_UNKNOWN = 2;
  14859. /*============================================================================*/
  14860. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  14861. // From zutil.h
  14862. var STORED_BLOCK = 0;
  14863. var STATIC_TREES = 1;
  14864. var DYN_TREES = 2;
  14865. /* The three kinds of block type */
  14866. var MIN_MATCH = 3;
  14867. var MAX_MATCH = 258;
  14868. /* The minimum and maximum match lengths */
  14869. // From deflate.h
  14870. /* ===========================================================================
  14871. * Internal compression state.
  14872. */
  14873. var LENGTH_CODES = 29;
  14874. /* number of length codes, not counting the special END_BLOCK code */
  14875. var LITERALS = 256;
  14876. /* number of literal bytes 0..255 */
  14877. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  14878. /* number of Literal or Length codes, including the END_BLOCK code */
  14879. var D_CODES = 30;
  14880. /* number of distance codes */
  14881. var BL_CODES = 19;
  14882. /* number of codes used to transfer the bit lengths */
  14883. var HEAP_SIZE = 2*L_CODES + 1;
  14884. /* maximum heap size */
  14885. var MAX_BITS = 15;
  14886. /* All codes must not exceed MAX_BITS bits */
  14887. var Buf_size = 16;
  14888. /* size of bit buffer in bi_buf */
  14889. /* ===========================================================================
  14890. * Constants
  14891. */
  14892. var MAX_BL_BITS = 7;
  14893. /* Bit length codes must not exceed MAX_BL_BITS bits */
  14894. var END_BLOCK = 256;
  14895. /* end of block literal code */
  14896. var REP_3_6 = 16;
  14897. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  14898. var REPZ_3_10 = 17;
  14899. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  14900. var REPZ_11_138 = 18;
  14901. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  14902. var extra_lbits = /* extra bits for each length code */
  14903. [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];
  14904. var extra_dbits = /* extra bits for each distance code */
  14905. [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];
  14906. var extra_blbits = /* extra bits for each bit length code */
  14907. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  14908. var bl_order =
  14909. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  14910. /* The lengths of the bit length codes are sent in order of decreasing
  14911. * probability, to avoid transmitting the lengths for unused bit length codes.
  14912. */
  14913. /* ===========================================================================
  14914. * Local data. These are initialized only once.
  14915. */
  14916. // We pre-fill arrays with 0 to avoid uninitialized gaps
  14917. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  14918. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  14919. var static_ltree = new Array((L_CODES+2) * 2);
  14920. zero(static_ltree);
  14921. /* The static literal tree. Since the bit lengths are imposed, there is no
  14922. * need for the L_CODES extra codes used during heap construction. However
  14923. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  14924. * below).
  14925. */
  14926. var static_dtree = new Array(D_CODES * 2);
  14927. zero(static_dtree);
  14928. /* The static distance tree. (Actually a trivial tree since all codes use
  14929. * 5 bits.)
  14930. */
  14931. var _dist_code = new Array(DIST_CODE_LEN);
  14932. zero(_dist_code);
  14933. /* Distance codes. The first 256 values correspond to the distances
  14934. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  14935. * the 15 bit distances.
  14936. */
  14937. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  14938. zero(_length_code);
  14939. /* length code for each normalized match length (0 == MIN_MATCH) */
  14940. var base_length = new Array(LENGTH_CODES);
  14941. zero(base_length);
  14942. /* First normalized length for each code (0 = MIN_MATCH) */
  14943. var base_dist = new Array(D_CODES);
  14944. zero(base_dist);
  14945. /* First normalized distance for each code (0 = distance of 1) */
  14946. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  14947. this.static_tree = static_tree; /* static tree or NULL */
  14948. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  14949. this.extra_base = extra_base; /* base index for extra_bits */
  14950. this.elems = elems; /* max number of elements in the tree */
  14951. this.max_length = max_length; /* max bit length for the codes */
  14952. // show if `static_tree` has data or dummy - needed for monomorphic objects
  14953. this.has_stree = static_tree && static_tree.length;
  14954. };
  14955. var static_l_desc;
  14956. var static_d_desc;
  14957. var static_bl_desc;
  14958. var TreeDesc = function(dyn_tree, stat_desc) {
  14959. this.dyn_tree = dyn_tree; /* the dynamic tree */
  14960. this.max_code = 0; /* largest code with non zero frequency */
  14961. this.stat_desc = stat_desc; /* the corresponding static tree */
  14962. };
  14963. function d_code(dist) {
  14964. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  14965. }
  14966. /* ===========================================================================
  14967. * Output a short LSB first on the stream.
  14968. * IN assertion: there is enough room in pendingBuf.
  14969. */
  14970. function put_short (s, w) {
  14971. // put_byte(s, (uch)((w) & 0xff));
  14972. // put_byte(s, (uch)((ush)(w) >> 8));
  14973. s.pending_buf[s.pending++] = (w) & 0xff;
  14974. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  14975. }
  14976. /* ===========================================================================
  14977. * Send a value on a given number of bits.
  14978. * IN assertion: length <= 16 and value fits in length bits.
  14979. */
  14980. function send_bits(s, value, length) {
  14981. if (s.bi_valid > (Buf_size - length)) {
  14982. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  14983. put_short(s, s.bi_buf);
  14984. s.bi_buf = value >> (Buf_size - s.bi_valid);
  14985. s.bi_valid += length - Buf_size;
  14986. } else {
  14987. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  14988. s.bi_valid += length;
  14989. }
  14990. }
  14991. function send_code(s, c, tree) {
  14992. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  14993. }
  14994. /* ===========================================================================
  14995. * Reverse the first len bits of a code, using straightforward code (a faster
  14996. * method would use a table)
  14997. * IN assertion: 1 <= len <= 15
  14998. */
  14999. function bi_reverse(code, len) {
  15000. var res = 0;
  15001. do {
  15002. res |= code & 1;
  15003. code >>>= 1;
  15004. res <<= 1;
  15005. } while (--len > 0);
  15006. return res >>> 1;
  15007. }
  15008. /* ===========================================================================
  15009. * Flush the bit buffer, keeping at most 7 bits in it.
  15010. */
  15011. function bi_flush(s) {
  15012. if (s.bi_valid === 16) {
  15013. put_short(s, s.bi_buf);
  15014. s.bi_buf = 0;
  15015. s.bi_valid = 0;
  15016. } else if (s.bi_valid >= 8) {
  15017. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  15018. s.bi_buf >>= 8;
  15019. s.bi_valid -= 8;
  15020. }
  15021. }
  15022. /* ===========================================================================
  15023. * Compute the optimal bit lengths for a tree and update the total bit length
  15024. * for the current block.
  15025. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  15026. * above are the tree nodes sorted by increasing frequency.
  15027. * OUT assertions: the field len is set to the optimal bit length, the
  15028. * array bl_count contains the frequencies for each bit length.
  15029. * The length opt_len is updated; static_len is also updated if stree is
  15030. * not null.
  15031. */
  15032. function gen_bitlen(s, desc)
  15033. // deflate_state *s;
  15034. // tree_desc *desc; /* the tree descriptor */
  15035. {
  15036. var tree = desc.dyn_tree;
  15037. var max_code = desc.max_code;
  15038. var stree = desc.stat_desc.static_tree;
  15039. var has_stree = desc.stat_desc.has_stree;
  15040. var extra = desc.stat_desc.extra_bits;
  15041. var base = desc.stat_desc.extra_base;
  15042. var max_length = desc.stat_desc.max_length;
  15043. var h; /* heap index */
  15044. var n, m; /* iterate over the tree elements */
  15045. var bits; /* bit length */
  15046. var xbits; /* extra bits */
  15047. var f; /* frequency */
  15048. var overflow = 0; /* number of elements with bit length too large */
  15049. for (bits = 0; bits <= MAX_BITS; bits++) {
  15050. s.bl_count[bits] = 0;
  15051. }
  15052. /* In a first pass, compute the optimal bit lengths (which may
  15053. * overflow in the case of the bit length tree).
  15054. */
  15055. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  15056. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  15057. n = s.heap[h];
  15058. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  15059. if (bits > max_length) {
  15060. bits = max_length;
  15061. overflow++;
  15062. }
  15063. tree[n*2 + 1]/*.Len*/ = bits;
  15064. /* We overwrite tree[n].Dad which is no longer needed */
  15065. if (n > max_code) { continue; } /* not a leaf node */
  15066. s.bl_count[bits]++;
  15067. xbits = 0;
  15068. if (n >= base) {
  15069. xbits = extra[n-base];
  15070. }
  15071. f = tree[n * 2]/*.Freq*/;
  15072. s.opt_len += f * (bits + xbits);
  15073. if (has_stree) {
  15074. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  15075. }
  15076. }
  15077. if (overflow === 0) { return; }
  15078. // Trace((stderr,"\nbit length overflow\n"));
  15079. /* This happens for example on obj2 and pic of the Calgary corpus */
  15080. /* Find the first bit length which could increase: */
  15081. do {
  15082. bits = max_length-1;
  15083. while (s.bl_count[bits] === 0) { bits--; }
  15084. s.bl_count[bits]--; /* move one leaf down the tree */
  15085. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  15086. s.bl_count[max_length]--;
  15087. /* The brother of the overflow item also moves one step up,
  15088. * but this does not affect bl_count[max_length]
  15089. */
  15090. overflow -= 2;
  15091. } while (overflow > 0);
  15092. /* Now recompute all bit lengths, scanning in increasing frequency.
  15093. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  15094. * lengths instead of fixing only the wrong ones. This idea is taken
  15095. * from 'ar' written by Haruhiko Okumura.)
  15096. */
  15097. for (bits = max_length; bits !== 0; bits--) {
  15098. n = s.bl_count[bits];
  15099. while (n !== 0) {
  15100. m = s.heap[--h];
  15101. if (m > max_code) { continue; }
  15102. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  15103. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  15104. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  15105. tree[m*2 + 1]/*.Len*/ = bits;
  15106. }
  15107. n--;
  15108. }
  15109. }
  15110. }
  15111. /* ===========================================================================
  15112. * Generate the codes for a given tree and bit counts (which need not be
  15113. * optimal).
  15114. * IN assertion: the array bl_count contains the bit length statistics for
  15115. * the given tree and the field len is set for all tree elements.
  15116. * OUT assertion: the field code is set for all tree elements of non
  15117. * zero code length.
  15118. */
  15119. function gen_codes(tree, max_code, bl_count)
  15120. // ct_data *tree; /* the tree to decorate */
  15121. // int max_code; /* largest code with non zero frequency */
  15122. // ushf *bl_count; /* number of codes at each bit length */
  15123. {
  15124. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  15125. var code = 0; /* running code value */
  15126. var bits; /* bit index */
  15127. var n; /* code index */
  15128. /* The distribution counts are first used to generate the code values
  15129. * without bit reversal.
  15130. */
  15131. for (bits = 1; bits <= MAX_BITS; bits++) {
  15132. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  15133. }
  15134. /* Check that the bit counts in bl_count are consistent. The last code
  15135. * must be all ones.
  15136. */
  15137. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  15138. // "inconsistent bit counts");
  15139. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  15140. for (n = 0; n <= max_code; n++) {
  15141. var len = tree[n*2 + 1]/*.Len*/;
  15142. if (len === 0) { continue; }
  15143. /* Now reverse the bits */
  15144. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  15145. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  15146. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  15147. }
  15148. }
  15149. /* ===========================================================================
  15150. * Initialize the various 'constant' tables.
  15151. */
  15152. function tr_static_init() {
  15153. var n; /* iterates over tree elements */
  15154. var bits; /* bit counter */
  15155. var length; /* length value */
  15156. var code; /* code value */
  15157. var dist; /* distance index */
  15158. var bl_count = new Array(MAX_BITS+1);
  15159. /* number of codes at each bit length for an optimal tree */
  15160. // do check in _tr_init()
  15161. //if (static_init_done) return;
  15162. /* For some embedded targets, global variables are not initialized: */
  15163. /*#ifdef NO_INIT_GLOBAL_POINTERS
  15164. static_l_desc.static_tree = static_ltree;
  15165. static_l_desc.extra_bits = extra_lbits;
  15166. static_d_desc.static_tree = static_dtree;
  15167. static_d_desc.extra_bits = extra_dbits;
  15168. static_bl_desc.extra_bits = extra_blbits;
  15169. #endif*/
  15170. /* Initialize the mapping length (0..255) -> length code (0..28) */
  15171. length = 0;
  15172. for (code = 0; code < LENGTH_CODES-1; code++) {
  15173. base_length[code] = length;
  15174. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  15175. _length_code[length++] = code;
  15176. }
  15177. }
  15178. //Assert (length == 256, "tr_static_init: length != 256");
  15179. /* Note that the length 255 (match length 258) can be represented
  15180. * in two different ways: code 284 + 5 bits or code 285, so we
  15181. * overwrite length_code[255] to use the best encoding:
  15182. */
  15183. _length_code[length-1] = code;
  15184. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  15185. dist = 0;
  15186. for (code = 0 ; code < 16; code++) {
  15187. base_dist[code] = dist;
  15188. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  15189. _dist_code[dist++] = code;
  15190. }
  15191. }
  15192. //Assert (dist == 256, "tr_static_init: dist != 256");
  15193. dist >>= 7; /* from now on, all distances are divided by 128 */
  15194. for (; code < D_CODES; code++) {
  15195. base_dist[code] = dist << 7;
  15196. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  15197. _dist_code[256 + dist++] = code;
  15198. }
  15199. }
  15200. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  15201. /* Construct the codes of the static literal tree */
  15202. for (bits = 0; bits <= MAX_BITS; bits++) {
  15203. bl_count[bits] = 0;
  15204. }
  15205. n = 0;
  15206. while (n <= 143) {
  15207. static_ltree[n*2 + 1]/*.Len*/ = 8;
  15208. n++;
  15209. bl_count[8]++;
  15210. }
  15211. while (n <= 255) {
  15212. static_ltree[n*2 + 1]/*.Len*/ = 9;
  15213. n++;
  15214. bl_count[9]++;
  15215. }
  15216. while (n <= 279) {
  15217. static_ltree[n*2 + 1]/*.Len*/ = 7;
  15218. n++;
  15219. bl_count[7]++;
  15220. }
  15221. while (n <= 287) {
  15222. static_ltree[n*2 + 1]/*.Len*/ = 8;
  15223. n++;
  15224. bl_count[8]++;
  15225. }
  15226. /* Codes 286 and 287 do not exist, but we must include them in the
  15227. * tree construction to get a canonical Huffman tree (longest code
  15228. * all ones)
  15229. */
  15230. gen_codes(static_ltree, L_CODES+1, bl_count);
  15231. /* The static distance tree is trivial: */
  15232. for (n = 0; n < D_CODES; n++) {
  15233. static_dtree[n*2 + 1]/*.Len*/ = 5;
  15234. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  15235. }
  15236. // Now data ready and we can init static trees
  15237. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  15238. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  15239. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  15240. //static_init_done = true;
  15241. }
  15242. /* ===========================================================================
  15243. * Initialize a new block.
  15244. */
  15245. function init_block(s) {
  15246. var n; /* iterates over tree elements */
  15247. /* Initialize the trees. */
  15248. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  15249. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  15250. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  15251. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  15252. s.opt_len = s.static_len = 0;
  15253. s.last_lit = s.matches = 0;
  15254. }
  15255. /* ===========================================================================
  15256. * Flush the bit buffer and align the output on a byte boundary
  15257. */
  15258. function bi_windup(s)
  15259. {
  15260. if (s.bi_valid > 8) {
  15261. put_short(s, s.bi_buf);
  15262. } else if (s.bi_valid > 0) {
  15263. //put_byte(s, (Byte)s->bi_buf);
  15264. s.pending_buf[s.pending++] = s.bi_buf;
  15265. }
  15266. s.bi_buf = 0;
  15267. s.bi_valid = 0;
  15268. }
  15269. /* ===========================================================================
  15270. * Copy a stored block, storing first the length and its
  15271. * one's complement if requested.
  15272. */
  15273. function copy_block(s, buf, len, header)
  15274. //DeflateState *s;
  15275. //charf *buf; /* the input data */
  15276. //unsigned len; /* its length */
  15277. //int header; /* true if block header must be written */
  15278. {
  15279. bi_windup(s); /* align on byte boundary */
  15280. if (header) {
  15281. put_short(s, len);
  15282. put_short(s, ~len);
  15283. }
  15284. // while (len--) {
  15285. // put_byte(s, *buf++);
  15286. // }
  15287. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  15288. s.pending += len;
  15289. }
  15290. /* ===========================================================================
  15291. * Compares to subtrees, using the tree depth as tie breaker when
  15292. * the subtrees have equal frequency. This minimizes the worst case length.
  15293. */
  15294. function smaller(tree, n, m, depth) {
  15295. var _n2 = n*2;
  15296. var _m2 = m*2;
  15297. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  15298. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  15299. }
  15300. /* ===========================================================================
  15301. * Restore the heap property by moving down the tree starting at node k,
  15302. * exchanging a node with the smallest of its two sons if necessary, stopping
  15303. * when the heap property is re-established (each father smaller than its
  15304. * two sons).
  15305. */
  15306. function pqdownheap(s, tree, k)
  15307. // deflate_state *s;
  15308. // ct_data *tree; /* the tree to restore */
  15309. // int k; /* node to move down */
  15310. {
  15311. var v = s.heap[k];
  15312. var j = k << 1; /* left son of k */
  15313. while (j <= s.heap_len) {
  15314. /* Set j to the smallest of the two sons: */
  15315. if (j < s.heap_len &&
  15316. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  15317. j++;
  15318. }
  15319. /* Exit if v is smaller than both sons */
  15320. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  15321. /* Exchange v with the smallest son */
  15322. s.heap[k] = s.heap[j];
  15323. k = j;
  15324. /* And continue down the tree, setting j to the left son of k */
  15325. j <<= 1;
  15326. }
  15327. s.heap[k] = v;
  15328. }
  15329. // inlined manually
  15330. // var SMALLEST = 1;
  15331. /* ===========================================================================
  15332. * Send the block data compressed using the given Huffman trees
  15333. */
  15334. function compress_block(s, ltree, dtree)
  15335. // deflate_state *s;
  15336. // const ct_data *ltree; /* literal tree */
  15337. // const ct_data *dtree; /* distance tree */
  15338. {
  15339. var dist; /* distance of matched string */
  15340. var lc; /* match length or unmatched char (if dist == 0) */
  15341. var lx = 0; /* running index in l_buf */
  15342. var code; /* the code to send */
  15343. var extra; /* number of extra bits to send */
  15344. if (s.last_lit !== 0) {
  15345. do {
  15346. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  15347. lc = s.pending_buf[s.l_buf + lx];
  15348. lx++;
  15349. if (dist === 0) {
  15350. send_code(s, lc, ltree); /* send a literal byte */
  15351. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  15352. } else {
  15353. /* Here, lc is the match length - MIN_MATCH */
  15354. code = _length_code[lc];
  15355. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  15356. extra = extra_lbits[code];
  15357. if (extra !== 0) {
  15358. lc -= base_length[code];
  15359. send_bits(s, lc, extra); /* send the extra length bits */
  15360. }
  15361. dist--; /* dist is now the match distance - 1 */
  15362. code = d_code(dist);
  15363. //Assert (code < D_CODES, "bad d_code");
  15364. send_code(s, code, dtree); /* send the distance code */
  15365. extra = extra_dbits[code];
  15366. if (extra !== 0) {
  15367. dist -= base_dist[code];
  15368. send_bits(s, dist, extra); /* send the extra distance bits */
  15369. }
  15370. } /* literal or match pair ? */
  15371. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  15372. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  15373. // "pendingBuf overflow");
  15374. } while (lx < s.last_lit);
  15375. }
  15376. send_code(s, END_BLOCK, ltree);
  15377. }
  15378. /* ===========================================================================
  15379. * Construct one Huffman tree and assigns the code bit strings and lengths.
  15380. * Update the total bit length for the current block.
  15381. * IN assertion: the field freq is set for all tree elements.
  15382. * OUT assertions: the fields len and code are set to the optimal bit length
  15383. * and corresponding code. The length opt_len is updated; static_len is
  15384. * also updated if stree is not null. The field max_code is set.
  15385. */
  15386. function build_tree(s, desc)
  15387. // deflate_state *s;
  15388. // tree_desc *desc; /* the tree descriptor */
  15389. {
  15390. var tree = desc.dyn_tree;
  15391. var stree = desc.stat_desc.static_tree;
  15392. var has_stree = desc.stat_desc.has_stree;
  15393. var elems = desc.stat_desc.elems;
  15394. var n, m; /* iterate over heap elements */
  15395. var max_code = -1; /* largest code with non zero frequency */
  15396. var node; /* new node being created */
  15397. /* Construct the initial heap, with least frequent element in
  15398. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  15399. * heap[0] is not used.
  15400. */
  15401. s.heap_len = 0;
  15402. s.heap_max = HEAP_SIZE;
  15403. for (n = 0; n < elems; n++) {
  15404. if (tree[n * 2]/*.Freq*/ !== 0) {
  15405. s.heap[++s.heap_len] = max_code = n;
  15406. s.depth[n] = 0;
  15407. } else {
  15408. tree[n*2 + 1]/*.Len*/ = 0;
  15409. }
  15410. }
  15411. /* The pkzip format requires that at least one distance code exists,
  15412. * and that at least one bit should be sent even if there is only one
  15413. * possible code. So to avoid special checks later on we force at least
  15414. * two codes of non zero frequency.
  15415. */
  15416. while (s.heap_len < 2) {
  15417. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  15418. tree[node * 2]/*.Freq*/ = 1;
  15419. s.depth[node] = 0;
  15420. s.opt_len--;
  15421. if (has_stree) {
  15422. s.static_len -= stree[node*2 + 1]/*.Len*/;
  15423. }
  15424. /* node is 0 or 1 so it does not have extra bits */
  15425. }
  15426. desc.max_code = max_code;
  15427. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  15428. * establish sub-heaps of increasing lengths:
  15429. */
  15430. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  15431. /* Construct the Huffman tree by repeatedly combining the least two
  15432. * frequent nodes.
  15433. */
  15434. node = elems; /* next internal node of the tree */
  15435. do {
  15436. //pqremove(s, tree, n); /* n = node of least frequency */
  15437. /*** pqremove ***/
  15438. n = s.heap[1/*SMALLEST*/];
  15439. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  15440. pqdownheap(s, tree, 1/*SMALLEST*/);
  15441. /***/
  15442. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  15443. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  15444. s.heap[--s.heap_max] = m;
  15445. /* Create a new node father of n and m */
  15446. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  15447. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  15448. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  15449. /* and insert the new node in the heap */
  15450. s.heap[1/*SMALLEST*/] = node++;
  15451. pqdownheap(s, tree, 1/*SMALLEST*/);
  15452. } while (s.heap_len >= 2);
  15453. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  15454. /* At this point, the fields freq and dad are set. We can now
  15455. * generate the bit lengths.
  15456. */
  15457. gen_bitlen(s, desc);
  15458. /* The field len is now set, we can generate the bit codes */
  15459. gen_codes(tree, max_code, s.bl_count);
  15460. }
  15461. /* ===========================================================================
  15462. * Scan a literal or distance tree to determine the frequencies of the codes
  15463. * in the bit length tree.
  15464. */
  15465. function scan_tree(s, tree, max_code)
  15466. // deflate_state *s;
  15467. // ct_data *tree; /* the tree to be scanned */
  15468. // int max_code; /* and its largest code of non zero frequency */
  15469. {
  15470. var n; /* iterates over all tree elements */
  15471. var prevlen = -1; /* last emitted length */
  15472. var curlen; /* length of current code */
  15473. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  15474. var count = 0; /* repeat count of the current code */
  15475. var max_count = 7; /* max repeat count */
  15476. var min_count = 4; /* min repeat count */
  15477. if (nextlen === 0) {
  15478. max_count = 138;
  15479. min_count = 3;
  15480. }
  15481. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  15482. for (n = 0; n <= max_code; n++) {
  15483. curlen = nextlen;
  15484. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  15485. if (++count < max_count && curlen === nextlen) {
  15486. continue;
  15487. } else if (count < min_count) {
  15488. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  15489. } else if (curlen !== 0) {
  15490. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  15491. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  15492. } else if (count <= 10) {
  15493. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  15494. } else {
  15495. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  15496. }
  15497. count = 0;
  15498. prevlen = curlen;
  15499. if (nextlen === 0) {
  15500. max_count = 138;
  15501. min_count = 3;
  15502. } else if (curlen === nextlen) {
  15503. max_count = 6;
  15504. min_count = 3;
  15505. } else {
  15506. max_count = 7;
  15507. min_count = 4;
  15508. }
  15509. }
  15510. }
  15511. /* ===========================================================================
  15512. * Send a literal or distance tree in compressed form, using the codes in
  15513. * bl_tree.
  15514. */
  15515. function send_tree(s, tree, max_code)
  15516. // deflate_state *s;
  15517. // ct_data *tree; /* the tree to be scanned */
  15518. // int max_code; /* and its largest code of non zero frequency */
  15519. {
  15520. var n; /* iterates over all tree elements */
  15521. var prevlen = -1; /* last emitted length */
  15522. var curlen; /* length of current code */
  15523. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  15524. var count = 0; /* repeat count of the current code */
  15525. var max_count = 7; /* max repeat count */
  15526. var min_count = 4; /* min repeat count */
  15527. /* tree[max_code+1].Len = -1; */ /* guard already set */
  15528. if (nextlen === 0) {
  15529. max_count = 138;
  15530. min_count = 3;
  15531. }
  15532. for (n = 0; n <= max_code; n++) {
  15533. curlen = nextlen;
  15534. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  15535. if (++count < max_count && curlen === nextlen) {
  15536. continue;
  15537. } else if (count < min_count) {
  15538. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  15539. } else if (curlen !== 0) {
  15540. if (curlen !== prevlen) {
  15541. send_code(s, curlen, s.bl_tree);
  15542. count--;
  15543. }
  15544. //Assert(count >= 3 && count <= 6, " 3_6?");
  15545. send_code(s, REP_3_6, s.bl_tree);
  15546. send_bits(s, count-3, 2);
  15547. } else if (count <= 10) {
  15548. send_code(s, REPZ_3_10, s.bl_tree);
  15549. send_bits(s, count-3, 3);
  15550. } else {
  15551. send_code(s, REPZ_11_138, s.bl_tree);
  15552. send_bits(s, count-11, 7);
  15553. }
  15554. count = 0;
  15555. prevlen = curlen;
  15556. if (nextlen === 0) {
  15557. max_count = 138;
  15558. min_count = 3;
  15559. } else if (curlen === nextlen) {
  15560. max_count = 6;
  15561. min_count = 3;
  15562. } else {
  15563. max_count = 7;
  15564. min_count = 4;
  15565. }
  15566. }
  15567. }
  15568. /* ===========================================================================
  15569. * Construct the Huffman tree for the bit lengths and return the index in
  15570. * bl_order of the last bit length code to send.
  15571. */
  15572. function build_bl_tree(s) {
  15573. var max_blindex; /* index of last bit length code of non zero freq */
  15574. /* Determine the bit length frequencies for literal and distance trees */
  15575. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  15576. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  15577. /* Build the bit length tree: */
  15578. build_tree(s, s.bl_desc);
  15579. /* opt_len now includes the length of the tree representations, except
  15580. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  15581. */
  15582. /* Determine the number of bit length codes to send. The pkzip format
  15583. * requires that at least 4 bit length codes be sent. (appnote.txt says
  15584. * 3 but the actual value used is 4.)
  15585. */
  15586. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  15587. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  15588. break;
  15589. }
  15590. }
  15591. /* Update opt_len to include the bit length tree and counts */
  15592. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  15593. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  15594. // s->opt_len, s->static_len));
  15595. return max_blindex;
  15596. }
  15597. /* ===========================================================================
  15598. * Send the header for a block using dynamic Huffman trees: the counts, the
  15599. * lengths of the bit length codes, the literal tree and the distance tree.
  15600. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  15601. */
  15602. function send_all_trees(s, lcodes, dcodes, blcodes)
  15603. // deflate_state *s;
  15604. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  15605. {
  15606. var rank; /* index in bl_order */
  15607. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  15608. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  15609. // "too many codes");
  15610. //Tracev((stderr, "\nbl counts: "));
  15611. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  15612. send_bits(s, dcodes-1, 5);
  15613. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  15614. for (rank = 0; rank < blcodes; rank++) {
  15615. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  15616. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  15617. }
  15618. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  15619. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  15620. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  15621. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  15622. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  15623. }
  15624. /* ===========================================================================
  15625. * Check if the data type is TEXT or BINARY, using the following algorithm:
  15626. * - TEXT if the two conditions below are satisfied:
  15627. * a) There are no non-portable control characters belonging to the
  15628. * "black list" (0..6, 14..25, 28..31).
  15629. * b) There is at least one printable character belonging to the
  15630. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  15631. * - BINARY otherwise.
  15632. * - The following partially-portable control characters form a
  15633. * "gray list" that is ignored in this detection algorithm:
  15634. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  15635. * IN assertion: the fields Freq of dyn_ltree are set.
  15636. */
  15637. function detect_data_type(s) {
  15638. /* black_mask is the bit mask of black-listed bytes
  15639. * set bits 0..6, 14..25, and 28..31
  15640. * 0xf3ffc07f = binary 11110011111111111100000001111111
  15641. */
  15642. var black_mask = 0xf3ffc07f;
  15643. var n;
  15644. /* Check for non-textual ("black-listed") bytes. */
  15645. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  15646. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  15647. return Z_BINARY;
  15648. }
  15649. }
  15650. /* Check for textual ("white-listed") bytes. */
  15651. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  15652. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  15653. return Z_TEXT;
  15654. }
  15655. for (n = 32; n < LITERALS; n++) {
  15656. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  15657. return Z_TEXT;
  15658. }
  15659. }
  15660. /* There are no "black-listed" or "white-listed" bytes:
  15661. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  15662. */
  15663. return Z_BINARY;
  15664. }
  15665. var static_init_done = false;
  15666. /* ===========================================================================
  15667. * Initialize the tree data structures for a new zlib stream.
  15668. */
  15669. function _tr_init(s)
  15670. {
  15671. if (!static_init_done) {
  15672. tr_static_init();
  15673. static_init_done = true;
  15674. }
  15675. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  15676. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  15677. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  15678. s.bi_buf = 0;
  15679. s.bi_valid = 0;
  15680. /* Initialize the first block of the first file: */
  15681. init_block(s);
  15682. }
  15683. /* ===========================================================================
  15684. * Send a stored block
  15685. */
  15686. function _tr_stored_block(s, buf, stored_len, last)
  15687. //DeflateState *s;
  15688. //charf *buf; /* input block */
  15689. //ulg stored_len; /* length of input block */
  15690. //int last; /* one if this is the last block for a file */
  15691. {
  15692. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  15693. copy_block(s, buf, stored_len, true); /* with header */
  15694. }
  15695. /* ===========================================================================
  15696. * Send one empty static block to give enough lookahead for inflate.
  15697. * This takes 10 bits, of which 7 may remain in the bit buffer.
  15698. */
  15699. function _tr_align(s) {
  15700. send_bits(s, STATIC_TREES<<1, 3);
  15701. send_code(s, END_BLOCK, static_ltree);
  15702. bi_flush(s);
  15703. }
  15704. /* ===========================================================================
  15705. * Determine the best encoding for the current block: dynamic trees, static
  15706. * trees or store, and output the encoded block to the zip file.
  15707. */
  15708. function _tr_flush_block(s, buf, stored_len, last)
  15709. //DeflateState *s;
  15710. //charf *buf; /* input block, or NULL if too old */
  15711. //ulg stored_len; /* length of input block */
  15712. //int last; /* one if this is the last block for a file */
  15713. {
  15714. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  15715. var max_blindex = 0; /* index of last bit length code of non zero freq */
  15716. /* Build the Huffman trees unless a stored block is forced */
  15717. if (s.level > 0) {
  15718. /* Check if the file is binary or text */
  15719. if (s.strm.data_type === Z_UNKNOWN) {
  15720. s.strm.data_type = detect_data_type(s);
  15721. }
  15722. /* Construct the literal and distance trees */
  15723. build_tree(s, s.l_desc);
  15724. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  15725. // s->static_len));
  15726. build_tree(s, s.d_desc);
  15727. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  15728. // s->static_len));
  15729. /* At this point, opt_len and static_len are the total bit lengths of
  15730. * the compressed block data, excluding the tree representations.
  15731. */
  15732. /* Build the bit length tree for the above two trees, and get the index
  15733. * in bl_order of the last bit length code to send.
  15734. */
  15735. max_blindex = build_bl_tree(s);
  15736. /* Determine the best encoding. Compute the block lengths in bytes. */
  15737. opt_lenb = (s.opt_len+3+7) >>> 3;
  15738. static_lenb = (s.static_len+3+7) >>> 3;
  15739. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  15740. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  15741. // s->last_lit));
  15742. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  15743. } else {
  15744. // Assert(buf != (char*)0, "lost buf");
  15745. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  15746. }
  15747. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  15748. /* 4: two words for the lengths */
  15749. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  15750. * Otherwise we can't have processed more than WSIZE input bytes since
  15751. * the last block flush, because compression would have been
  15752. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  15753. * transform a block into a stored block.
  15754. */
  15755. _tr_stored_block(s, buf, stored_len, last);
  15756. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  15757. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  15758. compress_block(s, static_ltree, static_dtree);
  15759. } else {
  15760. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  15761. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  15762. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  15763. }
  15764. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  15765. /* The above check is made mod 2^32, for files larger than 512 MB
  15766. * and uLong implemented on 32 bits.
  15767. */
  15768. init_block(s);
  15769. if (last) {
  15770. bi_windup(s);
  15771. }
  15772. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  15773. // s->compressed_len-7*last));
  15774. }
  15775. /* ===========================================================================
  15776. * Save the match info and tally the frequency counts. Return true if
  15777. * the current block must be flushed.
  15778. */
  15779. function _tr_tally(s, dist, lc)
  15780. // deflate_state *s;
  15781. // unsigned dist; /* distance of matched string */
  15782. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  15783. {
  15784. //var out_length, in_length, dcode;
  15785. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  15786. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  15787. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  15788. s.last_lit++;
  15789. if (dist === 0) {
  15790. /* lc is the unmatched char */
  15791. s.dyn_ltree[lc*2]/*.Freq*/++;
  15792. } else {
  15793. s.matches++;
  15794. /* Here, lc is the match length - MIN_MATCH */
  15795. dist--; /* dist = match distance - 1 */
  15796. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  15797. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  15798. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  15799. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  15800. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  15801. }
  15802. // (!) This block is disabled in zlib defailts,
  15803. // don't enable it for binary compatibility
  15804. //#ifdef TRUNCATE_BLOCK
  15805. // /* Try to guess if it is profitable to stop the current block here */
  15806. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  15807. // /* Compute an upper bound for the compressed length */
  15808. // out_length = s.last_lit*8;
  15809. // in_length = s.strstart - s.block_start;
  15810. //
  15811. // for (dcode = 0; dcode < D_CODES; dcode++) {
  15812. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  15813. // }
  15814. // out_length >>>= 3;
  15815. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  15816. // // s->last_lit, in_length, out_length,
  15817. // // 100L - out_length*100L/in_length));
  15818. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  15819. // return true;
  15820. // }
  15821. // }
  15822. //#endif
  15823. return (s.last_lit === s.lit_bufsize-1);
  15824. /* We avoid equality with lit_bufsize because of wraparound at 64K
  15825. * on 16 bit machines and because stored blocks are restricted to
  15826. * 64K-1 bytes.
  15827. */
  15828. }
  15829. exports._tr_init = _tr_init;
  15830. exports._tr_stored_block = _tr_stored_block;
  15831. exports._tr_flush_block = _tr_flush_block;
  15832. exports._tr_tally = _tr_tally;
  15833. exports._tr_align = _tr_align;
  15834. },{"../utils/common":39}],51:[function(require,module,exports){
  15835. 'use strict';
  15836. function ZStream() {
  15837. /* next input byte */
  15838. this.input = null; // JS specific, because we have no pointers
  15839. this.next_in = 0;
  15840. /* number of bytes available at input */
  15841. this.avail_in = 0;
  15842. /* total number of input bytes read so far */
  15843. this.total_in = 0;
  15844. /* next output byte should be put there */
  15845. this.output = null; // JS specific, because we have no pointers
  15846. this.next_out = 0;
  15847. /* remaining free space at output */
  15848. this.avail_out = 0;
  15849. /* total number of bytes output so far */
  15850. this.total_out = 0;
  15851. /* last error message, NULL if no error */
  15852. this.msg = ''/*Z_NULL*/;
  15853. /* not visible by applications */
  15854. this.state = null;
  15855. /* best guess about the data type: binary or text */
  15856. this.data_type = 2/*Z_UNKNOWN*/;
  15857. /* adler32 value of the uncompressed data */
  15858. this.adler = 0;
  15859. }
  15860. module.exports = ZStream;
  15861. },{}],52:[function(require,module,exports){
  15862. module.exports = function arrayEquals(array) {
  15863. // if the other array is a falsy value, return
  15864. if (!array)
  15865. return false;
  15866. // compare lengths - can save a lot of time
  15867. if (this.length != array.length)
  15868. return false;
  15869. for (var i = 0, l = this.length; i < l; i++) {
  15870. // Check if we have nested arrays
  15871. if (this[i] instanceof Array && array[i] instanceof Array) {
  15872. // recurse into the nested arrays
  15873. if (!arrayEquals.apply(this[i], [array[i]]))
  15874. return false;
  15875. } else if (this[i] != array[i]) {
  15876. // Warning - two different object instances will never be equal:
  15877. // {x:20} != {x:20}
  15878. return false;
  15879. }
  15880. }
  15881. return true;
  15882. }
  15883. },{}],53:[function(require,module,exports){
  15884. exports.Interop = require('./interop');
  15885. },{"./interop":54}],54:[function(require,module,exports){
  15886. "use strict";
  15887. var transform = require('./transform');
  15888. var arrayEquals = require('./array-equals');
  15889. function Interop() {
  15890. /**
  15891. * This map holds the most recent Unified Plan offer/answer SDP that was
  15892. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  15893. * the SDP string as values.
  15894. *
  15895. * @type {{}}
  15896. */
  15897. this.cache = {};
  15898. }
  15899. module.exports = Interop;
  15900. /**
  15901. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  15902. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  15903. * application.
  15904. *
  15905. * @param desc
  15906. * @returns {*}
  15907. */
  15908. Interop.prototype.toPlanB = function(desc) {
  15909. //#region Preliminary input validation.
  15910. if (typeof desc !== 'object' || desc === null ||
  15911. typeof desc.sdp !== 'string') {
  15912. console.warn('An empty description was passed as an argument.');
  15913. return desc;
  15914. }
  15915. // Objectify the SDP for easier manipulation.
  15916. var session = transform.parse(desc.sdp);
  15917. // If the SDP contains no media, there's nothing to transform.
  15918. if (typeof session.media === 'undefined' ||
  15919. !Array.isArray(session.media) || session.media.length === 0) {
  15920. console.warn('The description has no media.');
  15921. return desc;
  15922. }
  15923. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  15924. // SDP has a video, an audio and a data "channel" at most.
  15925. if (session.media.length <= 3 && session.media.every(function(m) {
  15926. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  15927. })) {
  15928. console.warn('This description does not look like Unified Plan.');
  15929. return desc;
  15930. }
  15931. //#endregion
  15932. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  15933. // -> Unified Plan transformation.
  15934. this.cache[desc.type] = desc.sdp;
  15935. //#region Convert from Unified Plan to Plan B.
  15936. // We rebuild the session.media array.
  15937. var media = session.media;
  15938. session.media = [];
  15939. // Associative array that maps channel types to channel objects for fast
  15940. // access to channel objects by their type, e.g. type2bl['audio']->channel
  15941. // obj.
  15942. var type2bl = {};
  15943. // Used to build the group:BUNDLE value after the channels construction
  15944. // loop.
  15945. var types = [];
  15946. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  15947. media.forEach(function(unifiedLine) {
  15948. // rtcp-mux is required in the Plan B SDP.
  15949. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  15950. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  15951. unifiedLine.direction !== 'inactive') {
  15952. throw new Error('Cannot convert to Plan B because m-lines ' +
  15953. 'without the rtcp-mux attribute were found.');
  15954. }
  15955. if (unifiedLine.type === 'application') {
  15956. session.media.push(unifiedLine);
  15957. types.push(unifiedLine.mid);
  15958. return;
  15959. }
  15960. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  15961. // as the channel basis.
  15962. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  15963. type2bl[unifiedLine.type] = unifiedLine;
  15964. }
  15965. // Add sources to the channel and handle a=msid.
  15966. if (typeof unifiedLine.sources === 'object') {
  15967. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  15968. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  15969. type2bl[unifiedLine.type].sources = {};
  15970. // Assign the sources to the channel.
  15971. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  15972. if (typeof unifiedLine.msid !== 'undefined') {
  15973. // In Plan B the msid is an SSRC attribute. Also, we don't
  15974. // care about the obsolete label and mslabel attributes.
  15975. //
  15976. // Note that it is not guaranteed that the unifiedLine will have
  15977. // an msid. recvonly channels in particular don't have one.
  15978. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  15979. }
  15980. // NOTE ssrcs in ssrc groups will share msids, as
  15981. // draft-uberti-rtcweb-plan-00 mandates.
  15982. });
  15983. }
  15984. // Add ssrc groups to the channel.
  15985. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  15986. Array.isArray(unifiedLine.ssrcGroups)) {
  15987. // Create the ssrcGroups array, if it's not defined.
  15988. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  15989. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  15990. type2bl[unifiedLine.type].ssrcGroups = [];
  15991. }
  15992. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  15993. }
  15994. if (type2bl[unifiedLine.type] === unifiedLine) {
  15995. // Copy ICE related stuff from the principal media line.
  15996. unifiedLine.candidates = media[0].candidates;
  15997. unifiedLine.iceUfrag = media[0].iceUfrag;
  15998. unifiedLine.icePwd = media[0].icePwd;
  15999. unifiedLine.fingerprint = media[0].fingerprint;
  16000. // Plan B mids are in ['audio', 'video', 'data']
  16001. unifiedLine.mid = unifiedLine.type;
  16002. // Plan B doesn't support/need the bundle-only attribute.
  16003. delete unifiedLine.bundleOnly;
  16004. // In Plan B the msid is an SSRC attribute.
  16005. delete unifiedLine.msid;
  16006. // Used to build the group:BUNDLE value after this loop.
  16007. types.push(unifiedLine.type);
  16008. // Add the channel to the new media array.
  16009. session.media.push(unifiedLine);
  16010. }
  16011. });
  16012. // We regenerate the BUNDLE group with the new mids.
  16013. session.groups.some(function(group) {
  16014. if (group.type === 'BUNDLE') {
  16015. group.mids = types.join(' ');
  16016. return true;
  16017. }
  16018. });
  16019. // msid semantic
  16020. session.msidSemantic = {
  16021. semantic: 'WMS',
  16022. token: '*'
  16023. };
  16024. var resStr = transform.write(session);
  16025. return new RTCSessionDescription({
  16026. type: desc.type,
  16027. sdp: resStr
  16028. });
  16029. //#endregion
  16030. };
  16031. /**
  16032. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  16033. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  16034. * to FF.
  16035. *
  16036. * @param desc
  16037. * @returns {*}
  16038. */
  16039. Interop.prototype.toUnifiedPlan = function(desc) {
  16040. //#region Preliminary input validation.
  16041. if (typeof desc !== 'object' || desc === null ||
  16042. typeof desc.sdp !== 'string') {
  16043. console.warn('An empty description was passed as an argument.');
  16044. return desc;
  16045. }
  16046. var session = transform.parse(desc.sdp);
  16047. // If the SDP contains no media, there's nothing to transform.
  16048. if (typeof session.media === 'undefined' ||
  16049. !Array.isArray(session.media) || session.media.length === 0) {
  16050. console.warn('The description has no media.');
  16051. return desc;
  16052. }
  16053. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  16054. // a video, an audio and a data "channel" at most.
  16055. if (session.media.length > 3 || !session.media.every(function(m) {
  16056. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  16057. })) {
  16058. console.warn('This description does not look like Plan B.');
  16059. return desc;
  16060. }
  16061. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  16062. var mids = [];
  16063. session.media.forEach(function(m) {
  16064. mids.push(m.mid);
  16065. });
  16066. var hasBundle = false;
  16067. if (typeof session.groups !== 'undefined' &&
  16068. Array.isArray(session.groups)) {
  16069. hasBundle = session.groups.every(function(g) {
  16070. return g.type !== 'BUNDLE' ||
  16071. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  16072. });
  16073. }
  16074. if (!hasBundle) {
  16075. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  16076. " are not bundled were found.");
  16077. }
  16078. //#endregion
  16079. //#region Convert from Plan B to Unified Plan.
  16080. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  16081. // rebuild an equivalent Unified Plan offer/answer.
  16082. //
  16083. // For example, if this is a local answer (in Unified Plan style) that we
  16084. // convert to Plan B prior to handing it over to the application (the
  16085. // PeerConnection wrapper called us, for instance, after a successful
  16086. // createAnswer), we want to remember the m-line at which we've seen the
  16087. // (local) SSRC. That's because when the application wants to do call the
  16088. // SLD method, forcing us to do the inverse transformation (from Plan B to
  16089. // Unified Plan), we need to know to which m-line to assign the (local)
  16090. // SSRC. We also need to know all the other m-lines that the original
  16091. // answer had and include them in the transformed answer as well.
  16092. //
  16093. // Another example is if this is a remote offer that we convert to Plan B
  16094. // prior to giving it to the application, we want to remember the mid at
  16095. // which we've seen the (remote) SSRC.
  16096. //
  16097. // In the iteration that follows, we use the cached Unified Plan (if it
  16098. // exists) to assign mids to ssrcs.
  16099. var cached;
  16100. if (typeof this.cache[desc.type] !== 'undefined') {
  16101. cached = transform.parse(this.cache[desc.type]);
  16102. }
  16103. // A helper map that sends mids to m-line objects. We use it later to
  16104. // rebuild the Unified Plan style session.media array.
  16105. var mid2ul = {};
  16106. session.media.forEach(function(bLine) {
  16107. if ((typeof bLine.rtcpMux !== 'string' ||
  16108. bLine.rtcpMux !== 'rtcp-mux') &&
  16109. bLine.direction !== 'inactive') {
  16110. throw new Error("Cannot convert to Unified Plan because m-lines " +
  16111. "without the rtcp-mux attribute were found.");
  16112. }
  16113. if (bLine.type === 'application') {
  16114. mid2ul[bLine.mid] = bLine;
  16115. return;
  16116. }
  16117. // With rtcp-mux and bundle all the channels should have the same ICE
  16118. // stuff.
  16119. var sources = bLine.sources;
  16120. var ssrcGroups = bLine.ssrcGroups;
  16121. var candidates = bLine.candidates;
  16122. var iceUfrag = bLine.iceUfrag;
  16123. var icePwd = bLine.icePwd;
  16124. var fingerprint = bLine.fingerprint;
  16125. var port = bLine.port;
  16126. // We'll use the "bLine" object as a prototype for each new "mLine"
  16127. // that we create, but first we need to clean it up a bit.
  16128. delete bLine.sources;
  16129. delete bLine.ssrcGroups;
  16130. delete bLine.candidates;
  16131. delete bLine.iceUfrag;
  16132. delete bLine.icePwd;
  16133. delete bLine.fingerprint;
  16134. delete bLine.port;
  16135. delete bLine.mid;
  16136. // inverted ssrc group map
  16137. var ssrc2group = {};
  16138. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  16139. ssrcGroups.forEach(function (ssrcGroup) {
  16140. // TODO(gp) find out how to receive simulcast with FF. For the
  16141. // time being, hide it.
  16142. if (ssrcGroup.semantics === 'SIM') {
  16143. return;
  16144. }
  16145. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  16146. Array.isArray(ssrcGroup.ssrcs)) {
  16147. ssrcGroup.ssrcs.forEach(function (ssrc) {
  16148. if (typeof ssrc2group[ssrc] === 'undefined') {
  16149. ssrc2group[ssrc] = [];
  16150. }
  16151. ssrc2group[ssrc].push(ssrcGroup);
  16152. });
  16153. }
  16154. });
  16155. }
  16156. // ssrc to m-line index.
  16157. var ssrc2ml = {};
  16158. if (typeof sources === 'object') {
  16159. // Explode the Plan B channel sources with one m-line per source.
  16160. Object.keys(sources).forEach(function(ssrc) {
  16161. // The (unified) m-line for this SSRC. We either create it from
  16162. // scratch or, if it's a grouped SSRC, we re-use a related
  16163. // mline. In other words, if the source is grouped with another
  16164. // source, put the two together in the same m-line.
  16165. var unifiedLine;
  16166. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  16167. Array.isArray(ssrc2group[ssrc])) {
  16168. ssrc2group[ssrc].some(function (ssrcGroup) {
  16169. // ssrcGroup.ssrcs *is* an Array, no need to check
  16170. // again here.
  16171. return ssrcGroup.ssrcs.some(function (related) {
  16172. if (typeof ssrc2ml[related] === 'object') {
  16173. unifiedLine = ssrc2ml[related];
  16174. return true;
  16175. }
  16176. });
  16177. });
  16178. }
  16179. if (typeof unifiedLine === 'object') {
  16180. // the m-line already exists. Just add the source.
  16181. unifiedLine.sources[ssrc] = sources[ssrc];
  16182. delete sources[ssrc].msid;
  16183. } else {
  16184. // Use the "bLine" as a prototype for the "unifiedLine".
  16185. unifiedLine = Object.create(bLine);
  16186. ssrc2ml[ssrc] = unifiedLine;
  16187. if (typeof sources[ssrc].msid !== 'undefined') {
  16188. // Assign the msid of the source to the m-line. Note
  16189. // that it is not guaranteed that the source will have
  16190. // msid. In particular "recvonly" sources don't have an
  16191. // msid. Note that "recvonly" is a term only defined
  16192. // for m-lines.
  16193. unifiedLine.msid = sources[ssrc].msid;
  16194. delete sources[ssrc].msid;
  16195. }
  16196. // We assign one SSRC per media line.
  16197. unifiedLine.sources = {};
  16198. unifiedLine.sources[ssrc] = sources[ssrc];
  16199. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  16200. // Use the cached Unified Plan SDP (if it exists) to assign
  16201. // SSRCs to mids.
  16202. if (typeof cached !== 'undefined' &&
  16203. typeof cached.media !== 'undefined' &&
  16204. Array.isArray(cached.media)) {
  16205. cached.media.forEach(function (m) {
  16206. if (typeof m.sources === 'object') {
  16207. Object.keys(m.sources).forEach(function (s) {
  16208. if (s === ssrc) {
  16209. unifiedLine.mid = m.mid;
  16210. }
  16211. });
  16212. }
  16213. });
  16214. }
  16215. if (typeof unifiedLine.mid === 'undefined') {
  16216. // If this is an SSRC that we see for the first time
  16217. // assign it a new mid. This is typically the case when
  16218. // this method is called to transform a remote
  16219. // description for the first time or when there is a
  16220. // new SSRC in the remote description because a new
  16221. // peer has joined the conference. Local SSRCs should
  16222. // have already been added to the map in the toPlanB
  16223. // method.
  16224. //
  16225. // Because FF generates answers in Unified Plan style,
  16226. // we MUST already have a cached answer with all the
  16227. // local SSRCs mapped to some m-line/mid.
  16228. if (desc.type === 'answer') {
  16229. throw new Error("An unmapped SSRC was found.");
  16230. }
  16231. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  16232. }
  16233. // Include the candidates in the 1st media line.
  16234. unifiedLine.candidates = candidates;
  16235. unifiedLine.iceUfrag = iceUfrag;
  16236. unifiedLine.icePwd = icePwd;
  16237. unifiedLine.fingerprint = fingerprint;
  16238. unifiedLine.port = port;
  16239. mid2ul[unifiedLine.mid] = unifiedLine;
  16240. }
  16241. });
  16242. }
  16243. });
  16244. // Rebuild the media array in the right order and add the missing mLines
  16245. // (missing from the Plan B SDP).
  16246. session.media = [];
  16247. mids = []; // reuse
  16248. if (desc.type === 'answer') {
  16249. // The media lines in the answer must match the media lines in the
  16250. // offer. The order is important too. Here we assume that Firefox is the
  16251. // answerer, so we merely have to use the reconstructed (unified) answer
  16252. // to update the cached (unified) answer accordingly.
  16253. //
  16254. // In the general case, one would have to use the cached (unified) offer
  16255. // to find the m-lines that are missing from the reconstructed answer,
  16256. // potentially grabbing them from the cached (unified) answer. One has
  16257. // to be carefull with this approach because inactive m-lines do not
  16258. // always have an mid, making it tricky (impossible?) to find where
  16259. // exactly and which m-lines are missing from the reconstructed answer.
  16260. for (var i = 0; i < cached.media.length; i++) {
  16261. var unifiedLine = cached.media[i];
  16262. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  16263. // The mid isn't in the reconstructed (unified) answer.
  16264. // This is either a (unified) m-line containing a remote
  16265. // track only, or a (unified) m-line containing a remote
  16266. // track and a local track that has been removed.
  16267. // In either case, it MUST exist in the cached
  16268. // (unified) answer.
  16269. //
  16270. // In case this is a removed local track, clean-up
  16271. // the (unified) m-line and make sure it's 'recvonly' or
  16272. // 'inactive'.
  16273. delete unifiedLine.msid;
  16274. delete unifiedLine.sources;
  16275. delete unifiedLine.ssrcGroups;
  16276. if (!unifiedLine.direction
  16277. || unifiedLine.direction === 'sendrecv')
  16278. unifiedLine.direction = 'recvonly';
  16279. if (!unifiedLine.direction
  16280. || unifiedLine.direction === 'sendonly')
  16281. unifiedLine.direction = 'inactive';
  16282. } else {
  16283. // This is an (unified) m-line/channel that contains a local
  16284. // track (sendrecv or sendonly channel) or it's a unified
  16285. // recvonly m-line/channel. In either case, since we're
  16286. // going from PlanB -> Unified Plan this m-line MUST
  16287. // exist in the cached answer.
  16288. }
  16289. session.media.push(unifiedLine);
  16290. if (typeof unifiedLine.mid === 'string') {
  16291. // inactive lines don't/may not have an mid.
  16292. mids.push(unifiedLine.mid);
  16293. }
  16294. }
  16295. } else {
  16296. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  16297. // under any circumstances. If we are no longer interested in sending a
  16298. // track, we just remove the msid and ssrc attributes and set it to
  16299. // either a=recvonly (as the reofferer, we must use recvonly if the
  16300. // other side was previously sending on the m-section, but we can also
  16301. // leave the possibility open if it wasn't previously in use), or
  16302. // a=inacive.
  16303. if (typeof cached !== 'undefined' &&
  16304. typeof cached.media !== 'undefined' &&
  16305. Array.isArray(cached.media)) {
  16306. cached.media.forEach(function(unifiedLine) {
  16307. mids.push(unifiedLine.mid);
  16308. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  16309. session.media.push(mid2ul[unifiedLine.mid]);
  16310. } else {
  16311. delete unifiedLine.msid;
  16312. delete unifiedLine.sources;
  16313. delete unifiedLine.ssrcGroups;
  16314. if (!unifiedLine.direction
  16315. || unifiedLine.direction === 'sendrecv')
  16316. unifiedLine.direction = 'recvonly';
  16317. if (!unifiedLine.direction
  16318. || unifiedLine.direction === 'sendonly')
  16319. unifiedLine.direction = 'inactive';
  16320. session.media.push(unifiedLine);
  16321. }
  16322. });
  16323. }
  16324. // Add all the remaining (new) m-lines of the transformed SDP.
  16325. Object.keys(mid2ul).forEach(function(mid) {
  16326. if (mids.indexOf(mid) === -1) {
  16327. mids.push(mid);
  16328. if (typeof mid2ul[mid].direction === 'recvonly') {
  16329. // This is a remote recvonly channel. Add its SSRC to the
  16330. // appropriate sendrecv or sendonly channel.
  16331. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  16332. session.media.some(function (unifiedLine) {
  16333. if ((unifiedLine.direction === 'sendrecv' ||
  16334. unifiedLine.direction === 'sendonly') &&
  16335. unifiedLine.type === mid2ul[mid].type) {
  16336. // mid2ul[mid] shouldn't have any ssrc-groups
  16337. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  16338. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  16339. });
  16340. return true;
  16341. }
  16342. });
  16343. } else {
  16344. session.media.push(mid2ul[mid]);
  16345. }
  16346. }
  16347. });
  16348. }
  16349. // We regenerate the BUNDLE group (since we regenerated the mids)
  16350. session.groups.some(function(group) {
  16351. if (group.type === 'BUNDLE') {
  16352. group.mids = mids.join(' ');
  16353. return true;
  16354. }
  16355. });
  16356. // msid semantic
  16357. session.msidSemantic = {
  16358. semantic: 'WMS',
  16359. token: '*'
  16360. };
  16361. var resStr = transform.write(session);
  16362. // Cache the transformed SDP (Unified Plan) for later re-use in this
  16363. // function.
  16364. this.cache[desc.type] = resStr;
  16365. return new RTCSessionDescription({
  16366. type: desc.type,
  16367. sdp: resStr
  16368. });
  16369. //#endregion
  16370. };
  16371. },{"./array-equals":52,"./transform":55}],55:[function(require,module,exports){
  16372. var transform = require('sdp-transform');
  16373. exports.write = function(session, opts) {
  16374. if (typeof session !== 'undefined' &&
  16375. typeof session.media !== 'undefined' &&
  16376. Array.isArray(session.media)) {
  16377. session.media.forEach(function (mLine) {
  16378. // expand sources to ssrcs
  16379. if (typeof mLine.sources !== 'undefined' &&
  16380. Object.keys(mLine.sources).length !== 0) {
  16381. mLine.ssrcs = [];
  16382. Object.keys(mLine.sources).forEach(function (ssrc) {
  16383. var source = mLine.sources[ssrc];
  16384. Object.keys(source).forEach(function (attribute) {
  16385. mLine.ssrcs.push({
  16386. id: ssrc,
  16387. attribute: attribute,
  16388. value: source[attribute]
  16389. });
  16390. });
  16391. });
  16392. delete mLine.sources;
  16393. }
  16394. // join ssrcs in ssrc groups
  16395. if (typeof mLine.ssrcGroups !== 'undefined' &&
  16396. Array.isArray(mLine.ssrcGroups)) {
  16397. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  16398. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  16399. Array.isArray(ssrcGroup.ssrcs)) {
  16400. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  16401. }
  16402. });
  16403. }
  16404. });
  16405. }
  16406. // join group mids
  16407. if (typeof session !== 'undefined' &&
  16408. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  16409. session.groups.forEach(function (g) {
  16410. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  16411. g.mids = g.mids.join(' ');
  16412. }
  16413. });
  16414. }
  16415. return transform.write(session, opts);
  16416. };
  16417. exports.parse = function(sdp) {
  16418. var session = transform.parse(sdp);
  16419. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  16420. Array.isArray(session.media)) {
  16421. session.media.forEach(function (mLine) {
  16422. // group sources attributes by ssrc
  16423. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  16424. mLine.sources = {};
  16425. mLine.ssrcs.forEach(function (ssrc) {
  16426. if (!mLine.sources[ssrc.id])
  16427. mLine.sources[ssrc.id] = {};
  16428. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  16429. });
  16430. delete mLine.ssrcs;
  16431. }
  16432. // split ssrcs in ssrc groups
  16433. if (typeof mLine.ssrcGroups !== 'undefined' &&
  16434. Array.isArray(mLine.ssrcGroups)) {
  16435. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  16436. if (typeof ssrcGroup.ssrcs === 'string') {
  16437. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  16438. }
  16439. });
  16440. }
  16441. });
  16442. }
  16443. // split group mids
  16444. if (typeof session !== 'undefined' &&
  16445. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  16446. session.groups.forEach(function (g) {
  16447. if (typeof g.mids === 'string') {
  16448. g.mids = g.mids.split(' ');
  16449. }
  16450. });
  16451. }
  16452. return session;
  16453. };
  16454. },{"sdp-transform":57}],56:[function(require,module,exports){
  16455. var grammar = module.exports = {
  16456. v: [{
  16457. name: 'version',
  16458. reg: /^(\d*)$/
  16459. }],
  16460. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  16461. // NB: sessionId will be a String in most cases because it is huge
  16462. name: 'origin',
  16463. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  16464. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  16465. format: "%s %s %d %s IP%d %s"
  16466. }],
  16467. // default parsing of these only (though some of these feel outdated)
  16468. s: [{ name: 'name' }],
  16469. i: [{ name: 'description' }],
  16470. u: [{ name: 'uri' }],
  16471. e: [{ name: 'email' }],
  16472. p: [{ name: 'phone' }],
  16473. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  16474. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  16475. //k: [{}], // outdated thing ignored
  16476. t: [{ //t=0 0
  16477. name: 'timing',
  16478. reg: /^(\d*) (\d*)/,
  16479. names: ['start', 'stop'],
  16480. format: "%d %d"
  16481. }],
  16482. c: [{ //c=IN IP4 10.47.197.26
  16483. name: 'connection',
  16484. reg: /^IN IP(\d) (\S*)/,
  16485. names: ['version', 'ip'],
  16486. format: "IN IP%d %s"
  16487. }],
  16488. b: [{ //b=AS:4000
  16489. push: 'bandwidth',
  16490. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  16491. names: ['type', 'limit'],
  16492. format: "%s:%s"
  16493. }],
  16494. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  16495. // NB: special - pushes to session
  16496. // TODO: rtp/fmtp should be filtered by the payloads found here?
  16497. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  16498. names: ['type', 'port', 'protocol', 'payloads'],
  16499. format: "%s %d %s %s"
  16500. }],
  16501. a: [
  16502. { //a=rtpmap:110 opus/48000/2
  16503. push: 'rtp',
  16504. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  16505. names: ['payload', 'codec', 'rate', 'encoding'],
  16506. format: function (o) {
  16507. return (o.encoding) ?
  16508. "rtpmap:%d %s/%s/%s":
  16509. "rtpmap:%d %s/%s";
  16510. }
  16511. },
  16512. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  16513. push: 'fmtp',
  16514. reg: /^fmtp:(\d*) (\S*)/,
  16515. names: ['payload', 'config'],
  16516. format: "fmtp:%d %s"
  16517. },
  16518. { //a=control:streamid=0
  16519. name: 'control',
  16520. reg: /^control:(.*)/,
  16521. format: "control:%s"
  16522. },
  16523. { //a=rtcp:65179 IN IP4 193.84.77.194
  16524. name: 'rtcp',
  16525. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  16526. names: ['port', 'netType', 'ipVer', 'address'],
  16527. format: function (o) {
  16528. return (o.address != null) ?
  16529. "rtcp:%d %s IP%d %s":
  16530. "rtcp:%d";
  16531. }
  16532. },
  16533. { //a=rtcp-fb:98 trr-int 100
  16534. push: 'rtcpFbTrrInt',
  16535. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  16536. names: ['payload', 'value'],
  16537. format: "rtcp-fb:%d trr-int %d"
  16538. },
  16539. { //a=rtcp-fb:98 nack rpsi
  16540. push: 'rtcpFb',
  16541. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  16542. names: ['payload', 'type', 'subtype'],
  16543. format: function (o) {
  16544. return (o.subtype != null) ?
  16545. "rtcp-fb:%s %s %s":
  16546. "rtcp-fb:%s %s";
  16547. }
  16548. },
  16549. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  16550. //a=extmap:1/recvonly URI-gps-string
  16551. push: 'ext',
  16552. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  16553. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  16554. format: function (o) {
  16555. return (o.config != null) ?
  16556. "extmap:%s %s %s":
  16557. "extmap:%s %s";
  16558. }
  16559. },
  16560. {
  16561. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  16562. push: 'crypto',
  16563. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  16564. names: ['id', 'suite', 'config', 'sessionConfig'],
  16565. format: function (o) {
  16566. return (o.sessionConfig != null) ?
  16567. "crypto:%d %s %s %s":
  16568. "crypto:%d %s %s";
  16569. }
  16570. },
  16571. { //a=setup:actpass
  16572. name: 'setup',
  16573. reg: /^setup:(\w*)/,
  16574. format: "setup:%s"
  16575. },
  16576. { //a=mid:1
  16577. name: 'mid',
  16578. reg: /^mid:([^\s]*)/,
  16579. format: "mid:%s"
  16580. },
  16581. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  16582. name: 'msid',
  16583. reg: /^msid:(.*)/,
  16584. format: "msid:%s"
  16585. },
  16586. { //a=ptime:20
  16587. name: 'ptime',
  16588. reg: /^ptime:(\d*)/,
  16589. format: "ptime:%d"
  16590. },
  16591. { //a=maxptime:60
  16592. name: 'maxptime',
  16593. reg: /^maxptime:(\d*)/,
  16594. format: "maxptime:%d"
  16595. },
  16596. { //a=sendrecv
  16597. name: 'direction',
  16598. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  16599. },
  16600. { //a=ice-lite
  16601. name: 'icelite',
  16602. reg: /^(ice-lite)/
  16603. },
  16604. { //a=ice-ufrag:F7gI
  16605. name: 'iceUfrag',
  16606. reg: /^ice-ufrag:(\S*)/,
  16607. format: "ice-ufrag:%s"
  16608. },
  16609. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  16610. name: 'icePwd',
  16611. reg: /^ice-pwd:(\S*)/,
  16612. format: "ice-pwd:%s"
  16613. },
  16614. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  16615. name: 'fingerprint',
  16616. reg: /^fingerprint:(\S*) (\S*)/,
  16617. names: ['type', 'hash'],
  16618. format: "fingerprint:%s %s"
  16619. },
  16620. {
  16621. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  16622. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  16623. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  16624. push:'candidates',
  16625. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  16626. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  16627. format: function (o) {
  16628. var str = "candidate:%s %d %s %d %s %d typ %s";
  16629. // NB: candidate has two optional chunks, so %void middle one if it's missing
  16630. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  16631. if (o.generation != null) {
  16632. str += " generation %d";
  16633. }
  16634. return str;
  16635. }
  16636. },
  16637. { //a=end-of-candidates (keep after the candidates line for readability)
  16638. name: 'endOfCandidates',
  16639. reg: /^(end-of-candidates)/
  16640. },
  16641. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  16642. name: 'remoteCandidates',
  16643. reg: /^remote-candidates:(.*)/,
  16644. format: "remote-candidates:%s"
  16645. },
  16646. { //a=ice-options:google-ice
  16647. name: 'iceOptions',
  16648. reg: /^ice-options:(\S*)/,
  16649. format: "ice-options:%s"
  16650. },
  16651. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  16652. push: "ssrcs",
  16653. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  16654. names: ['id', 'attribute', 'value'],
  16655. format: "ssrc:%d %s:%s"
  16656. },
  16657. { //a=ssrc-group:FEC 1 2
  16658. push: "ssrcGroups",
  16659. reg: /^ssrc-group:(\w*) (.*)/,
  16660. names: ['semantics', 'ssrcs'],
  16661. format: "ssrc-group:%s %s"
  16662. },
  16663. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  16664. name: "msidSemantic",
  16665. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  16666. names: ['semantic', 'token'],
  16667. format: "msid-semantic: %s %s" // space after ":" is not accidental
  16668. },
  16669. { //a=group:BUNDLE audio video
  16670. push: 'groups',
  16671. reg: /^group:(\w*) (.*)/,
  16672. names: ['type', 'mids'],
  16673. format: "group:%s %s"
  16674. },
  16675. { //a=rtcp-mux
  16676. name: 'rtcpMux',
  16677. reg: /^(rtcp-mux)/
  16678. },
  16679. { //a=rtcp-rsize
  16680. name: 'rtcpRsize',
  16681. reg: /^(rtcp-rsize)/
  16682. },
  16683. { // any a= that we don't understand is kepts verbatim on media.invalid
  16684. push: 'invalid',
  16685. names: ["value"]
  16686. }
  16687. ]
  16688. };
  16689. // set sensible defaults to avoid polluting the grammar with boring details
  16690. Object.keys(grammar).forEach(function (key) {
  16691. var objs = grammar[key];
  16692. objs.forEach(function (obj) {
  16693. if (!obj.reg) {
  16694. obj.reg = /(.*)/;
  16695. }
  16696. if (!obj.format) {
  16697. obj.format = "%s";
  16698. }
  16699. });
  16700. });
  16701. },{}],57:[function(require,module,exports){
  16702. var parser = require('./parser');
  16703. var writer = require('./writer');
  16704. exports.write = writer;
  16705. exports.parse = parser.parse;
  16706. exports.parseFmtpConfig = parser.parseFmtpConfig;
  16707. exports.parsePayloads = parser.parsePayloads;
  16708. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  16709. },{"./parser":58,"./writer":59}],58:[function(require,module,exports){
  16710. var toIntIfInt = function (v) {
  16711. return String(Number(v)) === v ? Number(v) : v;
  16712. };
  16713. var attachProperties = function (match, location, names, rawName) {
  16714. if (rawName && !names) {
  16715. location[rawName] = toIntIfInt(match[1]);
  16716. }
  16717. else {
  16718. for (var i = 0; i < names.length; i += 1) {
  16719. if (match[i+1] != null) {
  16720. location[names[i]] = toIntIfInt(match[i+1]);
  16721. }
  16722. }
  16723. }
  16724. };
  16725. var parseReg = function (obj, location, content) {
  16726. var needsBlank = obj.name && obj.names;
  16727. if (obj.push && !location[obj.push]) {
  16728. location[obj.push] = [];
  16729. }
  16730. else if (needsBlank && !location[obj.name]) {
  16731. location[obj.name] = {};
  16732. }
  16733. var keyLocation = obj.push ?
  16734. {} : // blank object that will be pushed
  16735. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  16736. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  16737. if (obj.push) {
  16738. location[obj.push].push(keyLocation);
  16739. }
  16740. };
  16741. var grammar = require('./grammar');
  16742. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  16743. exports.parse = function (sdp) {
  16744. var session = {}
  16745. , media = []
  16746. , location = session; // points at where properties go under (one of the above)
  16747. // parse lines we understand
  16748. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  16749. var type = l[0];
  16750. var content = l.slice(2);
  16751. if (type === 'm') {
  16752. media.push({rtp: [], fmtp: []});
  16753. location = media[media.length-1]; // point at latest media line
  16754. }
  16755. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  16756. var obj = grammar[type][j];
  16757. if (obj.reg.test(content)) {
  16758. return parseReg(obj, location, content);
  16759. }
  16760. }
  16761. });
  16762. session.media = media; // link it up
  16763. return session;
  16764. };
  16765. var fmtpReducer = function (acc, expr) {
  16766. var s = expr.split('=');
  16767. if (s.length === 2) {
  16768. acc[s[0]] = toIntIfInt(s[1]);
  16769. }
  16770. return acc;
  16771. };
  16772. exports.parseFmtpConfig = function (str) {
  16773. return str.split(';').reduce(fmtpReducer, {});
  16774. };
  16775. exports.parsePayloads = function (str) {
  16776. return str.split(' ').map(Number);
  16777. };
  16778. exports.parseRemoteCandidates = function (str) {
  16779. var candidates = [];
  16780. var parts = str.split(' ').map(toIntIfInt);
  16781. for (var i = 0; i < parts.length; i += 3) {
  16782. candidates.push({
  16783. component: parts[i],
  16784. ip: parts[i + 1],
  16785. port: parts[i + 2]
  16786. });
  16787. }
  16788. return candidates;
  16789. };
  16790. },{"./grammar":56}],59:[function(require,module,exports){
  16791. var grammar = require('./grammar');
  16792. // customized util.format - discards excess arguments and can void middle ones
  16793. var formatRegExp = /%[sdv%]/g;
  16794. var format = function (formatStr) {
  16795. var i = 1;
  16796. var args = arguments;
  16797. var len = args.length;
  16798. return formatStr.replace(formatRegExp, function (x) {
  16799. if (i >= len) {
  16800. return x; // missing argument
  16801. }
  16802. var arg = args[i];
  16803. i += 1;
  16804. switch (x) {
  16805. case '%%':
  16806. return '%';
  16807. case '%s':
  16808. return String(arg);
  16809. case '%d':
  16810. return Number(arg);
  16811. case '%v':
  16812. return '';
  16813. }
  16814. });
  16815. // NB: we discard excess arguments - they are typically undefined from makeLine
  16816. };
  16817. var makeLine = function (type, obj, location) {
  16818. var str = obj.format instanceof Function ?
  16819. (obj.format(obj.push ? location : location[obj.name])) :
  16820. obj.format;
  16821. var args = [type + '=' + str];
  16822. if (obj.names) {
  16823. for (var i = 0; i < obj.names.length; i += 1) {
  16824. var n = obj.names[i];
  16825. if (obj.name) {
  16826. args.push(location[obj.name][n]);
  16827. }
  16828. else { // for mLine and push attributes
  16829. args.push(location[obj.names[i]]);
  16830. }
  16831. }
  16832. }
  16833. else {
  16834. args.push(location[obj.name]);
  16835. }
  16836. return format.apply(null, args);
  16837. };
  16838. // RFC specified order
  16839. // TODO: extend this with all the rest
  16840. var defaultOuterOrder = [
  16841. 'v', 'o', 's', 'i',
  16842. 'u', 'e', 'p', 'c',
  16843. 'b', 't', 'r', 'z', 'a'
  16844. ];
  16845. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  16846. module.exports = function (session, opts) {
  16847. opts = opts || {};
  16848. // ensure certain properties exist
  16849. if (session.version == null) {
  16850. session.version = 0; // "v=0" must be there (only defined version atm)
  16851. }
  16852. if (session.name == null) {
  16853. session.name = " "; // "s= " must be there if no meaningful name set
  16854. }
  16855. session.media.forEach(function (mLine) {
  16856. if (mLine.payloads == null) {
  16857. mLine.payloads = "";
  16858. }
  16859. });
  16860. var outerOrder = opts.outerOrder || defaultOuterOrder;
  16861. var innerOrder = opts.innerOrder || defaultInnerOrder;
  16862. var sdp = [];
  16863. // loop through outerOrder for matching properties on session
  16864. outerOrder.forEach(function (type) {
  16865. grammar[type].forEach(function (obj) {
  16866. if (obj.name in session && session[obj.name] != null) {
  16867. sdp.push(makeLine(type, obj, session));
  16868. }
  16869. else if (obj.push in session && session[obj.push] != null) {
  16870. session[obj.push].forEach(function (el) {
  16871. sdp.push(makeLine(type, obj, el));
  16872. });
  16873. }
  16874. });
  16875. });
  16876. // then for each media line, follow the innerOrder
  16877. session.media.forEach(function (mLine) {
  16878. sdp.push(makeLine('m', grammar.m[0], mLine));
  16879. innerOrder.forEach(function (type) {
  16880. grammar[type].forEach(function (obj) {
  16881. if (obj.name in mLine && mLine[obj.name] != null) {
  16882. sdp.push(makeLine(type, obj, mLine));
  16883. }
  16884. else if (obj.push in mLine && mLine[obj.push] != null) {
  16885. mLine[obj.push].forEach(function (el) {
  16886. sdp.push(makeLine(type, obj, el));
  16887. });
  16888. }
  16889. });
  16890. });
  16891. });
  16892. return sdp.join('\r\n') + '\r\n';
  16893. };
  16894. },{"./grammar":56}],60:[function(require,module,exports){
  16895. var transform = require('sdp-transform');
  16896. var transformUtils = require('./transform-utils');
  16897. var parseSsrcs = transformUtils.parseSsrcs;
  16898. var writeSsrcs = transformUtils.writeSsrcs;
  16899. //region Constants
  16900. var DEFAULT_NUM_OF_LAYERS = 3;
  16901. //endregion
  16902. //region Ctor
  16903. function Simulcast(options) {
  16904. this.options = options ? options : {};
  16905. if (!this.options.numOfLayers) {
  16906. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  16907. }
  16908. this.layers = [];
  16909. }
  16910. //endregion
  16911. //region Stateless private utility functions
  16912. /**
  16913. * Returns a random integer between min (included) and max (excluded)
  16914. * Using Math.round() gives a non-uniform distribution!
  16915. * @returns {number}
  16916. */
  16917. function generateSSRC() {
  16918. var min = 0, max = 0xffffffff;
  16919. return Math.floor(Math.random() * (max - min)) + min;
  16920. };
  16921. function processVideo(session, action) {
  16922. if (session == null || !Array.isArray(session.media)) {
  16923. return;
  16924. }
  16925. session.media.forEach(function (mLine) {
  16926. if (mLine.type === 'video') {
  16927. action(mLine);
  16928. }
  16929. });
  16930. }
  16931. function validateDescription(desc)
  16932. {
  16933. return desc && desc != null
  16934. && desc.type && desc.type != ''
  16935. && desc.sdp && desc.sdp != '';
  16936. }
  16937. function explodeRemoteSimulcast(mLine) {
  16938. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  16939. return;
  16940. }
  16941. var sources = parseSsrcs(mLine);
  16942. var order = [];
  16943. // Find the SIM group and explode its sources.
  16944. var j = mLine.ssrcGroups.length;
  16945. while (j--) {
  16946. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  16947. continue;
  16948. }
  16949. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  16950. for (var i = 0; i < simulcastSsrcs.length; i++) {
  16951. var ssrc = simulcastSsrcs[i];
  16952. order.push(ssrc);
  16953. var parts = sources[ssrc].msid.split(' ');
  16954. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  16955. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  16956. // Remove all the groups that this SSRC participates in.
  16957. mLine.ssrcGroups.forEach(function (relatedGroup) {
  16958. if (relatedGroup.semantics === 'SIM') {
  16959. return;
  16960. }
  16961. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  16962. if (relatedSsrcs.indexOf(ssrc) === -1) {
  16963. return;
  16964. }
  16965. // Nuke all the related SSRCs.
  16966. relatedSsrcs.forEach(function (relatedSSRC) {
  16967. sources[relatedSSRC].msid = sources[ssrc].msid;
  16968. sources[relatedSSRC].cname = sources[ssrc].cname;
  16969. if (relatedSSRC !== ssrc) {
  16970. order.push(relatedSSRC);
  16971. }
  16972. });
  16973. // Schedule the related group for nuking.
  16974. })
  16975. }
  16976. mLine.ssrcs = writeSsrcs(sources, order);
  16977. mLine.ssrcGroups.splice(j, 1);
  16978. };
  16979. }
  16980. function squeezeRemoteSimulcast(mLine) {
  16981. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  16982. return;
  16983. }
  16984. var sources = parseSsrcs(mLine);
  16985. // Find the SIM group and nuke it.
  16986. mLine.ssrcGroups.some(function (simulcastGroup) {
  16987. if (simulcastGroup.semantics !== 'SIM') {
  16988. return false;
  16989. }
  16990. // Schedule the SIM group for nuking.
  16991. simulcastGroup.nuke = true;
  16992. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  16993. // Nuke all the higher layer SSRCs.
  16994. for (var i = 1; i < simulcastSsrcs.length; i++) {
  16995. var ssrc = simulcastSsrcs[i];
  16996. delete sources[ssrc];
  16997. // Remove all the groups that this SSRC participates in.
  16998. mLine.ssrcGroups.forEach(function (relatedGroup) {
  16999. if (relatedGroup.semantics === 'SIM') {
  17000. return;
  17001. }
  17002. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  17003. if (relatedSsrcs.indexOf(ssrc) === -1) {
  17004. return;
  17005. }
  17006. // Nuke all the related SSRCs.
  17007. relatedSsrcs.forEach(function (relatedSSRC) {
  17008. delete sources[relatedSSRC];
  17009. });
  17010. // Schedule the related group for nuking.
  17011. relatedGroup.nuke = true;
  17012. })
  17013. }
  17014. return true;
  17015. });
  17016. mLine.ssrcs = writeSsrcs(sources);
  17017. // Nuke all the scheduled groups.
  17018. var i = mLine.ssrcGroups.length;
  17019. while (i--) {
  17020. if (mLine.ssrcGroups[i].nuke) {
  17021. mLine.ssrcGroups.splice(i, 1);
  17022. }
  17023. }
  17024. }
  17025. function removeGoogConference(mLine) {
  17026. if (!mLine || !Array.isArray(mLine.invalid)) {
  17027. return;
  17028. }
  17029. var i = mLine.invalid.length;
  17030. while (i--) {
  17031. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  17032. mLine.invalid.splice(i, 1);
  17033. }
  17034. }
  17035. }
  17036. function assertGoogConference(mLine) {
  17037. if (!mLine) {
  17038. return;
  17039. }
  17040. if (!Array.isArray(mLine.invalid)) {
  17041. mLine.invalid = [];
  17042. }
  17043. if (!mLine.invalid.some(
  17044. function (i) { return i.value === 'x-google-flag:conference' })) {
  17045. mLine.invalid.push({'value': 'x-google-flag:conference'});
  17046. }
  17047. }
  17048. //endregion
  17049. //region "Private" functions
  17050. /**
  17051. *
  17052. * @param mLine
  17053. * @private
  17054. */
  17055. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  17056. if (!mLine || mLine.type !== 'video') {
  17057. return;
  17058. }
  17059. var sources = parseSsrcs(mLine);
  17060. if (Object.keys(sources).length === 0) {
  17061. // no sources, disable simulcast.
  17062. if (this.layers.length !== 0) {
  17063. this.layers = [];
  17064. }
  17065. return;
  17066. }
  17067. // find the base layer (we'll reuse its msid and cname).
  17068. var baseLayerSSRC = Object.keys(sources)[0];
  17069. var baseLayer = sources[baseLayerSSRC];
  17070. // todo(gp) handle screen sharing.
  17071. // check if base CNAME has changed and reinitialise layers.
  17072. if (this.layers.length > 0
  17073. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  17074. this.layers = [];
  17075. }
  17076. // (re)initialise layers
  17077. if (this.layers.length < 1) {
  17078. // first push the base layer.
  17079. this.layers.push({
  17080. ssrc: baseLayerSSRC,
  17081. msid: baseLayer.msid,
  17082. cname: baseLayer.cname
  17083. });
  17084. var rtx = false; // RFC 4588
  17085. if (Array.isArray(mLine.rtp)) {
  17086. rtx = mLine.rtp.some(
  17087. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  17088. }
  17089. if (rtx) {
  17090. this.layers[0].rtx = generateSSRC();
  17091. }
  17092. // now push additional layers.
  17093. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  17094. var layer = { ssrc: generateSSRC() };
  17095. if (rtx) {
  17096. layer.rtx = generateSSRC();
  17097. }
  17098. this.layers.push(layer);
  17099. }
  17100. }
  17101. };
  17102. /**
  17103. *
  17104. * @param mLine
  17105. * @private
  17106. */
  17107. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  17108. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  17109. var sources = {};
  17110. var msid = this.layers[0].msid;
  17111. var cname = this.layers[0].cname;
  17112. var simulcastSsrcs = [];
  17113. var ssrcGroups = [];
  17114. for (var i = 0; i < this.layers.length; i++) {
  17115. var layer = this.layers[i];
  17116. sources[layer.ssrc] = { msid: msid, cname: cname };
  17117. simulcastSsrcs.push(layer.ssrc);
  17118. if (layer.rtx) {
  17119. sources[layer.rtx] = {
  17120. msid: msid,
  17121. cname: cname
  17122. }
  17123. ssrcGroups.push({
  17124. semantics: 'FID',
  17125. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  17126. });
  17127. }
  17128. }
  17129. ssrcGroups.push({
  17130. semantics: 'SIM',
  17131. ssrcs: simulcastSsrcs.join(' ')
  17132. });
  17133. mLine.ssrcGroups = ssrcGroups;
  17134. mLine.ssrcs = writeSsrcs(sources);
  17135. }
  17136. }
  17137. //endregion
  17138. //region "Public" functions
  17139. Simulcast.prototype.isSupported = function () {
  17140. return window.chrome;
  17141. // TODO this needs improvements. For example I doubt that Chrome in Android
  17142. // has simulcast support. Also, only recent versions of Chromium have native
  17143. // simulcast support.
  17144. }
  17145. /**
  17146. *
  17147. * @param desc
  17148. * @returns {RTCSessionDescription}
  17149. */
  17150. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  17151. if (!validateDescription(desc)) {
  17152. return desc;
  17153. }
  17154. var session = transform.parse(desc.sdp);
  17155. var self = this;
  17156. processVideo(session, function (mLine) {
  17157. // Handle simulcast reception.
  17158. if (self.options.explodeRemoteSimulcast) {
  17159. explodeRemoteSimulcast(mLine);
  17160. } else {
  17161. squeezeRemoteSimulcast(mLine);
  17162. }
  17163. // If native simulcast is enabled, we must append the x-goog-conference
  17164. // attribute to the SDP.
  17165. if (self.layers.length < 1) {
  17166. removeGoogConference(mLine);
  17167. } else {
  17168. assertGoogConference(mLine);
  17169. }
  17170. });
  17171. return new RTCSessionDescription({
  17172. type: desc.type,
  17173. sdp: transform.write(session)
  17174. });
  17175. };
  17176. /**
  17177. *
  17178. * @param desc
  17179. * @returns {RTCSessionDescription}
  17180. */
  17181. Simulcast.prototype.mungeLocalDescription = function (desc) {
  17182. if (!validateDescription(desc) || !this.isSupported()) {
  17183. return desc;
  17184. }
  17185. var session = transform.parse(desc.sdp);
  17186. var self = this;
  17187. processVideo(session, function (mLine) {
  17188. // Initialize native simulcast layers, if not already done.
  17189. self._maybeInitializeLayers(mLine);
  17190. // Update the SDP with the simulcast layers.
  17191. self._restoreSimulcastView(mLine);
  17192. });
  17193. return new RTCSessionDescription({
  17194. type: desc.type,
  17195. sdp: transform.write(session)
  17196. });
  17197. };
  17198. //endregion
  17199. module.exports = Simulcast;
  17200. },{"./transform-utils":61,"sdp-transform":63}],61:[function(require,module,exports){
  17201. exports.writeSsrcs = function(sources, order) {
  17202. var ssrcs = [];
  17203. // expand sources to ssrcs
  17204. if (typeof sources !== 'undefined' &&
  17205. Object.keys(sources).length !== 0) {
  17206. if (Array.isArray(order)) {
  17207. for (var i = 0; i < order.length; i++) {
  17208. var ssrc = order[i];
  17209. var source = sources[ssrc];
  17210. Object.keys(source).forEach(function (attribute) {
  17211. ssrcs.push({
  17212. id: ssrc,
  17213. attribute: attribute,
  17214. value: source[attribute]
  17215. });
  17216. });
  17217. }
  17218. } else {
  17219. Object.keys(sources).forEach(function (ssrc) {
  17220. var source = sources[ssrc];
  17221. Object.keys(source).forEach(function (attribute) {
  17222. ssrcs.push({
  17223. id: ssrc,
  17224. attribute: attribute,
  17225. value: source[attribute]
  17226. });
  17227. });
  17228. });
  17229. }
  17230. }
  17231. return ssrcs;
  17232. };
  17233. exports.parseSsrcs = function (mLine) {
  17234. var sources = {};
  17235. // group sources attributes by ssrc.
  17236. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  17237. mLine.ssrcs.forEach(function (ssrc) {
  17238. if (!sources[ssrc.id])
  17239. sources[ssrc.id] = {};
  17240. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  17241. });
  17242. }
  17243. return sources;
  17244. };
  17245. },{}],62:[function(require,module,exports){
  17246. arguments[4][56][0].apply(exports,arguments)
  17247. },{"dup":56}],63:[function(require,module,exports){
  17248. arguments[4][57][0].apply(exports,arguments)
  17249. },{"./parser":64,"./writer":65,"dup":57}],64:[function(require,module,exports){
  17250. arguments[4][58][0].apply(exports,arguments)
  17251. },{"./grammar":62,"dup":58}],65:[function(require,module,exports){
  17252. arguments[4][59][0].apply(exports,arguments)
  17253. },{"./grammar":62,"dup":59}],66:[function(require,module,exports){
  17254. var grammar = module.exports = {
  17255. v: [{
  17256. name: 'version',
  17257. reg: /^(\d*)$/
  17258. }],
  17259. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  17260. // NB: sessionId will be a String in most cases because it is huge
  17261. name: 'origin',
  17262. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  17263. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  17264. format: "%s %s %d %s IP%d %s"
  17265. }],
  17266. // default parsing of these only (though some of these feel outdated)
  17267. s: [{ name: 'name' }],
  17268. i: [{ name: 'description' }],
  17269. u: [{ name: 'uri' }],
  17270. e: [{ name: 'email' }],
  17271. p: [{ name: 'phone' }],
  17272. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  17273. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  17274. //k: [{}], // outdated thing ignored
  17275. t: [{ //t=0 0
  17276. name: 'timing',
  17277. reg: /^(\d*) (\d*)/,
  17278. names: ['start', 'stop'],
  17279. format: "%d %d"
  17280. }],
  17281. c: [{ //c=IN IP4 10.47.197.26
  17282. name: 'connection',
  17283. reg: /^IN IP(\d) (\S*)/,
  17284. names: ['version', 'ip'],
  17285. format: "IN IP%d %s"
  17286. }],
  17287. b: [{ //b=AS:4000
  17288. push: 'bandwidth',
  17289. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  17290. names: ['type', 'limit'],
  17291. format: "%s:%s"
  17292. }],
  17293. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  17294. // NB: special - pushes to session
  17295. // TODO: rtp/fmtp should be filtered by the payloads found here?
  17296. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  17297. names: ['type', 'port', 'protocol', 'payloads'],
  17298. format: "%s %d %s %s"
  17299. }],
  17300. a: [
  17301. { //a=rtpmap:110 opus/48000/2
  17302. push: 'rtp',
  17303. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  17304. names: ['payload', 'codec', 'rate', 'encoding'],
  17305. format: function (o) {
  17306. return (o.encoding) ?
  17307. "rtpmap:%d %s/%s/%s":
  17308. "rtpmap:%d %s/%s";
  17309. }
  17310. },
  17311. {
  17312. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  17313. //a=fmtp:111 minptime=10; useinbandfec=1
  17314. push: 'fmtp',
  17315. reg: /^fmtp:(\d*) ([\S| ]*)/,
  17316. names: ['payload', 'config'],
  17317. format: "fmtp:%d %s"
  17318. },
  17319. { //a=control:streamid=0
  17320. name: 'control',
  17321. reg: /^control:(.*)/,
  17322. format: "control:%s"
  17323. },
  17324. { //a=rtcp:65179 IN IP4 193.84.77.194
  17325. name: 'rtcp',
  17326. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  17327. names: ['port', 'netType', 'ipVer', 'address'],
  17328. format: function (o) {
  17329. return (o.address != null) ?
  17330. "rtcp:%d %s IP%d %s":
  17331. "rtcp:%d";
  17332. }
  17333. },
  17334. { //a=rtcp-fb:98 trr-int 100
  17335. push: 'rtcpFbTrrInt',
  17336. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  17337. names: ['payload', 'value'],
  17338. format: "rtcp-fb:%d trr-int %d"
  17339. },
  17340. { //a=rtcp-fb:98 nack rpsi
  17341. push: 'rtcpFb',
  17342. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  17343. names: ['payload', 'type', 'subtype'],
  17344. format: function (o) {
  17345. return (o.subtype != null) ?
  17346. "rtcp-fb:%s %s %s":
  17347. "rtcp-fb:%s %s";
  17348. }
  17349. },
  17350. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  17351. //a=extmap:1/recvonly URI-gps-string
  17352. push: 'ext',
  17353. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  17354. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  17355. format: function (o) {
  17356. return (o.config != null) ?
  17357. "extmap:%s %s %s":
  17358. "extmap:%s %s";
  17359. }
  17360. },
  17361. {
  17362. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  17363. push: 'crypto',
  17364. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  17365. names: ['id', 'suite', 'config', 'sessionConfig'],
  17366. format: function (o) {
  17367. return (o.sessionConfig != null) ?
  17368. "crypto:%d %s %s %s":
  17369. "crypto:%d %s %s";
  17370. }
  17371. },
  17372. { //a=setup:actpass
  17373. name: 'setup',
  17374. reg: /^setup:(\w*)/,
  17375. format: "setup:%s"
  17376. },
  17377. { //a=mid:1
  17378. name: 'mid',
  17379. reg: /^mid:([^\s]*)/,
  17380. format: "mid:%s"
  17381. },
  17382. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  17383. name: 'msid',
  17384. reg: /^msid:(.*)/,
  17385. format: "msid:%s"
  17386. },
  17387. { //a=ptime:20
  17388. name: 'ptime',
  17389. reg: /^ptime:(\d*)/,
  17390. format: "ptime:%d"
  17391. },
  17392. { //a=maxptime:60
  17393. name: 'maxptime',
  17394. reg: /^maxptime:(\d*)/,
  17395. format: "maxptime:%d"
  17396. },
  17397. { //a=sendrecv
  17398. name: 'direction',
  17399. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  17400. },
  17401. { //a=ice-lite
  17402. name: 'icelite',
  17403. reg: /^(ice-lite)/
  17404. },
  17405. { //a=ice-ufrag:F7gI
  17406. name: 'iceUfrag',
  17407. reg: /^ice-ufrag:(\S*)/,
  17408. format: "ice-ufrag:%s"
  17409. },
  17410. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  17411. name: 'icePwd',
  17412. reg: /^ice-pwd:(\S*)/,
  17413. format: "ice-pwd:%s"
  17414. },
  17415. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  17416. name: 'fingerprint',
  17417. reg: /^fingerprint:(\S*) (\S*)/,
  17418. names: ['type', 'hash'],
  17419. format: "fingerprint:%s %s"
  17420. },
  17421. {
  17422. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  17423. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  17424. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  17425. push:'candidates',
  17426. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  17427. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  17428. format: function (o) {
  17429. var str = "candidate:%s %d %s %d %s %d typ %s";
  17430. // NB: candidate has two optional chunks, so %void middle one if it's missing
  17431. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  17432. if (o.generation != null) {
  17433. str += " generation %d";
  17434. }
  17435. return str;
  17436. }
  17437. },
  17438. { //a=end-of-candidates (keep after the candidates line for readability)
  17439. name: 'endOfCandidates',
  17440. reg: /^(end-of-candidates)/
  17441. },
  17442. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  17443. name: 'remoteCandidates',
  17444. reg: /^remote-candidates:(.*)/,
  17445. format: "remote-candidates:%s"
  17446. },
  17447. { //a=ice-options:google-ice
  17448. name: 'iceOptions',
  17449. reg: /^ice-options:(\S*)/,
  17450. format: "ice-options:%s"
  17451. },
  17452. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  17453. push: "ssrcs",
  17454. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  17455. names: ['id', 'attribute', 'value'],
  17456. format: "ssrc:%d %s:%s"
  17457. },
  17458. { //a=ssrc-group:FEC 1 2
  17459. push: "ssrcGroups",
  17460. reg: /^ssrc-group:(\w*) (.*)/,
  17461. names: ['semantics', 'ssrcs'],
  17462. format: "ssrc-group:%s %s"
  17463. },
  17464. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  17465. name: "msidSemantic",
  17466. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  17467. names: ['semantic', 'token'],
  17468. format: "msid-semantic: %s %s" // space after ":" is not accidental
  17469. },
  17470. { //a=group:BUNDLE audio video
  17471. push: 'groups',
  17472. reg: /^group:(\w*) (.*)/,
  17473. names: ['type', 'mids'],
  17474. format: "group:%s %s"
  17475. },
  17476. { //a=rtcp-mux
  17477. name: 'rtcpMux',
  17478. reg: /^(rtcp-mux)/
  17479. },
  17480. { //a=rtcp-rsize
  17481. name: 'rtcpRsize',
  17482. reg: /^(rtcp-rsize)/
  17483. },
  17484. { // any a= that we don't understand is kepts verbatim on media.invalid
  17485. push: 'invalid',
  17486. names: ["value"]
  17487. }
  17488. ]
  17489. };
  17490. // set sensible defaults to avoid polluting the grammar with boring details
  17491. Object.keys(grammar).forEach(function (key) {
  17492. var objs = grammar[key];
  17493. objs.forEach(function (obj) {
  17494. if (!obj.reg) {
  17495. obj.reg = /(.*)/;
  17496. }
  17497. if (!obj.format) {
  17498. obj.format = "%s";
  17499. }
  17500. });
  17501. });
  17502. },{}],67:[function(require,module,exports){
  17503. arguments[4][57][0].apply(exports,arguments)
  17504. },{"./parser":68,"./writer":69,"dup":57}],68:[function(require,module,exports){
  17505. var toIntIfInt = function (v) {
  17506. return String(Number(v)) === v ? Number(v) : v;
  17507. };
  17508. var attachProperties = function (match, location, names, rawName) {
  17509. if (rawName && !names) {
  17510. location[rawName] = toIntIfInt(match[1]);
  17511. }
  17512. else {
  17513. for (var i = 0; i < names.length; i += 1) {
  17514. if (match[i+1] != null) {
  17515. location[names[i]] = toIntIfInt(match[i+1]);
  17516. }
  17517. }
  17518. }
  17519. };
  17520. var parseReg = function (obj, location, content) {
  17521. var needsBlank = obj.name && obj.names;
  17522. if (obj.push && !location[obj.push]) {
  17523. location[obj.push] = [];
  17524. }
  17525. else if (needsBlank && !location[obj.name]) {
  17526. location[obj.name] = {};
  17527. }
  17528. var keyLocation = obj.push ?
  17529. {} : // blank object that will be pushed
  17530. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  17531. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  17532. if (obj.push) {
  17533. location[obj.push].push(keyLocation);
  17534. }
  17535. };
  17536. var grammar = require('./grammar');
  17537. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  17538. exports.parse = function (sdp) {
  17539. var session = {}
  17540. , media = []
  17541. , location = session; // points at where properties go under (one of the above)
  17542. // parse lines we understand
  17543. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  17544. var type = l[0];
  17545. var content = l.slice(2);
  17546. if (type === 'm') {
  17547. media.push({rtp: [], fmtp: []});
  17548. location = media[media.length-1]; // point at latest media line
  17549. }
  17550. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  17551. var obj = grammar[type][j];
  17552. if (obj.reg.test(content)) {
  17553. return parseReg(obj, location, content);
  17554. }
  17555. }
  17556. });
  17557. session.media = media; // link it up
  17558. return session;
  17559. };
  17560. var fmtpReducer = function (acc, expr) {
  17561. var s = expr.split('=');
  17562. if (s.length === 2) {
  17563. acc[s[0]] = toIntIfInt(s[1]);
  17564. }
  17565. return acc;
  17566. };
  17567. exports.parseFmtpConfig = function (str) {
  17568. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  17569. };
  17570. exports.parsePayloads = function (str) {
  17571. return str.split(' ').map(Number);
  17572. };
  17573. exports.parseRemoteCandidates = function (str) {
  17574. var candidates = [];
  17575. var parts = str.split(' ').map(toIntIfInt);
  17576. for (var i = 0; i < parts.length; i += 3) {
  17577. candidates.push({
  17578. component: parts[i],
  17579. ip: parts[i + 1],
  17580. port: parts[i + 2]
  17581. });
  17582. }
  17583. return candidates;
  17584. };
  17585. },{"./grammar":66}],69:[function(require,module,exports){
  17586. arguments[4][59][0].apply(exports,arguments)
  17587. },{"./grammar":66,"dup":59}],70:[function(require,module,exports){
  17588. var MediaStreamType = {
  17589. VIDEO_TYPE: "Video",
  17590. AUDIO_TYPE: "Audio"
  17591. };
  17592. module.exports = MediaStreamType;
  17593. },{}],71:[function(require,module,exports){
  17594. var RTCEvents = {
  17595. RTC_READY: "rtc.ready",
  17596. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  17597. LASTN_CHANGED: "rtc.lastn_changed",
  17598. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  17599. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  17600. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  17601. };
  17602. module.exports = RTCEvents;
  17603. },{}],72:[function(require,module,exports){
  17604. var Resolutions = {
  17605. "1080": {
  17606. width: 1920,
  17607. height: 1080,
  17608. order: 7
  17609. },
  17610. "fullhd": {
  17611. width: 1920,
  17612. height: 1080,
  17613. order: 7
  17614. },
  17615. "720": {
  17616. width: 1280,
  17617. height: 720,
  17618. order: 6
  17619. },
  17620. "hd": {
  17621. width: 1280,
  17622. height: 720,
  17623. order: 6
  17624. },
  17625. "960": {
  17626. width: 960,
  17627. height: 720,
  17628. order: 5
  17629. },
  17630. "640": {
  17631. width: 640,
  17632. height: 480,
  17633. order: 4
  17634. },
  17635. "vga": {
  17636. width: 640,
  17637. height: 480,
  17638. order: 4
  17639. },
  17640. "360": {
  17641. width: 640,
  17642. height: 360,
  17643. order: 3
  17644. },
  17645. "320": {
  17646. width: 320,
  17647. height: 240,
  17648. order: 2
  17649. },
  17650. "180": {
  17651. width: 320,
  17652. height: 180,
  17653. order: 1
  17654. }
  17655. };
  17656. module.exports = Resolutions;
  17657. },{}],73:[function(require,module,exports){
  17658. var StreamEventTypes = {
  17659. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  17660. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  17661. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  17662. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  17663. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  17664. TRACK_MUTE_CHANGED: "rtc.track_mute_changed"
  17665. };
  17666. module.exports = StreamEventTypes;
  17667. },{}],74:[function(require,module,exports){
  17668. var AuthenticationEvents = {
  17669. /**
  17670. * Event callback arguments:
  17671. * function(authenticationEnabled, userIdentity)
  17672. * authenticationEnabled - indicates whether authentication has been enabled
  17673. * in this session
  17674. * userIdentity - if user has been logged in then it contains user name. If
  17675. * contains 'null' or 'undefined' then user is not logged in.
  17676. */
  17677. IDENTITY_UPDATED: "authentication.identity_updated"
  17678. };
  17679. module.exports = AuthenticationEvents;
  17680. },{}],75:[function(require,module,exports){
  17681. var DesktopSharingEventTypes = {
  17682. INIT: "ds.init",
  17683. SWITCHING_DONE: "ds.switching_done",
  17684. NEW_STREAM_CREATED: "ds.new_stream_created"
  17685. };
  17686. module.exports = DesktopSharingEventTypes;
  17687. },{}],76:[function(require,module,exports){
  17688. var XMPPEvents = {
  17689. CONNECTION_FAILED: "xmpp.connection.failed",
  17690. // Indicates an interrupted connection event.
  17691. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  17692. // Indicates a restored connection event.
  17693. CONNECTION_RESTORED: "xmpp.connection.restored",
  17694. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  17695. CALL_INCOMING: "xmpp.callincoming.jingle",
  17696. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  17697. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  17698. KICKED: "xmpp.kicked",
  17699. BRIDGE_DOWN: "xmpp.bridge_down",
  17700. USER_ID_CHANGED: "xmpp.user_id_changed",
  17701. // We joined the MUC
  17702. MUC_JOINED: "xmpp.muc_joined",
  17703. // A member joined the MUC
  17704. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  17705. // A member left the MUC
  17706. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  17707. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  17708. MUC_DESTROYED: "xmpp.muc_destroyed",
  17709. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  17710. REMOTE_STATS: "xmpp.remote_stats",
  17711. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  17712. PRESENCE_STATUS: "xmpp.presence_status",
  17713. RESERVATION_ERROR: "xmpp.room_reservation_error",
  17714. SUBJECT_CHANGED: "xmpp.subject_changed",
  17715. MESSAGE_RECEIVED: "xmpp.message_received",
  17716. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  17717. PASSWORD_REQUIRED: "xmpp.password_required",
  17718. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  17719. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  17720. ETHERPAD: "xmpp.etherpad",
  17721. DEVICE_AVAILABLE: "xmpp.device_available",
  17722. VIDEO_TYPE: "xmpp.video_type",
  17723. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  17724. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  17725. AUDIO_MUTED: "xmpp.audio_muted",
  17726. VIDEO_MUTED: "xmpp.video_muted",
  17727. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  17728. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  17729. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  17730. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  17731. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  17732. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  17733. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  17734. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  17735. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  17736. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  17737. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  17738. // xmpp is connected and obtained user media
  17739. READY_TO_JOIN: 'xmpp.ready_to_join',
  17740. FOCUS_LEFT: "xmpp.focus_left",
  17741. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received"
  17742. };
  17743. module.exports = XMPPEvents;
  17744. },{}],77:[function(require,module,exports){
  17745. // Copyright Joyent, Inc. and other Node contributors.
  17746. //
  17747. // Permission is hereby granted, free of charge, to any person obtaining a
  17748. // copy of this software and associated documentation files (the
  17749. // "Software"), to deal in the Software without restriction, including
  17750. // without limitation the rights to use, copy, modify, merge, publish,
  17751. // distribute, sublicense, and/or sell copies of the Software, and to permit
  17752. // persons to whom the Software is furnished to do so, subject to the
  17753. // following conditions:
  17754. //
  17755. // The above copyright notice and this permission notice shall be included
  17756. // in all copies or substantial portions of the Software.
  17757. //
  17758. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  17759. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17760. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  17761. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  17762. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  17763. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  17764. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  17765. function EventEmitter() {
  17766. this._events = this._events || {};
  17767. this._maxListeners = this._maxListeners || undefined;
  17768. }
  17769. module.exports = EventEmitter;
  17770. // Backwards-compat with node 0.10.x
  17771. EventEmitter.EventEmitter = EventEmitter;
  17772. EventEmitter.prototype._events = undefined;
  17773. EventEmitter.prototype._maxListeners = undefined;
  17774. // By default EventEmitters will print a warning if more than 10 listeners are
  17775. // added to it. This is a useful default which helps finding memory leaks.
  17776. EventEmitter.defaultMaxListeners = 10;
  17777. // Obviously not all Emitters should be limited to 10. This function allows
  17778. // that to be increased. Set to zero for unlimited.
  17779. EventEmitter.prototype.setMaxListeners = function(n) {
  17780. if (!isNumber(n) || n < 0 || isNaN(n))
  17781. throw TypeError('n must be a positive number');
  17782. this._maxListeners = n;
  17783. return this;
  17784. };
  17785. EventEmitter.prototype.emit = function(type) {
  17786. var er, handler, len, args, i, listeners;
  17787. if (!this._events)
  17788. this._events = {};
  17789. // If there is no 'error' event listener then throw.
  17790. if (type === 'error') {
  17791. if (!this._events.error ||
  17792. (isObject(this._events.error) && !this._events.error.length)) {
  17793. er = arguments[1];
  17794. if (er instanceof Error) {
  17795. throw er; // Unhandled 'error' event
  17796. }
  17797. throw TypeError('Uncaught, unspecified "error" event.');
  17798. }
  17799. }
  17800. handler = this._events[type];
  17801. if (isUndefined(handler))
  17802. return false;
  17803. if (isFunction(handler)) {
  17804. switch (arguments.length) {
  17805. // fast cases
  17806. case 1:
  17807. handler.call(this);
  17808. break;
  17809. case 2:
  17810. handler.call(this, arguments[1]);
  17811. break;
  17812. case 3:
  17813. handler.call(this, arguments[1], arguments[2]);
  17814. break;
  17815. // slower
  17816. default:
  17817. len = arguments.length;
  17818. args = new Array(len - 1);
  17819. for (i = 1; i < len; i++)
  17820. args[i - 1] = arguments[i];
  17821. handler.apply(this, args);
  17822. }
  17823. } else if (isObject(handler)) {
  17824. len = arguments.length;
  17825. args = new Array(len - 1);
  17826. for (i = 1; i < len; i++)
  17827. args[i - 1] = arguments[i];
  17828. listeners = handler.slice();
  17829. len = listeners.length;
  17830. for (i = 0; i < len; i++)
  17831. listeners[i].apply(this, args);
  17832. }
  17833. return true;
  17834. };
  17835. EventEmitter.prototype.addListener = function(type, listener) {
  17836. var m;
  17837. if (!isFunction(listener))
  17838. throw TypeError('listener must be a function');
  17839. if (!this._events)
  17840. this._events = {};
  17841. // To avoid recursion in the case that type === "newListener"! Before
  17842. // adding it to the listeners, first emit "newListener".
  17843. if (this._events.newListener)
  17844. this.emit('newListener', type,
  17845. isFunction(listener.listener) ?
  17846. listener.listener : listener);
  17847. if (!this._events[type])
  17848. // Optimize the case of one listener. Don't need the extra array object.
  17849. this._events[type] = listener;
  17850. else if (isObject(this._events[type]))
  17851. // If we've already got an array, just append.
  17852. this._events[type].push(listener);
  17853. else
  17854. // Adding the second element, need to change to array.
  17855. this._events[type] = [this._events[type], listener];
  17856. // Check for listener leak
  17857. if (isObject(this._events[type]) && !this._events[type].warned) {
  17858. var m;
  17859. if (!isUndefined(this._maxListeners)) {
  17860. m = this._maxListeners;
  17861. } else {
  17862. m = EventEmitter.defaultMaxListeners;
  17863. }
  17864. if (m && m > 0 && this._events[type].length > m) {
  17865. this._events[type].warned = true;
  17866. console.error('(node) warning: possible EventEmitter memory ' +
  17867. 'leak detected. %d listeners added. ' +
  17868. 'Use emitter.setMaxListeners() to increase limit.',
  17869. this._events[type].length);
  17870. if (typeof console.trace === 'function') {
  17871. // not supported in IE 10
  17872. console.trace();
  17873. }
  17874. }
  17875. }
  17876. return this;
  17877. };
  17878. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  17879. EventEmitter.prototype.once = function(type, listener) {
  17880. if (!isFunction(listener))
  17881. throw TypeError('listener must be a function');
  17882. var fired = false;
  17883. function g() {
  17884. this.removeListener(type, g);
  17885. if (!fired) {
  17886. fired = true;
  17887. listener.apply(this, arguments);
  17888. }
  17889. }
  17890. g.listener = listener;
  17891. this.on(type, g);
  17892. return this;
  17893. };
  17894. // emits a 'removeListener' event iff the listener was removed
  17895. EventEmitter.prototype.removeListener = function(type, listener) {
  17896. var list, position, length, i;
  17897. if (!isFunction(listener))
  17898. throw TypeError('listener must be a function');
  17899. if (!this._events || !this._events[type])
  17900. return this;
  17901. list = this._events[type];
  17902. length = list.length;
  17903. position = -1;
  17904. if (list === listener ||
  17905. (isFunction(list.listener) && list.listener === listener)) {
  17906. delete this._events[type];
  17907. if (this._events.removeListener)
  17908. this.emit('removeListener', type, listener);
  17909. } else if (isObject(list)) {
  17910. for (i = length; i-- > 0;) {
  17911. if (list[i] === listener ||
  17912. (list[i].listener && list[i].listener === listener)) {
  17913. position = i;
  17914. break;
  17915. }
  17916. }
  17917. if (position < 0)
  17918. return this;
  17919. if (list.length === 1) {
  17920. list.length = 0;
  17921. delete this._events[type];
  17922. } else {
  17923. list.splice(position, 1);
  17924. }
  17925. if (this._events.removeListener)
  17926. this.emit('removeListener', type, listener);
  17927. }
  17928. return this;
  17929. };
  17930. EventEmitter.prototype.removeAllListeners = function(type) {
  17931. var key, listeners;
  17932. if (!this._events)
  17933. return this;
  17934. // not listening for removeListener, no need to emit
  17935. if (!this._events.removeListener) {
  17936. if (arguments.length === 0)
  17937. this._events = {};
  17938. else if (this._events[type])
  17939. delete this._events[type];
  17940. return this;
  17941. }
  17942. // emit removeListener for all listeners on all events
  17943. if (arguments.length === 0) {
  17944. for (key in this._events) {
  17945. if (key === 'removeListener') continue;
  17946. this.removeAllListeners(key);
  17947. }
  17948. this.removeAllListeners('removeListener');
  17949. this._events = {};
  17950. return this;
  17951. }
  17952. listeners = this._events[type];
  17953. if (isFunction(listeners)) {
  17954. this.removeListener(type, listeners);
  17955. } else {
  17956. // LIFO order
  17957. while (listeners.length)
  17958. this.removeListener(type, listeners[listeners.length - 1]);
  17959. }
  17960. delete this._events[type];
  17961. return this;
  17962. };
  17963. EventEmitter.prototype.listeners = function(type) {
  17964. var ret;
  17965. if (!this._events || !this._events[type])
  17966. ret = [];
  17967. else if (isFunction(this._events[type]))
  17968. ret = [this._events[type]];
  17969. else
  17970. ret = this._events[type].slice();
  17971. return ret;
  17972. };
  17973. EventEmitter.listenerCount = function(emitter, type) {
  17974. var ret;
  17975. if (!emitter._events || !emitter._events[type])
  17976. ret = 0;
  17977. else if (isFunction(emitter._events[type]))
  17978. ret = 1;
  17979. else
  17980. ret = emitter._events[type].length;
  17981. return ret;
  17982. };
  17983. function isFunction(arg) {
  17984. return typeof arg === 'function';
  17985. }
  17986. function isNumber(arg) {
  17987. return typeof arg === 'number';
  17988. }
  17989. function isObject(arg) {
  17990. return typeof arg === 'object' && arg !== null;
  17991. }
  17992. function isUndefined(arg) {
  17993. return arg === void 0;
  17994. }
  17995. },{}],78:[function(require,module,exports){
  17996. // shim for using process in browser
  17997. var process = module.exports = {};
  17998. var queue = [];
  17999. var draining = false;
  18000. function drainQueue() {
  18001. if (draining) {
  18002. return;
  18003. }
  18004. draining = true;
  18005. var currentQueue;
  18006. var len = queue.length;
  18007. while(len) {
  18008. currentQueue = queue;
  18009. queue = [];
  18010. var i = -1;
  18011. while (++i < len) {
  18012. currentQueue[i]();
  18013. }
  18014. len = queue.length;
  18015. }
  18016. draining = false;
  18017. }
  18018. process.nextTick = function (fun) {
  18019. queue.push(fun);
  18020. if (!draining) {
  18021. setTimeout(drainQueue, 0);
  18022. }
  18023. };
  18024. process.title = 'browser';
  18025. process.browser = true;
  18026. process.env = {};
  18027. process.argv = [];
  18028. process.version = ''; // empty string to avoid regexp issues
  18029. function noop() {}
  18030. process.on = noop;
  18031. process.addListener = noop;
  18032. process.once = noop;
  18033. process.off = noop;
  18034. process.removeListener = noop;
  18035. process.removeAllListeners = noop;
  18036. process.emit = noop;
  18037. process.binding = function (name) {
  18038. throw new Error('process.binding is not supported');
  18039. };
  18040. // TODO(shtylman)
  18041. process.cwd = function () { return '/' };
  18042. process.chdir = function (dir) {
  18043. throw new Error('process.chdir is not supported');
  18044. };
  18045. process.umask = function() { return 0; };
  18046. },{}]},{},[7])(7)
  18047. });