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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567
  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. this.lastActiveSpeaker = null;
  28. }
  29. /**
  30. * Joins the conference.
  31. * @param password {string} the password
  32. */
  33. JitsiConference.prototype.join = function (password) {
  34. this.room.join(password);
  35. }
  36. /**
  37. * Leaves the conference.
  38. */
  39. JitsiConference.prototype.leave = function () {
  40. this.xmpp.leaveRoom(this.room.roomjid);
  41. this.room = null;
  42. }
  43. /**
  44. * Creates the media tracks and returns them trough the callback.
  45. * @param options Object with properties / settings specifying the tracks which should be created.
  46. * should be created or some additional configurations about resolution for example.
  47. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>} A promise that returns an array of created JitsiTracks if resolved,
  48. * or a JitsiConferenceError if rejected.
  49. */
  50. JitsiConference.prototype.createLocalTracks = function (options) {
  51. return this.rtc.obtainAudioAndVideoPermissions(options || {});
  52. }
  53. /**
  54. * Returns the local tracks.
  55. */
  56. JitsiConference.prototype.getLocalTracks = function () {
  57. return this.rtc.localStreams;
  58. };
  59. /**
  60. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  61. * in JitsiConferenceEvents.
  62. * @param eventId the event ID.
  63. * @param handler handler for the event.
  64. *
  65. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  66. */
  67. JitsiConference.prototype.on = function (eventId, handler) {
  68. this.eventEmitter.on(eventId, handler);
  69. }
  70. /**
  71. * Removes event listener
  72. * @param eventId the event ID.
  73. * @param [handler] optional, the specific handler to unbind
  74. *
  75. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  76. */
  77. JitsiConference.prototype.off = function (eventId, handler) {
  78. this.eventEmitter.removeListener(eventId, listener);
  79. }
  80. // Common aliases for event emitter
  81. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on
  82. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off
  83. /**
  84. * Receives notifications from another participants for commands / custom events(send by sendPresenceCommand method).
  85. * @param command {String} the name of the command
  86. * @param handler {Function} handler for the command
  87. */
  88. JitsiConference.prototype.addCommandListener = function (command, handler) {
  89. this.room.addPresenceListener(command, handler);
  90. }
  91. /**
  92. * Removes command listener
  93. * @param command {String} the name of the command
  94. */
  95. JitsiConference.prototype.removeCommandListener = function (command) {
  96. this.room.removePresenceListener(command);
  97. }
  98. /**
  99. * Sends text message to the other participants in the conference
  100. * @param message the text message.
  101. */
  102. JitsiConference.prototype.sendTextMessage = function (message) {
  103. this.room.sendMessage(message);
  104. }
  105. /**
  106. * Send presence command.
  107. * @param name the name of the command.
  108. * @param values Object with keys and values that will be send.
  109. **/
  110. JitsiConference.prototype.sendCommand = function (name, values) {
  111. this.room.addToPresence(name, values);
  112. this.room.sendPresence();
  113. }
  114. /**
  115. * Send presence command one time.
  116. * @param name the name of the command.
  117. * @param values Object with keys and values that will be send.
  118. **/
  119. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  120. this.sendCommand(name, values);
  121. this.removeCommand(name);
  122. }
  123. /**
  124. * Send presence command.
  125. * @param name the name of the command.
  126. * @param values Object with keys and values that will be send.
  127. * @param persistent if false the command will be sent only one time
  128. **/
  129. JitsiConference.prototype.removeCommand = function (name) {
  130. this.room.removeFromPresence(name);
  131. }
  132. /**
  133. * Sets the display name for this conference.
  134. * @param name the display name to set
  135. */
  136. JitsiConference.prototype.setDisplayName = function(name) {
  137. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  138. }
  139. /**
  140. * Elects the participant with the given id to be the selected participant or the speaker.
  141. * @param id the identifier of the participant
  142. */
  143. JitsiConference.prototype.selectParticipant = function(participantId) {
  144. this.rtc.selectedEndpoint(participantId);
  145. }
  146. /**
  147. *
  148. * @param id the identifier of the participant
  149. */
  150. JitsiConference.prototype.pinParticipant = function(participantId) {
  151. this.rtc.pinEndpoint(participantId);
  152. }
  153. /**
  154. * Returns the list of participants for this conference.
  155. * @return Object a list of participant identifiers containing all conference participants.
  156. */
  157. JitsiConference.prototype.getParticipants = function() {
  158. return this.participants;
  159. }
  160. /**
  161. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  162. * null if there isn't one).
  163. * @param id the id of the participant.
  164. */
  165. JitsiConference.prototype.getParticipantById = function(id) {
  166. return this.participants[id];
  167. }
  168. JitsiConference.prototype.onMemberJoined = function (jid, email, nick) {
  169. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, Strophe.getResourceFromJid(jid));
  170. // this.participants[jid] = new JitsiParticipant();
  171. }
  172. /**
  173. * Setups the listeners needed for the conference.
  174. * @param conference the conference
  175. */
  176. function setupListeners(conference) {
  177. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING,
  178. conference.rtc.onIncommingCall.bind(conference.rtc));
  179. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  180. conference.rtc.createRemoteStream.bind(conference.rtc));
  181. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, function (stream) {
  182. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, stream);
  183. });
  184. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_REMOTE_ENDED, function (stream) {
  185. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, stream);
  186. });
  187. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, function (stream) {
  188. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, stream);
  189. });
  190. conference.rtc.addListener(StreamEventTypes.TRACK_MUTE_CHANGED, function (track) {
  191. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  192. });
  193. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  194. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  195. });
  196. // FIXME
  197. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  198. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  199. // });
  200. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  201. if(conference.lastActiveSpeaker !== id && conference.room
  202. && conference.room.myroomjid !== id) {
  203. conference.lastActiveSpeaker = id;
  204. conference.eventEmitter.emit(JitsiConferenceEvents.ACTIVE_SPEAKER_CHANGED, id);
  205. }
  206. });
  207. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  208. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  209. });
  210. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  211. function (lastNEndpoints, endpointsEnteringLastN) {
  212. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  213. lastNEndpoints, endpointsEnteringLastN);
  214. });
  215. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  216. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT,function (jid) {
  217. conference.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, Strophe.getResourceFromJid(jid));
  218. });
  219. }
  220. module.exports = JitsiConference;
  221. },{"./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){
  222. /**
  223. * Enumeration with the errors for the conference.
  224. * @type {{string: string}}
  225. */
  226. var JitsiConferenceErrors = {
  227. /**
  228. * Indicates that a password is required in order to join the conference.
  229. */
  230. PASSWORD_REQUIRED: "conference.passwordRequired",
  231. /**
  232. * Indicates that a connection error occurred when trying to join a conference.
  233. */
  234. CONNECTION_ERROR: "conference.connectionError",
  235. /**
  236. * Indicates that there is no available videobridge.
  237. */
  238. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  239. /**
  240. * Many more errors TBD here.
  241. */
  242. };
  243. module.exports = JitsiConferenceErrors;
  244. },{}],3:[function(require,module,exports){
  245. /**
  246. * Enumeration with the events for the conference.
  247. * @type {{string: string}}
  248. */
  249. var JitsiConferenceEvents = {
  250. /**
  251. * A new media track was added to the conference.
  252. */
  253. TRACK_ADDED: "conference.trackAdded",
  254. /**
  255. * The media track was removed to the conference.
  256. */
  257. TRACK_REMOVED: "conference.trackRemoved",
  258. /**
  259. * The active speaker was changed.
  260. */
  261. ACTIVE_SPEAKER_CHANGED: "conference.activeSpeaker",
  262. /**
  263. * A new user joinned the conference.
  264. */
  265. USER_JOINED: "conference.userJoined",
  266. /**
  267. * A user has left the conference.
  268. */
  269. USER_LEFT: "conference.userLeft",
  270. /**
  271. * New text message was received.
  272. */
  273. MESSAGE_RECEIVED: "conference.messageReceived",
  274. /**
  275. * A user has changed it display name
  276. */
  277. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  278. /**
  279. * A participant avatar has changed.
  280. */
  281. AVATAR_CHANGED: "conference.avatarChanged",
  282. /**
  283. * New connection statistics are received.
  284. */
  285. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  286. /**
  287. * The Last N set is changed.
  288. */
  289. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  290. /**
  291. * You are included / excluded in somebody's last N set
  292. */
  293. IN_LAST_N_CHANGED: "conference.lastNEndpointsChanged",
  294. /**
  295. * A media track mute status was changed.
  296. */
  297. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  298. /**
  299. * Audio levels of a media track was changed.
  300. */
  301. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  302. /**
  303. * Indicates that the connection to the conference has been interrupted for some reason.
  304. */
  305. CONNECTION_INTERRUPTED: "conference.connecionInterrupted",
  306. /**
  307. * Indicates that the connection to the conference has been restored.
  308. */
  309. CONNECTION_RESTORED: "conference.connecionRestored",
  310. /**
  311. * Indicates that conference has been joined.
  312. */
  313. CONFERENCE_JOINED: "conference.joined",
  314. /**
  315. * Indicates that conference has been left.
  316. */
  317. CONFERENCE_LEFT: "conference.left"
  318. };
  319. module.exports = JitsiConferenceEvents;
  320. },{}],4:[function(require,module,exports){
  321. var JitsiConference = require("./JitsiConference");
  322. var XMPP = require("./modules/xmpp/xmpp");
  323. /**
  324. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  325. * JitsiConference interface.
  326. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  327. * @param token secret generated by the provider of Jitsi Meet video conferencing services.
  328. * The token will be send to the provider from the Jitsi Meet server deployment for authorization of the current client.
  329. * @param options Object with properties / settings related to connection with the server.
  330. * @constructor
  331. */
  332. function JitsiConnection(appID, token, options) {
  333. this.appID = appID;
  334. this.token = token;
  335. this.options = options;
  336. this.xmpp = new XMPP(options);
  337. this.conferences = {};
  338. }
  339. /**
  340. * Connect the client with the server.
  341. * @param options {object} connecting options (for example authentications parameters).
  342. */
  343. JitsiConnection.prototype.connect = function (options) {
  344. if(!options)
  345. options = {};
  346. this.xmpp.connect(options.id, options.password);
  347. }
  348. /**
  349. * Disconnect the client from the server.
  350. */
  351. JitsiConnection.prototype.disconnect = function () {
  352. this.xmpp.disconnect();
  353. }
  354. /**
  355. * This method allows renewal of the tokens if they are expiring.
  356. * @param token the new token.
  357. */
  358. JitsiConnection.prototype.setToken = function (token) {
  359. this.token = token;
  360. }
  361. /**
  362. * Creates and joins new conference.
  363. * @param name the name of the conference; if null - a generated name will be provided from the api
  364. * @param options Object with properties / settings related to the conference that will be created.
  365. * @returns {JitsiConference} returns the new conference object.
  366. */
  367. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  368. this.conferences[name] = new JitsiConference({name: name, config: options, connection: this});
  369. return this.conferences[name];
  370. }
  371. /**
  372. * Subscribes the passed listener to the event.
  373. * @param event {JitsiConnectionEvents} the connection event.
  374. * @param listener {Function} the function that will receive the event
  375. */
  376. JitsiConnection.prototype.addEventListener = function (event, listener) {
  377. this.xmpp.addListener(event, listener);
  378. }
  379. /**
  380. * Unsubscribes the passed handler.
  381. * @param event {JitsiConnectionEvents} the connection event.
  382. * @param listener {Function} the function that will receive the event
  383. */
  384. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  385. this.xmpp.removeListener(event, listener);
  386. }
  387. module.exports = JitsiConnection;
  388. },{"./JitsiConference":1,"./modules/xmpp/xmpp":33}],5:[function(require,module,exports){
  389. /**
  390. * Enumeration with the errors for the connection.
  391. * @type {{string: string}}
  392. */
  393. var JitsiConnectionErrors = {
  394. /**
  395. * Indicates that a password is required in order to join the conference.
  396. */
  397. PASSWORD_REQUIRED: "connection.passwordRequired",
  398. /**
  399. * Indicates that a connection error occurred when trying to join a conference.
  400. */
  401. CONNECTION_ERROR: "connection.connectionError",
  402. /**
  403. * Not specified errors.
  404. */
  405. OTHER_ERROR: "connection.otherError"
  406. };
  407. module.exports = JitsiConnectionErrors;
  408. },{}],6:[function(require,module,exports){
  409. /**
  410. * Enumeration with the events for the connection.
  411. * @type {{string: string}}
  412. */
  413. var JitsiConnnectionEvents = {
  414. /**
  415. * Indicates that the connection has been failed for some reason.
  416. */
  417. CONNECTION_FAILED: "connection.connecionFailed",
  418. /**
  419. * Indicates that the connection has been established.
  420. */
  421. CONNECTION_ESTABLISHED: "connection.connecionEstablished",
  422. /**
  423. * Indicates that the connection has been disconnected.
  424. */
  425. CONNECTION_DISCONNECTED: "connection.connecionDisconnected",
  426. /**
  427. * Indicates that the perfomed action cannot be executed because the
  428. * connection is not in the correct state(connected, disconnected, etc.)
  429. */
  430. WRONG_STATE: "connection.wrongState"
  431. };
  432. module.exports = JitsiConnnectionEvents;
  433. },{}],7:[function(require,module,exports){
  434. var JitsiConnection = require("./JitsiConnection");
  435. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  436. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  437. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  438. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  439. /**
  440. * Namespace for the interface of Jitsi Meet Library.
  441. */
  442. var LibJitsiMeet = {
  443. JitsiConnection: JitsiConnection,
  444. events: {
  445. conference: JitsiConferenceEvents,
  446. connection: JitsiConnectionEvents
  447. },
  448. errors: {
  449. conference: JitsiConferenceErrors,
  450. connection: JitsiConnectionErrors
  451. },
  452. init: function (options) {
  453. require("./modules/RTC/RTC").init(options || {});
  454. }
  455. }
  456. //Setups the promise object.
  457. window.Promise = window.Promise || require("es6-promise").polyfill();
  458. module.exports = LibJitsiMeet;
  459. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./modules/RTC/RTC":13,"es6-promise":35}],8:[function(require,module,exports){
  460. /**
  461. * Represents a participant in (a member of) a conference.
  462. */
  463. function JitsiParticipant(id, conference, displayName){
  464. this._id = id;
  465. this._conference = conference;
  466. this._displayName = displayName;
  467. }
  468. /**
  469. * @returns {JitsiConference} The conference that this participant belongs to.
  470. */
  471. JitsiParticipant.prototype.getConference = function() {
  472. return this._conference;
  473. }
  474. /**
  475. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  476. */
  477. JitsiParticipant.prototype.getTracks = function() {
  478. }
  479. /**
  480. * @returns {String} The ID (i.e. JID) of this participant.
  481. */
  482. JitsiParticipant.prototype.getId = function() {
  483. return this._id;
  484. }
  485. /**
  486. * @returns {String} The human-readable display name of this participant.
  487. */
  488. JitsiParticipant.prototype.getDisplayName = function() {
  489. return this._displayName;
  490. }
  491. /**
  492. * @returns {Boolean} Whether this participant is a moderator or not.
  493. */
  494. JitsiParticipant.prototype.isModerator = function() {
  495. }
  496. // Gets a link to an etherpad instance advertised by the participant?
  497. //JitsiParticipant.prototype.getEtherpad = function() {
  498. //
  499. //}
  500. /*
  501. * @returns {Boolean} Whether this participant has muted their audio.
  502. */
  503. JitsiParticipant.prototype.isAudioMuted = function() {
  504. }
  505. /*
  506. * @returns {Boolean} Whether this participant has muted their video.
  507. */
  508. JitsiParticipant.prototype.isVideoMuted = function() {
  509. }
  510. /*
  511. * @returns {???} The latest statistics reported by this participant (i.e. info used to populate the GSM bars)
  512. * TODO: do we expose this or handle it internally?
  513. */
  514. JitsiParticipant.prototype.getLatestStats = function() {
  515. }
  516. /**
  517. * @returns {String} The role of this participant.
  518. */
  519. JitsiParticipant.prototype.getRole = function() {
  520. }
  521. /*
  522. * @returns {Boolean} Whether this participant is the conference focus (i.e. jicofo).
  523. */
  524. JitsiParticipant.prototype.isFocus = function() {
  525. }
  526. /*
  527. * @returns {Boolean} Whether this participant is a conference recorder (i.e. jirecon).
  528. */
  529. JitsiParticipant.prototype.isRecorder = function() {
  530. }
  531. /*
  532. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  533. */
  534. JitsiParticipant.prototype.isSipGateway = function() {
  535. }
  536. /**
  537. * @returns {String} The ID for this participant's avatar.
  538. */
  539. JitsiParticipant.prototype.getAvatarId = function() {
  540. }
  541. /**
  542. * @returns {Boolean} Whether this participant is currently sharing their screen.
  543. */
  544. JitsiParticipant.prototype.isScreenSharing = function() {
  545. }
  546. /**
  547. * @returns {String} The user agent of this participant (i.e. browser userAgent string).
  548. */
  549. JitsiParticipant.prototype.getUserAgent = function() {
  550. }
  551. /**
  552. * Kicks the participant from the conference (requires certain privileges).
  553. */
  554. JitsiParticipant.prototype.kick = function() {
  555. }
  556. /**
  557. * Asks this participant to mute themselves.
  558. */
  559. JitsiParticipant.prototype.askToMute = function() {
  560. }
  561. module.exports = JitsiParticipant();
  562. },{}],9:[function(require,module,exports){
  563. /* global config, APP, Strophe */
  564. // cache datachannels to avoid garbage collection
  565. // https://code.google.com/p/chromium/issues/detail?id=405545
  566. var RTCEvents = require("../../service/RTC/RTCEvents");
  567. /**
  568. * Binds "ondatachannel" event listener to given PeerConnection instance.
  569. * @param peerConnection WebRTC peer connection instance.
  570. */
  571. function DataChannels(peerConnection, emitter) {
  572. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  573. this.eventEmitter = emitter;
  574. this._dataChannels = [];
  575. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  576. // Although it's not a requirement to open separate channels from both bridge
  577. // and peer as single channel can be used for sending and receiving data.
  578. // So either channel opened by the bridge or the one opened here is enough
  579. // for communication with the bridge.
  580. /*var dataChannelOptions =
  581. {
  582. reliable: true
  583. };
  584. var dataChannel
  585. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  586. // Can be used only when is in open state
  587. dataChannel.onopen = function ()
  588. {
  589. dataChannel.send("My channel !!!");
  590. };
  591. dataChannel.onmessage = function (event)
  592. {
  593. var msgData = event.data;
  594. console.info("Got My Data Channel Message:", msgData, dataChannel);
  595. };*/
  596. };
  597. /**
  598. * Callback triggered by PeerConnection when new data channel is opened
  599. * on the bridge.
  600. * @param event the event info object.
  601. */
  602. DataChannels.prototype.onDataChannel = function (event) {
  603. var dataChannel = event.channel;
  604. var self = this;
  605. dataChannel.onopen = function () {
  606. console.info("Data channel opened by the Videobridge!", dataChannel);
  607. // Code sample for sending string and/or binary data
  608. // Sends String message to the bridge
  609. //dataChannel.send("Hello bridge!");
  610. // Sends 12 bytes binary message to the bridge
  611. //dataChannel.send(new ArrayBuffer(12));
  612. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  613. };
  614. dataChannel.onerror = function (error) {
  615. console.error("Data Channel Error:", error, dataChannel);
  616. };
  617. dataChannel.onmessage = function (event) {
  618. var data = event.data;
  619. // JSON
  620. var obj;
  621. try {
  622. obj = JSON.parse(data);
  623. }
  624. catch (e) {
  625. console.error(
  626. "Failed to parse data channel message as JSON: ",
  627. data,
  628. dataChannel);
  629. }
  630. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  631. var colibriClass = obj.colibriClass;
  632. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  633. // Endpoint ID from the Videobridge.
  634. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  635. console.info(
  636. "Data channel new dominant speaker event: ",
  637. dominantSpeakerEndpoint);
  638. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  639. }
  640. else if ("InLastNChangeEvent" === colibriClass) {
  641. var oldValue = obj.oldValue;
  642. var newValue = obj.newValue;
  643. // Make sure that oldValue and newValue are of type boolean.
  644. var type;
  645. if ((type = typeof oldValue) !== 'boolean') {
  646. if (type === 'string') {
  647. oldValue = (oldValue == "true");
  648. } else {
  649. oldValue = new Boolean(oldValue).valueOf();
  650. }
  651. }
  652. if ((type = typeof newValue) !== 'boolean') {
  653. if (type === 'string') {
  654. newValue = (newValue == "true");
  655. } else {
  656. newValue = new Boolean(newValue).valueOf();
  657. }
  658. }
  659. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  660. }
  661. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  662. // The new/latest list of last-n endpoint IDs.
  663. var lastNEndpoints = obj.lastNEndpoints;
  664. // The list of endpoint IDs which are entering the list of
  665. // last-n at this time i.e. were not in the old list of last-n
  666. // endpoint IDs.
  667. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  668. console.log(
  669. "Data channel new last-n event: ",
  670. lastNEndpoints, endpointsEnteringLastN, obj);
  671. this.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  672. lastNEndpoints, endpointsEnteringLastN, obj);
  673. }
  674. else {
  675. console.debug("Data channel JSON-formatted message: ", obj);
  676. }
  677. }
  678. };
  679. dataChannel.onclose = function () {
  680. console.info("The Data Channel closed", dataChannel);
  681. var idx = self._dataChannels.indexOf(dataChannel);
  682. if (idx > -1)
  683. self._dataChannels = self._dataChannels.splice(idx, 1);
  684. };
  685. this._dataChannels.push(dataChannel);
  686. };
  687. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  688. console.log('selected endpoint changed: ', userResource);
  689. if (this._dataChannels && this._dataChannels.length != 0) {
  690. this._dataChannels.some(function (dataChannel) {
  691. if (dataChannel.readyState == 'open') {
  692. console.log('sending selected endpoint changed ' +
  693. 'notification to the bridge: ', userResource);
  694. dataChannel.send(JSON.stringify({
  695. 'colibriClass': 'SelectedEndpointChangedEvent',
  696. 'selectedEndpoint':
  697. (!userResource || userResource === null)?
  698. null : userResource
  699. }));
  700. return true;
  701. }
  702. });
  703. }
  704. }
  705. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  706. console.log('pinned endpoint changed: ', userResource);
  707. if (this._dataChannels && this._dataChannels.length != 0) {
  708. this._dataChannels.some(function (dataChannel) {
  709. if (dataChannel.readyState == 'open') {
  710. dataChannel.send(JSON.stringify({
  711. 'colibriClass': 'PinnedEndpointChangedEvent',
  712. 'pinnedEndpoint':
  713. (!userResource || userResource == null)?
  714. null : userResource
  715. }));
  716. return true;
  717. }
  718. });
  719. }
  720. }
  721. module.exports = DataChannels;
  722. },{"../../service/RTC/RTCEvents":71}],10:[function(require,module,exports){
  723. var JitsiTrack = require("./JitsiTrack");
  724. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  725. var RTC = require("./RTCUtils");
  726. var RTCBrowserType = require("./RTCBrowserType");
  727. /**
  728. * Represents a single media track (either audio or video).
  729. * @constructor
  730. */
  731. function JitsiLocalTrack(RTC, stream, eventEmitter, videoType, isGUMStream)
  732. {
  733. JitsiTrack.call(this, RTC, stream);
  734. this.eventEmitter = eventEmitter;
  735. this.videoType = videoType;
  736. this.isGUMStream = true;
  737. this.dontFireRemoveEvent = false;
  738. this.isStarted = false;
  739. var self = this;
  740. if(isGUMStream === false)
  741. this.isGUMStream = isGUMStream;
  742. this.stream.onended = function () {
  743. if(!self.dontFireRemoveEvent)
  744. self.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, self);
  745. self.dontFireRemoveEvent = false;
  746. };
  747. }
  748. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  749. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  750. /**
  751. * Mutes / unmutes the track.
  752. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  753. */
  754. JitsiLocalTrack.prototype._setMute = function (mute) {
  755. var isAudio = this.type === JitsiTrack.AUDIO;
  756. this.dontFireRemoveEvent = false;
  757. if ((window.location.protocol != "https:" && this.isGUMStream) ||
  758. (isAudio && this.isGUMStream) || this.videoType === "screen" ||
  759. // FIXME FF does not support 'removeStream' method used to mute
  760. RTCBrowserType.isFirefox()) {
  761. var tracks = this._getTracks();
  762. for (var idx = 0; idx < tracks.length; idx++) {
  763. tracks[idx].enabled = !mute;
  764. }
  765. if(isAudio)
  766. this.rtc.room.setAudioMute(mute);
  767. else
  768. this.rtc.room.setVideoMute(mute);
  769. this.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  770. } else {
  771. if (mute) {
  772. this.dontFireRemoveEvent = true;
  773. this.rtc.room.removeStream(this.stream);
  774. this.stream.stop();
  775. if(isAudio)
  776. this.rtc.room.setAudioMute(mute);
  777. else
  778. this.rtc.room.setVideoMute(mute);
  779. this.stream = null;
  780. this.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  781. //FIXME: Maybe here we should set the SRC for the containers to something
  782. } else {
  783. var self = this;
  784. this.rtc.obtainAudioAndVideoPermissions(
  785. {devices: (isAudio ? ["audio"] : ["video"])}, true)
  786. .then(function (streams) {
  787. var stream = null;
  788. for(var i = 0; i < streams.length; i++) {
  789. stream = streams[i];
  790. if(stream.type === self.type) {
  791. self.stream = stream.stream;
  792. self.videoType = stream.videoType;
  793. self.isGUMStream = stream.isGUMStream;
  794. break;
  795. }
  796. }
  797. if(!stream)
  798. return;
  799. for(var i = 0; i < self.containers.length; i++)
  800. {
  801. RTC.attachMediaStream(self.containers[i], self.stream);
  802. }
  803. self.rtc.room.addStream(stream.stream,
  804. function () {
  805. if(isAudio)
  806. self.rtc.room.setAudioMute(mute);
  807. else
  808. self.rtc.room.setVideoMute(mute);
  809. self.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, self);
  810. });
  811. });
  812. }
  813. }
  814. }
  815. /**
  816. * Stops sending the media track. And removes it from the HTML.
  817. * NOTE: Works for local tracks only.
  818. */
  819. JitsiLocalTrack.prototype.stop = function () {
  820. if(!this.stream)
  821. return;
  822. this.rtc.room.removeStream(this.stream);
  823. this.stream.stop();
  824. this.detach();
  825. }
  826. /**
  827. * Starts sending the track.
  828. * NOTE: Works for local tracks only.
  829. */
  830. JitsiLocalTrack.prototype.start = function() {
  831. this.isStarted = true;
  832. this.rtc.room.addStream(this.stream, function () {});
  833. }
  834. /**
  835. * Returns <tt>true</tt> - if the stream is muted
  836. * and <tt>false</tt> otherwise.
  837. * @returns {boolean} <tt>true</tt> - if the stream is muted
  838. * and <tt>false</tt> otherwise.
  839. */
  840. JitsiLocalTrack.prototype.isMuted = function () {
  841. if (!this.stream)
  842. return true;
  843. var tracks = [];
  844. var isAudio = this.type === JitsiTrack.AUDIO;
  845. if (isAudio) {
  846. tracks = this.stream.getAudioTracks();
  847. } else {
  848. if (this.stream.ended)
  849. return true;
  850. tracks = this.stream.getVideoTracks();
  851. }
  852. for (var idx = 0; idx < tracks.length; idx++) {
  853. if(tracks[idx].enabled)
  854. return false;
  855. }
  856. return true;
  857. };
  858. module.exports = JitsiLocalTrack;
  859. },{"../../service/RTC/StreamEventTypes":73,"./JitsiTrack":12,"./RTCBrowserType":14,"./RTCUtils":15}],11:[function(require,module,exports){
  860. var JitsiTrack = require("./JitsiTrack");
  861. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  862. /**
  863. * Represents a single media track (either audio or video).
  864. * @param RTC the rtc instance.
  865. * @param data object with the stream and some details about it(participant id, video type, etc.)
  866. * @param sid sid for the Media Stream
  867. * @param ssrc ssrc for the Media Stream
  868. * @param eventEmitter the event emitter
  869. * @constructor
  870. */
  871. function JitsiRemoteTrack(RTC, data, sid, ssrc, eventEmitter) {
  872. JitsiTrack.call(this, RTC, data.stream);
  873. this.rtc = RTC;
  874. this.sid = sid;
  875. this.stream = data.stream;
  876. this.peerjid = data.peerjid;
  877. this.videoType = data.videoType;
  878. this.ssrc = ssrc;
  879. this.muted = false;
  880. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  881. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  882. this.muted = true
  883. }
  884. this.eventEmitter = eventEmitter;
  885. var self = this;
  886. if(this.stream)
  887. this.stream.onended = function () {
  888. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_ENDED, self);
  889. }
  890. }
  891. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  892. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  893. /**
  894. * Sets current muted status and fires an events for the change.
  895. * @param value the muted status.
  896. */
  897. JitsiRemoteTrack.prototype.setMute = function (value) {
  898. this.stream.muted = value;
  899. this.muted = value;
  900. this.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  901. };
  902. /**
  903. * Returns the current muted status of the track.
  904. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  905. */
  906. JitsiRemoteTrack.prototype.isMuted = function () {
  907. return this.muted;
  908. }
  909. /**
  910. * Returns the participant id which owns the track.
  911. * @returns {string} the id of the participants.
  912. */
  913. JitsiRemoteTrack.prototype.getParitcipantId = function() {
  914. return Strophe.getResourceFromJid(this.peerjid);
  915. };
  916. delete JitsiRemoteTrack.prototype.stop;
  917. delete JitsiRemoteTrack.prototype.start;
  918. module.exports = JitsiRemoteTrack;
  919. },{"../../service/RTC/StreamEventTypes":73,"./JitsiTrack":12}],12:[function(require,module,exports){
  920. var RTC = require("./RTCUtils");
  921. var RTCBrowserType = require("./RTCBrowserType");
  922. /**
  923. * This implements 'onended' callback normally fired by WebRTC after the stream
  924. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  925. * @param stream original WebRTC stream object to which 'onended' handling
  926. * will be added.
  927. */
  928. function implementOnEndedHandling(stream) {
  929. var originalStop = stream.stop;
  930. stream.stop = function () {
  931. originalStop.apply(stream);
  932. if (!stream.ended) {
  933. stream.ended = true;
  934. stream.onended();
  935. }
  936. };
  937. }
  938. /**
  939. * Represents a single media track (either audio or video).
  940. * @constructor
  941. */
  942. function JitsiTrack(RTC, stream)
  943. {
  944. /**
  945. * Array with the HTML elements that are displaying the streams.
  946. * @type {Array}
  947. */
  948. this.containers = [];
  949. this.rtc = RTC;
  950. this.stream = stream;
  951. this.type = (this.stream.getVideoTracks().length > 0)?
  952. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  953. if(this.type == "audio") {
  954. this._getTracks = function () {
  955. return this.stream.getAudioTracks();
  956. }.bind(this);
  957. } else {
  958. this._getTracks = function () {
  959. return this.stream.getVideoTracks();
  960. }.bind(this);
  961. }
  962. if (RTCBrowserType.isFirefox() && this.stream) {
  963. implementOnEndedHandling(this.stream);
  964. }
  965. }
  966. /**
  967. * JitsiTrack video type.
  968. * @type {string}
  969. */
  970. JitsiTrack.VIDEO = "video";
  971. /**
  972. * JitsiTrack audio type.
  973. * @type {string}
  974. */
  975. JitsiTrack.AUDIO = "audio";
  976. /**
  977. * Returns the type (audio or video) of this track.
  978. */
  979. JitsiTrack.prototype.getType = function() {
  980. return this.type;
  981. };
  982. /**
  983. * Returns the RTCMediaStream from the browser (?).
  984. */
  985. JitsiTrack.prototype.getOriginalStream = function() {
  986. return this.stream;
  987. }
  988. /**
  989. * Mutes the track.
  990. */
  991. JitsiTrack.prototype.mute = function () {
  992. this._setMute(true);
  993. }
  994. /**
  995. * Unmutes the stream.
  996. */
  997. JitsiTrack.prototype.unmute = function () {
  998. this._setMute(false);
  999. }
  1000. /**
  1001. * Attaches the MediaStream of this track to an HTML container (?).
  1002. * Adds the container to the list of containers that are displaying the track.
  1003. * @param container the HTML container
  1004. */
  1005. JitsiTrack.prototype.attach = function (container) {
  1006. if(this.stream)
  1007. RTC.attachMediaStream(container, this.stream);
  1008. this.containers.push(container);
  1009. }
  1010. /**
  1011. * Removes the track from the passed HTML container.
  1012. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  1013. */
  1014. JitsiTrack.prototype.detach = function (container) {
  1015. for(var i = 0; i < this.containers.length; i++)
  1016. {
  1017. if(this.containers[i].is(container))
  1018. {
  1019. this.containers.splice(i,1);
  1020. }
  1021. if(!container)
  1022. {
  1023. this.containers[i].find(">video").remove();
  1024. }
  1025. }
  1026. if(container)
  1027. $(container).find(">video").remove();
  1028. }
  1029. /**
  1030. * Stops sending the media track. And removes it from the HTML.
  1031. * NOTE: Works for local tracks only.
  1032. */
  1033. JitsiTrack.prototype.stop = function () {
  1034. }
  1035. /**
  1036. * Starts sending the track.
  1037. * NOTE: Works for local tracks only.
  1038. */
  1039. JitsiTrack.prototype.start = function() {
  1040. }
  1041. /**
  1042. * Returns true if this is a video track and the source of the video is a
  1043. * screen capture as opposed to a camera.
  1044. */
  1045. JitsiTrack.prototype.isScreenSharing = function(){
  1046. }
  1047. /**
  1048. * Returns id of the track.
  1049. * @returns {string} id of the track or null if this is fake track.
  1050. */
  1051. JitsiTrack.prototype.getId = function () {
  1052. var tracks = this.stream.getTracks();
  1053. if(!tracks || tracks.length === 0)
  1054. return null;
  1055. return tracks[0].id;
  1056. };
  1057. module.exports = JitsiTrack;
  1058. },{"./RTCBrowserType":14,"./RTCUtils":15}],13:[function(require,module,exports){
  1059. /* global APP */
  1060. var EventEmitter = require("events");
  1061. var RTCBrowserType = require("./RTCBrowserType");
  1062. var RTCUtils = require("./RTCUtils.js");
  1063. var JitsiTrack = require("./JitsiTrack");
  1064. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  1065. var DataChannels = require("./DataChannels");
  1066. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  1067. var DesktopSharingEventTypes
  1068. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1069. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  1070. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  1071. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  1072. var desktopsharing = require("../desktopsharing/desktopsharing");
  1073. function getMediaStreamUsage()
  1074. {
  1075. var result = {
  1076. audio: true,
  1077. video: true
  1078. };
  1079. /** There are some issues with the desktop sharing
  1080. * when this property is enabled.
  1081. * WARNING: We must change the implementation to start video/audio if we
  1082. * receive from the focus that the peer is not muted.
  1083. var isSecureConnection = window.location.protocol == "https:";
  1084. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  1085. {
  1086. result = {
  1087. audio: false,
  1088. video: false
  1089. };
  1090. }
  1091. **/
  1092. return result;
  1093. }
  1094. var rtcReady = false;
  1095. function RTC(room, options) {
  1096. this.devices = {
  1097. audio: true,
  1098. video: true
  1099. };
  1100. this.room = room;
  1101. this.localStreams = [];
  1102. this.remoteStreams = {};
  1103. this.localAudio = null;
  1104. this.localVideo = null;
  1105. this.eventEmitter = new EventEmitter();
  1106. var self = this;
  1107. this.options = options || {};
  1108. desktopsharing.addListener(
  1109. function (stream, isUsingScreenStream, callback) {
  1110. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  1111. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  1112. room.addPresenceListener("videomuted", function (values, from) {
  1113. if(self.remoteStreams[from])
  1114. self.remoteStreams[from][JitsiTrack.VIDEO].setMute(values.value == "true");
  1115. });
  1116. room.addPresenceListener("audiomuted", function (values, from) {
  1117. if(self.remoteStreams[from])
  1118. self.remoteStreams[from][JitsiTrack.AUDIO].setMute(values.value == "true");
  1119. });
  1120. }
  1121. /**
  1122. * Creates the local MediaStreams.
  1123. * @param options object for options (NOTE: currently only list of devices and resolution are supported)
  1124. * @param dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1125. * type: "audio" or "video", isMuted: true/false, videoType: "camera" or "desktop"}
  1126. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1127. * @returns {*} Promise object that will receive the new JitsiTracks
  1128. */
  1129. RTC.prototype.obtainAudioAndVideoPermissions = function (options, dontCreateJitsiTrack) {
  1130. return RTCUtils.obtainAudioAndVideoPermissions(this,
  1131. options.devices, getMediaStreamUsage(), options.resolution, dontCreateJitsiTrack);
  1132. }
  1133. RTC.prototype.onIncommingCall = function(event) {
  1134. if(this.options.config.openSctp)
  1135. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  1136. for(var i = 0; i < this.localStreams.length; i++)
  1137. if(this.localStreams[i].isStarted)
  1138. {
  1139. this.localStreams[i].start();
  1140. }
  1141. }
  1142. RTC.prototype.selectedEndpoint = function (id) {
  1143. if(this.dataChannels)
  1144. this.dataChannels.handleSelectedEndpointEvent(id);
  1145. }
  1146. RTC.prototype.pinEndpoint = function (id) {
  1147. if(this.dataChannels)
  1148. this.dataChannels.handlePinnedEndpointEvent(id);
  1149. }
  1150. RTC.prototype.addStreamListener = function (listener, eventType) {
  1151. this.eventEmitter.on(eventType, listener);
  1152. };
  1153. RTC.prototype.addListener = function (type, listener) {
  1154. this.eventEmitter.on(type, listener);
  1155. };
  1156. RTC.prototype.removeListener = function (listener, eventType) {
  1157. this.eventEmitter.removeListener(eventType, listener);
  1158. };
  1159. RTC.prototype.removeStreamListener = function (listener, eventType) {
  1160. if(!(eventType instanceof StreamEventTypes))
  1161. throw "Illegal argument";
  1162. this.eventEmitter.removeListener(eventType, listener);
  1163. };
  1164. RTC.addRTCReadyListener = function (listener) {
  1165. RTCUtils.eventEmitter.on(RTCEvents.RTC_READY, listener);
  1166. }
  1167. RTC.removeRTCReadyListener = function (listener) {
  1168. RTCUtils.eventEmitter.removeListener(RTCEvents.RTC_READY, listener);
  1169. }
  1170. RTC.isRTCReady = function () {
  1171. return rtcReady;
  1172. }
  1173. RTC.init = function (options) {
  1174. // In case of IE we continue from 'onReady' callback
  1175. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  1176. // once it is initialized.
  1177. var onReady = function () {
  1178. rtcReady = true;
  1179. RTCUtils.eventEmitter.emit(RTCEvents.RTC_READY, true);
  1180. };
  1181. RTCUtils.init(onReady, options || {});
  1182. // Call onReady() if Temasys plugin is not used
  1183. if (!RTCBrowserType.isTemasysPluginUsed()) {
  1184. onReady();
  1185. }
  1186. }
  1187. RTC.prototype.createLocalStreams = function (streams, change) {
  1188. for (var i = 0; i < streams.length; i++) {
  1189. var localStream = new JitsiLocalTrack(this, streams[i].stream,
  1190. this.eventEmitter, streams[i].videoType,
  1191. streams[i].isGUMStream);
  1192. this.localStreams.push(localStream);
  1193. if (streams[i].isMuted === true)
  1194. localStream.setMute(true);
  1195. if (streams[i].type == "audio") {
  1196. this.localAudio = localStream;
  1197. } else {
  1198. this.localVideo = localStream;
  1199. }
  1200. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  1201. if (change)
  1202. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  1203. this.eventEmitter.emit(eventType, localStream, streams[i].isMuted);
  1204. }
  1205. return this.localStreams;
  1206. };
  1207. RTC.prototype.removeLocalStream = function (stream) {
  1208. for(var i = 0; i < this.localStreams.length; i++) {
  1209. if(this.localStreams[i].getOriginalStream() === stream) {
  1210. delete this.localStreams[i];
  1211. return;
  1212. }
  1213. }
  1214. };
  1215. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  1216. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc,
  1217. this.eventEmitter);
  1218. if(!data.peerjid)
  1219. return;
  1220. var jid = data.peerjid;
  1221. if(!this.remoteStreams[jid]) {
  1222. this.remoteStreams[jid] = {};
  1223. }
  1224. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  1225. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  1226. return remoteStream;
  1227. };
  1228. RTC.getPCConstraints = function () {
  1229. return RTCUtils.pc_constraints;
  1230. };
  1231. RTC.prototype.getUserMediaWithConstraints = function(um, success_callback,
  1232. failure_callback, resolution,
  1233. bandwidth, fps, desktopStream)
  1234. {
  1235. return RTCUtils.getUserMediaWithConstraints(this, um, success_callback,
  1236. failure_callback, resolution, bandwidth, fps, desktopStream);
  1237. };
  1238. RTC.attachMediaStream = function (elSelector, stream) {
  1239. RTCUtils.attachMediaStream(elSelector, stream);
  1240. };
  1241. RTC.getStreamID = function (stream) {
  1242. return RTCUtils.getStreamID(stream);
  1243. };
  1244. RTC.getVideoSrc = function (element) {
  1245. return RTCUtils.getVideoSrc(element);
  1246. };
  1247. RTC.setVideoSrc = function (element, src) {
  1248. RTCUtils.setVideoSrc(element, src);
  1249. };
  1250. RTC.prototype.getVideoElementName = function () {
  1251. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  1252. };
  1253. RTC.prototype.dispose = function() {
  1254. };
  1255. RTC.prototype.muteRemoteVideoStream = function (jid, value) {
  1256. var stream;
  1257. if(this.remoteStreams[jid] &&
  1258. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1259. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  1260. }
  1261. if(!stream)
  1262. return true;
  1263. if (value != stream.muted) {
  1264. stream.setMute(value);
  1265. return true;
  1266. }
  1267. return false;
  1268. };
  1269. RTC.prototype.switchVideoStreams = function (new_stream) {
  1270. this.localVideo.stream = new_stream;
  1271. this.localStreams = [];
  1272. //in firefox we have only one stream object
  1273. if (this.localAudio.getOriginalStream() != new_stream)
  1274. this.localStreams.push(this.localAudio);
  1275. this.localStreams.push(this.localVideo);
  1276. };
  1277. /**
  1278. * Creates <tt>JitsiTrack</tt> instance and replaces it with the local video.
  1279. * The method also handles the sdp changes.
  1280. * @param stream the new MediaStream received by the browser.
  1281. * @param isUsingScreenStream <tt>true</tt> if the stream is for desktop stream.
  1282. * @param callback - function that will be called after the operation is completed.
  1283. */
  1284. RTC.prototype.changeLocalVideo = function (stream, isUsingScreenStream, callback) {
  1285. var oldStream = this.localVideo.getOriginalStream();
  1286. var type = (isUsingScreenStream ? "screen" : "camera");
  1287. var localCallback = callback;
  1288. if(this.localVideo.isMuted() && this.localVideo.videoType !== type) {
  1289. localCallback = function() {
  1290. this.room.setVideoMute(false, function(mute) {
  1291. this.eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);
  1292. }.bind(this));
  1293. callback();
  1294. };
  1295. }
  1296. // FIXME: Workaround for FF/IE/Safari
  1297. if (stream && stream.videoStream) {
  1298. stream = stream.videoStream;
  1299. }
  1300. var videoStream = RTCUtils.createStream(stream, true);
  1301. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  1302. // Stop the stream to trigger onended event for old stream
  1303. oldStream.stop();
  1304. this.switchVideoStreams(videoStream, oldStream);
  1305. this.room.switchStreams(videoStream, oldStream,localCallback);
  1306. };
  1307. /**
  1308. * Creates <tt>JitsiTrack</tt> instance and replaces it with the local audio.
  1309. * The method also handles the sdp changes.
  1310. * @param stream the new MediaStream received by the browser.
  1311. * @param callback - function that will be called after the operation is completed.
  1312. */
  1313. RTC.prototype.changeLocalAudio = function (stream, callback) {
  1314. var oldStream = this.localAudio.getOriginalStream();
  1315. var newStream = RTCUtils.createStream(stream);
  1316. this.localAudio = this.createLocalStream(newStream, "audio", true);
  1317. // Stop the stream to trigger onended event for old stream
  1318. oldStream.stop();
  1319. this.room.switchStreams(newStream, oldStream, callback, true);
  1320. };
  1321. RTC.prototype.isVideoMuted = function (jid) {
  1322. if (jid === APP.xmpp.myJid()) {
  1323. var localVideo = APP.RTC.localVideo;
  1324. return (!localVideo || localVideo.isMuted());
  1325. } else {
  1326. if (!this.remoteStreams[jid] ||
  1327. !this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1328. return null;
  1329. }
  1330. return this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  1331. }
  1332. };
  1333. RTC.prototype.setVideoMute = function (mute, callback, options) {
  1334. if (!this.localVideo)
  1335. return;
  1336. if (mute == this.localVideo.isMuted())
  1337. {
  1338. APP.xmpp.sendVideoInfoPresence(mute);
  1339. if (callback)
  1340. callback(mute);
  1341. }
  1342. else
  1343. {
  1344. this.localVideo.setMute(mute);
  1345. this.room.setVideoMute(
  1346. mute,
  1347. callback,
  1348. options);
  1349. }
  1350. };
  1351. RTC.prototype.setDeviceAvailability = function (devices) {
  1352. if(!devices)
  1353. return;
  1354. if(devices.audio === true || devices.audio === false)
  1355. this.devices.audio = devices.audio;
  1356. if(devices.video === true || devices.video === false)
  1357. this.devices.video = devices.video;
  1358. this.eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  1359. };
  1360. module.exports = RTC;
  1361. },{"../../service/RTC/MediaStreamTypes":70,"../../service/RTC/RTCEvents.js":71,"../../service/RTC/StreamEventTypes.js":73,"../../service/desktopsharing/DesktopSharingEventTypes":75,"../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){
  1362. var currentBrowser;
  1363. var browserVersion;
  1364. var RTCBrowserType = {
  1365. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  1366. RTC_BROWSER_OPERA: "rtc_browser.opera",
  1367. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  1368. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  1369. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  1370. getBrowserType: function () {
  1371. return currentBrowser;
  1372. },
  1373. isChrome: function () {
  1374. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  1375. },
  1376. isOpera: function () {
  1377. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  1378. },
  1379. isFirefox: function () {
  1380. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  1381. },
  1382. isIExplorer: function () {
  1383. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1384. },
  1385. isSafari: function () {
  1386. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  1387. },
  1388. isTemasysPluginUsed: function () {
  1389. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  1390. },
  1391. getFirefoxVersion: function () {
  1392. return RTCBrowserType.isFirefox() ? browserVersion : null;
  1393. },
  1394. getChromeVersion: function () {
  1395. return RTCBrowserType.isChrome() ? browserVersion : null;
  1396. },
  1397. usesPlanB: function() {
  1398. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  1399. RTCBrowserType.isTemasysPluginUsed();
  1400. },
  1401. usesUnifiedPlan: function() {
  1402. return RTCBrowserType.isFirefox();
  1403. }
  1404. // Add version getters for other browsers when needed
  1405. };
  1406. // detectOpera() must be called before detectChrome() !!!
  1407. // otherwise Opera wil be detected as Chrome
  1408. function detectChrome() {
  1409. if (navigator.webkitGetUserMedia) {
  1410. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  1411. var userAgent = navigator.userAgent.toLowerCase();
  1412. // We can assume that user agent is chrome, because it's
  1413. // enforced when 'ext' streaming method is set
  1414. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  1415. console.log("This appears to be Chrome, ver: " + ver);
  1416. return ver;
  1417. }
  1418. return null;
  1419. }
  1420. function detectOpera() {
  1421. var userAgent = navigator.userAgent;
  1422. if (userAgent.match(/Opera|OPR/)) {
  1423. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  1424. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  1425. console.info("This appears to be Opera, ver: " + version);
  1426. return version;
  1427. }
  1428. return null;
  1429. }
  1430. function detectFirefox() {
  1431. if (navigator.mozGetUserMedia) {
  1432. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1433. var version = parseInt(
  1434. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1435. console.log('This appears to be Firefox, ver: ' + version);
  1436. return version;
  1437. }
  1438. return null;
  1439. }
  1440. function detectSafari() {
  1441. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1442. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1443. console.info("This appears to be Safari");
  1444. // FIXME detect Safari version when needed
  1445. return 1;
  1446. }
  1447. return null;
  1448. }
  1449. function detectIE() {
  1450. var version;
  1451. var ua = window.navigator.userAgent;
  1452. var msie = ua.indexOf('MSIE ');
  1453. if (msie > 0) {
  1454. // IE 10 or older => return version number
  1455. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1456. }
  1457. var trident = ua.indexOf('Trident/');
  1458. if (!version && trident > 0) {
  1459. // IE 11 => return version number
  1460. var rv = ua.indexOf('rv:');
  1461. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1462. }
  1463. var edge = ua.indexOf('Edge/');
  1464. if (!version && edge > 0) {
  1465. // IE 12 => return version number
  1466. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1467. }
  1468. if (version) {
  1469. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1470. console.info("This appears to be IExplorer, ver: " + version);
  1471. }
  1472. return version;
  1473. }
  1474. function detectBrowser() {
  1475. var version;
  1476. var detectors = [
  1477. detectOpera,
  1478. detectChrome,
  1479. detectFirefox,
  1480. detectIE,
  1481. detectSafari
  1482. ];
  1483. // Try all browser detectors
  1484. for (var i = 0; i < detectors.length; i++) {
  1485. version = detectors[i]();
  1486. if (version)
  1487. return version;
  1488. }
  1489. console.error("Failed to detect browser type");
  1490. return undefined;
  1491. }
  1492. browserVersion = detectBrowser();
  1493. module.exports = RTCBrowserType;
  1494. },{}],15:[function(require,module,exports){
  1495. /* global config, require, attachMediaStream, getUserMedia */
  1496. var RTCBrowserType = require("./RTCBrowserType");
  1497. var Resolutions = require("../../service/RTC/Resolutions");
  1498. var AdapterJS = require("./adapter.screenshare");
  1499. var SDPUtil = require("../xmpp/SDPUtil");
  1500. var EventEmitter = require("events");
  1501. function DummyMediaStream(id) {
  1502. this.id = id;
  1503. this.label = id;
  1504. this.stop = function() { };
  1505. this.getAudioTracks = function() { return []; };
  1506. this.getVideoTracks = function() { return []; };
  1507. }
  1508. function getPreviousResolution(resolution) {
  1509. if(!Resolutions[resolution])
  1510. return null;
  1511. var order = Resolutions[resolution].order;
  1512. var res = null;
  1513. var resName = null;
  1514. for(var i in Resolutions) {
  1515. var tmp = Resolutions[i];
  1516. if(res == null || (res.order < tmp.order && tmp.order < order)) {
  1517. resName = i;
  1518. res = tmp;
  1519. }
  1520. }
  1521. return resName;
  1522. }
  1523. function setResolutionConstraints(constraints, resolution, isAndroid) {
  1524. if (Resolutions[resolution]) {
  1525. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1526. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1527. }
  1528. else if (isAndroid) {
  1529. // FIXME can't remember if the purpose of this was to always request
  1530. // low resolution on Android ? if yes it should be moved up front
  1531. constraints.video.mandatory.minWidth = 320;
  1532. constraints.video.mandatory.minHeight = 240;
  1533. constraints.video.mandatory.maxFrameRate = 15;
  1534. }
  1535. if (constraints.video.mandatory.minWidth)
  1536. constraints.video.mandatory.maxWidth =
  1537. constraints.video.mandatory.minWidth;
  1538. if (constraints.video.mandatory.minHeight)
  1539. constraints.video.mandatory.maxHeight =
  1540. constraints.video.mandatory.minHeight;
  1541. }
  1542. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1543. {
  1544. var constraints = {audio: false, video: false};
  1545. if (um.indexOf('video') >= 0) {
  1546. // same behaviour as true
  1547. constraints.video = { mandatory: {}, optional: [] };
  1548. constraints.video.optional.push({ googLeakyBucket: true });
  1549. setResolutionConstraints(constraints, resolution, isAndroid);
  1550. }
  1551. if (um.indexOf('audio') >= 0) {
  1552. if (!RTCBrowserType.isFirefox()) {
  1553. // same behaviour as true
  1554. constraints.audio = { mandatory: {}, optional: []};
  1555. // if it is good enough for hangouts...
  1556. constraints.audio.optional.push(
  1557. {googEchoCancellation: true},
  1558. {googAutoGainControl: true},
  1559. {googNoiseSupression: true},
  1560. {googHighpassFilter: true},
  1561. {googNoisesuppression2: true},
  1562. {googEchoCancellation2: true},
  1563. {googAutoGainControl2: true}
  1564. );
  1565. } else {
  1566. constraints.audio = true;
  1567. }
  1568. }
  1569. if (um.indexOf('screen') >= 0) {
  1570. if (RTCBrowserType.isChrome()) {
  1571. constraints.video = {
  1572. mandatory: {
  1573. chromeMediaSource: "screen",
  1574. googLeakyBucket: true,
  1575. maxWidth: window.screen.width,
  1576. maxHeight: window.screen.height,
  1577. maxFrameRate: 3
  1578. },
  1579. optional: []
  1580. };
  1581. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1582. constraints.video = {
  1583. optional: [
  1584. {
  1585. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1586. }
  1587. ]
  1588. };
  1589. } else {
  1590. console.error(
  1591. "'screen' WebRTC media source is supported only in Chrome" +
  1592. " and with Temasys plugin");
  1593. }
  1594. }
  1595. if (um.indexOf('desktop') >= 0) {
  1596. constraints.video = {
  1597. mandatory: {
  1598. chromeMediaSource: "desktop",
  1599. chromeMediaSourceId: desktopStream,
  1600. googLeakyBucket: true,
  1601. maxWidth: window.screen.width,
  1602. maxHeight: window.screen.height,
  1603. maxFrameRate: 3
  1604. },
  1605. optional: []
  1606. };
  1607. }
  1608. if (bandwidth) {
  1609. if (!constraints.video) {
  1610. //same behaviour as true
  1611. constraints.video = {mandatory: {}, optional: []};
  1612. }
  1613. constraints.video.optional.push({bandwidth: bandwidth});
  1614. }
  1615. if (fps) {
  1616. // for some cameras it might be necessary to request 30fps
  1617. // so they choose 30fps mjpg over 10fps yuy2
  1618. if (!constraints.video) {
  1619. // same behaviour as true;
  1620. constraints.video = {mandatory: {}, optional: []};
  1621. }
  1622. constraints.video.mandatory.minFrameRate = fps;
  1623. }
  1624. return constraints;
  1625. }
  1626. //Options parameter is to pass config options. Currently uses only "useIPv6".
  1627. var RTCUtils = {
  1628. eventEmitter: new EventEmitter(),
  1629. init: function (onTemasysPluginReady, options) {
  1630. var self = this;
  1631. if (RTCBrowserType.isFirefox()) {
  1632. var FFversion = RTCBrowserType.getFirefoxVersion();
  1633. if (FFversion >= 40) {
  1634. this.peerconnection = mozRTCPeerConnection;
  1635. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1636. this.pc_constraints = {};
  1637. this.attachMediaStream = function (element, stream) {
  1638. // srcObject is being standardized and FF will eventually
  1639. // support that unprefixed. FF also supports the
  1640. // "element.src = URL.createObjectURL(...)" combo, but that
  1641. // will be deprecated in favour of srcObject.
  1642. //
  1643. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1644. // https://github.com/webrtc/samples/issues/302
  1645. if (!element[0])
  1646. return;
  1647. element[0].mozSrcObject = stream;
  1648. element[0].play();
  1649. };
  1650. this.getStreamID = function (stream) {
  1651. var id = stream.id;
  1652. if (!id) {
  1653. var tracks = stream.getVideoTracks();
  1654. if (!tracks || tracks.length === 0) {
  1655. tracks = stream.getAudioTracks();
  1656. }
  1657. id = tracks[0].id;
  1658. }
  1659. return SDPUtil.filter_special_chars(id);
  1660. };
  1661. this.getVideoSrc = function (element) {
  1662. if (!element)
  1663. return null;
  1664. return element.mozSrcObject;
  1665. };
  1666. this.setVideoSrc = function (element, src) {
  1667. if (element)
  1668. element.mozSrcObject = src;
  1669. };
  1670. RTCSessionDescription = mozRTCSessionDescription;
  1671. RTCIceCandidate = mozRTCIceCandidate;
  1672. } else {
  1673. console.error(
  1674. "Firefox version too old: " + FFversion + ". Required >= 40.");
  1675. window.location.href = 'unsupported_browser.html';
  1676. return;
  1677. }
  1678. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1679. this.peerconnection = webkitRTCPeerConnection;
  1680. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1681. this.attachMediaStream = function (element, stream) {
  1682. element.attr('src', webkitURL.createObjectURL(stream));
  1683. };
  1684. this.getStreamID = function (stream) {
  1685. // streams from FF endpoints have the characters '{' and '}'
  1686. // that make jQuery choke.
  1687. return SDPUtil.filter_special_chars(stream.id);
  1688. };
  1689. this.getVideoSrc = function (element) {
  1690. if (!element)
  1691. return null;
  1692. return element.getAttribute("src");
  1693. };
  1694. this.setVideoSrc = function (element, src) {
  1695. if (element)
  1696. element.setAttribute("src", src);
  1697. };
  1698. // DTLS should now be enabled by default but..
  1699. this.pc_constraints = {'optional': [
  1700. {'DtlsSrtpKeyAgreement': 'true'}
  1701. ]};
  1702. if (options.useIPv6) {
  1703. // https://code.google.com/p/webrtc/issues/detail?id=2828
  1704. this.pc_constraints.optional.push({googIPv6: true});
  1705. }
  1706. if (navigator.userAgent.indexOf('Android') != -1) {
  1707. this.pc_constraints = {}; // disable DTLS on Android
  1708. }
  1709. if (!webkitMediaStream.prototype.getVideoTracks) {
  1710. webkitMediaStream.prototype.getVideoTracks = function () {
  1711. return this.videoTracks;
  1712. };
  1713. }
  1714. if (!webkitMediaStream.prototype.getAudioTracks) {
  1715. webkitMediaStream.prototype.getAudioTracks = function () {
  1716. return this.audioTracks;
  1717. };
  1718. }
  1719. }
  1720. // Detect IE/Safari
  1721. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1722. //AdapterJS.WebRTCPlugin.setLogLevel(
  1723. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1724. AdapterJS.webRTCReady(function (isPlugin) {
  1725. self.peerconnection = RTCPeerConnection;
  1726. self.getUserMedia = getUserMedia;
  1727. self.attachMediaStream = function (elSel, stream) {
  1728. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1729. return;
  1730. }
  1731. attachMediaStream(elSel[0], stream);
  1732. };
  1733. self.getStreamID = function (stream) {
  1734. var id = SDPUtil.filter_special_chars(stream.label);
  1735. return id;
  1736. };
  1737. self.getVideoSrc = function (element) {
  1738. if (!element) {
  1739. console.warn("Attempt to get video SRC of null element");
  1740. return null;
  1741. }
  1742. var children = element.children;
  1743. for (var i = 0; i !== children.length; ++i) {
  1744. if (children[i].name === 'streamId') {
  1745. return children[i].value;
  1746. }
  1747. }
  1748. //console.info(element.id + " SRC: " + src);
  1749. return null;
  1750. };
  1751. self.setVideoSrc = function (element, src) {
  1752. //console.info("Set video src: ", element, src);
  1753. if (!src) {
  1754. console.warn("Not attaching video stream, 'src' is null");
  1755. return;
  1756. }
  1757. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1758. var stream = AdapterJS.WebRTCPlugin.plugin
  1759. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1760. attachMediaStream(element, stream);
  1761. };
  1762. onTemasysPluginReady(isPlugin);
  1763. });
  1764. } else {
  1765. try {
  1766. console.log('Browser does not appear to be WebRTC-capable');
  1767. } catch (e) {
  1768. }
  1769. window.location.href = 'unsupported_browser.html';
  1770. }
  1771. },
  1772. getUserMediaWithConstraints: function (RTC, um, success_callback, failure_callback, resolution, bandwidth, fps, desktopStream) {
  1773. // Check if we are running on Android device
  1774. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1775. var constraints = getConstraints(
  1776. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1777. console.info("Get media constraints", constraints);
  1778. var self = this;
  1779. try {
  1780. this.getUserMedia(constraints,
  1781. function (stream) {
  1782. console.log('onUserMediaSuccess');
  1783. self.setAvailableDevices(RTC, um, true);
  1784. success_callback(stream);
  1785. },
  1786. function (error) {
  1787. self.setAvailableDevices(RTC, um, false);
  1788. console.warn('Failed to get access to local media. Error ',
  1789. error, constraints);
  1790. if (failure_callback) {
  1791. failure_callback(error, resolution);
  1792. }
  1793. });
  1794. } catch (e) {
  1795. console.error('GUM failed: ', e);
  1796. if (failure_callback) {
  1797. failure_callback(e);
  1798. }
  1799. }
  1800. },
  1801. setAvailableDevices: function (RTC, um, available) {
  1802. var devices = {};
  1803. if (um.indexOf("video") != -1) {
  1804. devices.video = available;
  1805. }
  1806. if (um.indexOf("audio") != -1) {
  1807. devices.audio = available;
  1808. }
  1809. RTC.setDeviceAvailability(devices);
  1810. },
  1811. /**
  1812. * Creates the local MediaStreams.
  1813. * @param RTC the rtc service.
  1814. * @param devices the devices that will be requested
  1815. * @param usageOptions object with devices that should be requested.
  1816. * @param resolution resolution constraints
  1817. * @param dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1818. * type: "audio" or "video", isMuted: true/false, videoType: "camera" or "desktop"}
  1819. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1820. * @returns {*} Promise object that will receive the new JitsiTracks
  1821. */
  1822. obtainAudioAndVideoPermissions: function (RTC, devices, usageOptions, resolution, dontCreateJitsiTracks) {
  1823. var self = this;
  1824. // Get AV
  1825. return new Promise(function (resolve, reject) {
  1826. var successCallback = function (stream) {
  1827. var streams = self.successCallback(RTC , stream, usageOptions);
  1828. resolve(dontCreateJitsiTracks? streams: RTC.createLocalStreams(streams));
  1829. };
  1830. if (!devices)
  1831. devices = ['audio', 'video'];
  1832. var newDevices = [];
  1833. if (usageOptions)
  1834. for (var i = 0; i < devices.length; i++) {
  1835. var device = devices[i];
  1836. if (usageOptions[device] === true)
  1837. newDevices.push(device);
  1838. }
  1839. else
  1840. newDevices = devices;
  1841. if (newDevices.length === 0) {
  1842. successCallback();
  1843. return;
  1844. }
  1845. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1846. // With FF/IE we can't split the stream into audio and video because FF
  1847. // doesn't support media stream constructors. So, we need to get the
  1848. // audio stream separately from the video stream using two distinct GUM
  1849. // calls. Not very user friendly :-( but we don't have many other
  1850. // options neither.
  1851. //
  1852. // Note that we pack those 2 streams in a single object and pass it to
  1853. // the successCallback method.
  1854. var obtainVideo = function (audioStream) {
  1855. self.getUserMediaWithConstraints(
  1856. RTC,
  1857. ['video'],
  1858. function (videoStream) {
  1859. return successCallback({
  1860. audioStream: audioStream,
  1861. videoStream: videoStream
  1862. });
  1863. },
  1864. function (error, resolution) {
  1865. console.error(
  1866. 'failed to obtain video stream - stop', error);
  1867. self.errorCallback(error, resolve, RTC, resolution, dontCreateJitsiTracks);
  1868. },
  1869. config.resolution || '360');
  1870. };
  1871. var obtainAudio = function () {
  1872. self.getUserMediaWithConstraints(
  1873. RTC,
  1874. ['audio'],
  1875. function (audioStream) {
  1876. if (newDevices.indexOf('video') !== -1)
  1877. obtainVideo(audioStream);
  1878. },
  1879. function (error) {
  1880. console.error(
  1881. 'failed to obtain audio stream - stop', error);
  1882. self.errorCallback(error, resolve, RTC, null, dontCreateJitsiTracks);
  1883. }
  1884. );
  1885. };
  1886. if (newDevices.indexOf('audio') !== -1) {
  1887. obtainAudio();
  1888. } else {
  1889. obtainVideo(null);
  1890. }
  1891. } else {
  1892. this.getUserMediaWithConstraints(
  1893. RTC,
  1894. newDevices,
  1895. function (stream) {
  1896. successCallback(stream);
  1897. },
  1898. function (error, resolution) {
  1899. self.errorCallback(error, resolve, RTC, resolution, dontCreateJitsiTracks);
  1900. },
  1901. resolution || '360');
  1902. }
  1903. }.bind(this));
  1904. },
  1905. /**
  1906. * Successful callback called from GUM.
  1907. * @param RTC the rtc service
  1908. * @param stream the new MediaStream
  1909. * @param usageOptions the list of the devices that should be queried.
  1910. * @returns {*}
  1911. */
  1912. successCallback: function (RTC, stream, usageOptions) {
  1913. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1914. // it's an object with two properties: audioStream, videoStream.
  1915. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1916. console.log('got', stream, stream.getAudioTracks().length,
  1917. stream.getVideoTracks().length);
  1918. return this.handleLocalStream(RTC, stream, usageOptions);
  1919. },
  1920. /**
  1921. * Error callback called from GUM. Retries the GUM call with different resolutions.
  1922. * @param error the error
  1923. * @param resolve the resolve funtion that will be called on success.
  1924. * @param RTC the rtc service
  1925. * @param currentResolution the last resolution used for GUM.
  1926. * @param dontCreateJitsiTracks if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1927. * type: "audio" or "video", isMuted: true/false, videoType: "camera" or "desktop"}
  1928. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1929. */
  1930. errorCallback: function (error, resolve, RTC, currentResolution, dontCreateJitsiTracks) {
  1931. var self = this;
  1932. console.error('failed to obtain audio/video stream - trying audio only', error);
  1933. var resolution = getPreviousResolution(currentResolution);
  1934. if (typeof error == "object" && error.constraintName && error.name
  1935. && (error.name == "ConstraintNotSatisfiedError" ||
  1936. error.name == "OverconstrainedError") &&
  1937. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1938. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1939. && resolution != null) {
  1940. self.getUserMediaWithConstraints(RTC, ['audio', 'video'],
  1941. function (stream) {
  1942. var streams = self.successCallback(RTC, stream);
  1943. resolve(dontCreateJitsiTracks? streams: RTC.createLocalStreams(streams));
  1944. }, function (error, resolution) {
  1945. return self.errorCallback(error, resolve, RTC, resolution, dontCreateJitsiTracks);
  1946. }, resolution);
  1947. }
  1948. else {
  1949. self.getUserMediaWithConstraints(
  1950. RTC,
  1951. ['audio'],
  1952. function (stream) {
  1953. var streams = self.successCallback(RTC, stream);
  1954. resolve(dontCreateJitsiTracks? streams: RTC.createLocalStreams(streams));
  1955. },
  1956. function (error) {
  1957. console.error('failed to obtain audio/video stream - stop',
  1958. error);
  1959. var streams = self.successCallback(RTC, null);
  1960. resolve(dontCreateJitsiTracks? streams: RTC.createLocalStreams(streams));
  1961. }
  1962. );
  1963. }
  1964. },
  1965. /**
  1966. * Handles the newly created Media Streams.
  1967. * @param service the rtc service
  1968. * @param stream the new Media Streams
  1969. * @param usageOptions the list of the devices that should be queried.
  1970. * @returns {*[]} Promise object with the new Media Streams.
  1971. */
  1972. handleLocalStream: function (service, stream, usageOptions) {
  1973. var audioStream, videoStream;
  1974. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1975. // an object with two properties: audioStream, videoStream.
  1976. if (window.webkitMediaStream) {
  1977. audioStream = new webkitMediaStream();
  1978. videoStream = new webkitMediaStream();
  1979. if (stream) {
  1980. var audioTracks = stream.getAudioTracks();
  1981. for (var i = 0; i < audioTracks.length; i++) {
  1982. audioStream.addTrack(audioTracks[i]);
  1983. }
  1984. var videoTracks = stream.getVideoTracks();
  1985. for (i = 0; i < videoTracks.length; i++) {
  1986. videoStream.addTrack(videoTracks[i]);
  1987. }
  1988. }
  1989. }
  1990. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  1991. if (stream && stream.audioStream)
  1992. audioStream = stream.audioStream;
  1993. else
  1994. audioStream = new DummyMediaStream("dummyAudio");
  1995. if (stream && stream.videoStream)
  1996. videoStream = stream.videoStream;
  1997. else
  1998. videoStream = new DummyMediaStream("dummyVideo");
  1999. }
  2000. var audioMuted = (usageOptions && usageOptions.audio === false),
  2001. videoMuted = (usageOptions && usageOptions.video === false);
  2002. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  2003. videoGUM = (!usageOptions || usageOptions.video !== false);
  2004. return [
  2005. {stream: audioStream, type: "audio", isMuted: audioMuted, isGUMStream: audioGUM, videoType: null},
  2006. {stream: videoStream, type: "video", isMuted: videoMuted, isGUMStream: videoGUM, videoType: "camera"}
  2007. ];
  2008. },
  2009. createStream: function (stream, isVideo) {
  2010. var newStream = null;
  2011. if (window.webkitMediaStream) {
  2012. newStream = new webkitMediaStream();
  2013. if (newStream) {
  2014. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  2015. for (var i = 0; i < tracks.length; i++) {
  2016. newStream.addTrack(tracks[i]);
  2017. }
  2018. }
  2019. } else {
  2020. // FIXME: this is duplicated with 'handleLocalStream' !!!
  2021. if (stream) {
  2022. newStream = stream;
  2023. } else {
  2024. newStream =
  2025. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  2026. }
  2027. }
  2028. return newStream;
  2029. }
  2030. }
  2031. module.exports = RTCUtils;
  2032. },{"../../service/RTC/Resolutions":72,"../xmpp/SDPUtil":25,"./RTCBrowserType":14,"./adapter.screenshare":16,"events":77}],16:[function(require,module,exports){
  2033. /*! adapterjs - custom version from - 2015-08-12 */
  2034. // Adapter's interface.
  2035. var AdapterJS = AdapterJS || {};
  2036. // Browserify compatibility
  2037. if(typeof exports !== 'undefined') {
  2038. module.exports = AdapterJS;
  2039. }
  2040. AdapterJS.options = AdapterJS.options || {};
  2041. // uncomment to get virtual webcams
  2042. // AdapterJS.options.getAllCams = true;
  2043. // uncomment to prevent the install prompt when the plugin in not yet installed
  2044. // AdapterJS.options.hidePluginInstallPrompt = true;
  2045. // AdapterJS version
  2046. AdapterJS.VERSION = '0.11.1';
  2047. // This function will be called when the WebRTC API is ready to be used
  2048. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  2049. // the plugin
  2050. // You may Override this function to synchronise the start of your application
  2051. // with the WebRTC API being ready.
  2052. // If you decide not to override use this synchronisation, it may result in
  2053. // an extensive CPU usage on the plugin start (once per tab loaded)
  2054. // Params:
  2055. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  2056. //
  2057. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  2058. // The WebRTC API is ready.
  2059. // Override me and do whatever you want here
  2060. };
  2061. // Sets a callback function to be called when the WebRTC interface is ready.
  2062. // The first argument is the function to callback.\
  2063. // Throws an error if the first argument is not a function
  2064. AdapterJS.webRTCReady = function (callback) {
  2065. if (typeof callback !== 'function') {
  2066. throw new Error('Callback provided is not a function');
  2067. }
  2068. if (true === AdapterJS.onwebrtcreadyDone) {
  2069. // All WebRTC interfaces are ready, just call the callback
  2070. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  2071. } else {
  2072. // will be triggered automatically when your browser/plugin is ready.
  2073. AdapterJS.onwebrtcready = callback;
  2074. }
  2075. };
  2076. // Plugin namespace
  2077. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  2078. // The object to store plugin information
  2079. AdapterJS.WebRTCPlugin.pluginInfo = {
  2080. prefix : 'Tem',
  2081. plugName : 'TemWebRTCPlugin',
  2082. pluginId : 'plugin0',
  2083. type : 'application/x-temwebrtcplugin',
  2084. onload : '__TemWebRTCReady0',
  2085. portalLink : 'http://skylink.io/plugin/',
  2086. downloadLink : null, //set below
  2087. companyName: 'Temasys'
  2088. };
  2089. if(!!navigator.platform.match(/^Mac/i)) {
  2090. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  2091. }
  2092. else if(!!navigator.platform.match(/^Win/i)) {
  2093. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  2094. }
  2095. // Unique identifier of each opened page
  2096. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  2097. // Use this whenever you want to call the plugin.
  2098. AdapterJS.WebRTCPlugin.plugin = null;
  2099. // Set log level for the plugin once it is ready.
  2100. // The different values are
  2101. // This is an asynchronous function that will run when the plugin is ready
  2102. AdapterJS.WebRTCPlugin.setLogLevel = null;
  2103. // Defines webrtc's JS interface according to the plugin's implementation.
  2104. // Define plugin Browsers as WebRTC Interface.
  2105. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  2106. // This function detects whether or not a plugin is installed.
  2107. // Checks if Not IE (firefox, for example), else if it's IE,
  2108. // we're running IE and do something. If not it is not supported.
  2109. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  2110. // Lets adapter.js wait until the the document is ready before injecting the plugin
  2111. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  2112. // Inject the HTML DOM object element into the page.
  2113. AdapterJS.WebRTCPlugin.injectPlugin = null;
  2114. // States of readiness that the plugin goes through when
  2115. // being injected and stated
  2116. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  2117. NONE : 0, // no plugin use
  2118. INITIALIZING : 1, // Detected need for plugin
  2119. INJECTING : 2, // Injecting plugin
  2120. INJECTED: 3, // Plugin element injected but not usable yet
  2121. READY: 4 // Plugin ready to be used
  2122. };
  2123. // Current state of the plugin. You cannot use the plugin before this is
  2124. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  2125. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  2126. // True is AdapterJS.onwebrtcready was already called, false otherwise
  2127. // Used to make sure AdapterJS.onwebrtcready is only called once
  2128. AdapterJS.onwebrtcreadyDone = false;
  2129. // Log levels for the plugin.
  2130. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  2131. /*
  2132. Log outputs are prefixed in some cases.
  2133. INFO: Information reported by the plugin.
  2134. ERROR: Errors originating from within the plugin.
  2135. WEBRTC: Error originating from within the libWebRTC library
  2136. */
  2137. // From the least verbose to the most verbose
  2138. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  2139. NONE : 'NONE',
  2140. ERROR : 'ERROR',
  2141. WARNING : 'WARNING',
  2142. INFO: 'INFO',
  2143. VERBOSE: 'VERBOSE',
  2144. SENSITIVE: 'SENSITIVE'
  2145. };
  2146. // Does a waiting check before proceeding to load the plugin.
  2147. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  2148. // This methid will use an interval to wait for the plugin to be ready.
  2149. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  2150. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  2151. // This function will be called when plugin is ready. It sends necessary
  2152. // details to the plugin.
  2153. // The function will wait for the document to be ready and the set the
  2154. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  2155. // indicating that it can start being requested.
  2156. // This function is not in the IE/Safari condition brackets so that
  2157. // TemPluginLoaded function might be called on Chrome/Firefox.
  2158. // This function is the only private function that is not encapsulated to
  2159. // allow the plugin method to be called.
  2160. __TemWebRTCReady0 = function () {
  2161. if (document.readyState === 'complete') {
  2162. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  2163. AdapterJS.maybeThroughWebRTCReady();
  2164. } else {
  2165. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  2166. if (document.readyState === 'complete') {
  2167. // TODO: update comments, we wait for the document to be ready
  2168. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  2169. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  2170. AdapterJS.maybeThroughWebRTCReady();
  2171. }
  2172. }, 100);
  2173. }
  2174. };
  2175. AdapterJS.maybeThroughWebRTCReady = function() {
  2176. if (!AdapterJS.onwebrtcreadyDone) {
  2177. AdapterJS.onwebrtcreadyDone = true;
  2178. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  2179. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  2180. }
  2181. }
  2182. };
  2183. // Text namespace
  2184. AdapterJS.TEXT = {
  2185. PLUGIN: {
  2186. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  2187. 'to work on this browser.',
  2188. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  2189. BUTTON: 'Install Now'
  2190. },
  2191. REFRESH: {
  2192. REQUIRE_REFRESH: 'Please refresh page',
  2193. BUTTON: 'Refresh Page'
  2194. }
  2195. };
  2196. // The result of ice connection states.
  2197. // - starting: Ice connection is starting.
  2198. // - checking: Ice connection is checking.
  2199. // - connected Ice connection is connected.
  2200. // - completed Ice connection is connected.
  2201. // - done Ice connection has been completed.
  2202. // - disconnected Ice connection has been disconnected.
  2203. // - failed Ice connection has failed.
  2204. // - closed Ice connection is closed.
  2205. AdapterJS._iceConnectionStates = {
  2206. starting : 'starting',
  2207. checking : 'checking',
  2208. connected : 'connected',
  2209. completed : 'connected',
  2210. done : 'completed',
  2211. disconnected : 'disconnected',
  2212. failed : 'failed',
  2213. closed : 'closed'
  2214. };
  2215. //The IceConnection states that has been fired for each peer.
  2216. AdapterJS._iceConnectionFiredStates = [];
  2217. // Check if WebRTC Interface is defined.
  2218. AdapterJS.isDefined = null;
  2219. // This function helps to retrieve the webrtc detected browser information.
  2220. // This sets:
  2221. // - webrtcDetectedBrowser: The browser agent name.
  2222. // - webrtcDetectedVersion: The browser version.
  2223. // - webrtcDetectedType: The types of webRTC support.
  2224. // - 'moz': Mozilla implementation of webRTC.
  2225. // - 'webkit': WebKit implementation of webRTC.
  2226. // - 'plugin': Using the plugin implementation.
  2227. AdapterJS.parseWebrtcDetectedBrowser = function () {
  2228. var hasMatch, checkMatch = navigator.userAgent.match(
  2229. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  2230. if (/trident/i.test(checkMatch[1])) {
  2231. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  2232. webrtcDetectedBrowser = 'IE';
  2233. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  2234. } else if (checkMatch[1] === 'Chrome') {
  2235. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2236. if (hasMatch !== null) {
  2237. webrtcDetectedBrowser = 'opera';
  2238. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  2239. }
  2240. }
  2241. if (navigator.userAgent.indexOf('Safari')) {
  2242. if (typeof InstallTrigger !== 'undefined') {
  2243. webrtcDetectedBrowser = 'firefox';
  2244. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  2245. webrtcDetectedBrowser = 'IE';
  2246. } else if (
  2247. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  2248. webrtcDetectedBrowser = 'safari';
  2249. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  2250. webrtcDetectedBrowser = 'opera';
  2251. } else if (!!window.chrome) {
  2252. webrtcDetectedBrowser = 'chrome';
  2253. }
  2254. }
  2255. if (!webrtcDetectedBrowser) {
  2256. webrtcDetectedVersion = checkMatch[1];
  2257. }
  2258. if (!webrtcDetectedVersion) {
  2259. try {
  2260. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  2261. [navigator.appName, navigator.appVersion, '-?'];
  2262. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  2263. checkMatch.splice(1, 1, hasMatch[1]);
  2264. }
  2265. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  2266. } catch (error) { }
  2267. }
  2268. };
  2269. // To fix configuration as some browsers does not support
  2270. // the 'urls' attribute.
  2271. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  2272. if (pcConfig === null) {
  2273. return;
  2274. }
  2275. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  2276. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  2277. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  2278. delete pcConfig.iceServers[i].urls;
  2279. }
  2280. }
  2281. };
  2282. AdapterJS.addEvent = function(elem, evnt, func) {
  2283. if (elem.addEventListener) { // W3C DOM
  2284. elem.addEventListener(evnt, func, false);
  2285. } else if (elem.attachEvent) {// OLD IE DOM
  2286. elem.attachEvent('on'+evnt, func);
  2287. } else { // No much to do
  2288. elem[evnt] = func;
  2289. }
  2290. };
  2291. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  2292. // only inject once the page is ready
  2293. if (document.readyState !== 'complete') {
  2294. return;
  2295. }
  2296. var w = window;
  2297. var i = document.createElement('iframe');
  2298. i.style.position = 'fixed';
  2299. i.style.top = '-41px';
  2300. i.style.left = 0;
  2301. i.style.right = 0;
  2302. i.style.width = '100%';
  2303. i.style.height = '40px';
  2304. i.style.backgroundColor = '#ffffe1';
  2305. i.style.border = 'none';
  2306. i.style.borderBottom = '1px solid #888888';
  2307. i.style.zIndex = '9999999';
  2308. if(typeof i.style.webkitTransition === 'string') {
  2309. i.style.webkitTransition = 'all .5s ease-out';
  2310. } else if(typeof i.style.transition === 'string') {
  2311. i.style.transition = 'all .5s ease-out';
  2312. }
  2313. document.body.appendChild(i);
  2314. c = (i.contentWindow) ? i.contentWindow :
  2315. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  2316. c.document.open();
  2317. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  2318. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  2319. 'middle; cursor: default;">' + text + '</span>');
  2320. if(buttonText && buttonLink) {
  2321. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  2322. c.document.close();
  2323. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  2324. if (!!displayRefreshBar) {
  2325. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  2326. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  2327. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  2328. }
  2329. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  2330. e.preventDefault();
  2331. try {
  2332. event.cancelBubble = true;
  2333. } catch(error) { }
  2334. var pluginInstallInterval = setInterval(function(){
  2335. if(! isIE) {
  2336. navigator.plugins.refresh(false);
  2337. }
  2338. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2339. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2340. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2341. function() {
  2342. clearInterval(pluginInstallInterval);
  2343. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  2344. },
  2345. function() { //Does nothing because not used here
  2346. });
  2347. } , 500);
  2348. });
  2349. }else {
  2350. c.document.close();
  2351. }
  2352. AdapterJS.addEvent(c.document, 'click', function() {
  2353. w.document.body.removeChild(i);
  2354. });
  2355. setTimeout(function() {
  2356. if(typeof i.style.webkitTransform === 'string') {
  2357. i.style.webkitTransform = 'translateY(40px)';
  2358. } else if(typeof i.style.transform === 'string') {
  2359. i.style.transform = 'translateY(40px)';
  2360. } else {
  2361. i.style.top = '0px';
  2362. }
  2363. }, 300);
  2364. };
  2365. // -----------------------------------------------------------
  2366. // Detected webrtc implementation. Types are:
  2367. // - 'moz': Mozilla implementation of webRTC.
  2368. // - 'webkit': WebKit implementation of webRTC.
  2369. // - 'plugin': Using the plugin implementation.
  2370. webrtcDetectedType = null;
  2371. // Detected webrtc datachannel support. Types are:
  2372. // - 'SCTP': SCTP datachannel support.
  2373. // - 'RTP': RTP datachannel support.
  2374. webrtcDetectedDCSupport = null;
  2375. // Set the settings for creating DataChannels, MediaStream for
  2376. // Cross-browser compability.
  2377. // - This is only for SCTP based support browsers.
  2378. // the 'urls' attribute.
  2379. checkMediaDataChannelSettings =
  2380. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  2381. if (typeof callback !== 'function') {
  2382. return;
  2383. }
  2384. var beOfferer = true;
  2385. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  2386. // Nightly version does not require MozDontOfferDataChannel for interop
  2387. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  2388. var isPeerFirefox = peerBrowserAgent === 'firefox';
  2389. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  2390. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  2391. // Resends an updated version of constraints for MozDataChannel to work
  2392. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  2393. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  2394. try {
  2395. delete constraints.mandatory.MozDontOfferDataChannel;
  2396. } catch (error) {
  2397. console.error('Failed deleting MozDontOfferDataChannel');
  2398. console.error(error);
  2399. }
  2400. } else if ((isLocalFirefox && !isPeerFirefox)) {
  2401. constraints.mandatory.MozDontOfferDataChannel = true;
  2402. }
  2403. if (!isLocalFirefox) {
  2404. // temporary measure to remove Moz* constraints in non Firefox browsers
  2405. for (var prop in constraints.mandatory) {
  2406. if (constraints.mandatory.hasOwnProperty(prop)) {
  2407. if (prop.indexOf('Moz') !== -1) {
  2408. delete constraints.mandatory[prop];
  2409. }
  2410. }
  2411. }
  2412. }
  2413. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  2414. // interopability of the media stream
  2415. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  2416. beOfferer = false;
  2417. }
  2418. callback(beOfferer, constraints);
  2419. };
  2420. // Handles the differences for all browsers ice connection state output.
  2421. // - Tested outcomes are:
  2422. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  2423. // - Chrome (answerer) : 'checking' > 'connected'
  2424. // - Firefox (offerer) : 'checking' > 'connected'
  2425. // - Firefox (answerer): 'checking' > 'connected'
  2426. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  2427. if (typeof callback !== 'function') {
  2428. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  2429. return;
  2430. }
  2431. peerId = (peerId) ? peerId : 'peer';
  2432. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  2433. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  2434. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  2435. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  2436. AdapterJS._iceConnectionFiredStates[peerId] = [];
  2437. }
  2438. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  2439. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  2440. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  2441. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  2442. setTimeout(function () {
  2443. AdapterJS._iceConnectionFiredStates[peerId]
  2444. .push(AdapterJS._iceConnectionStates.done);
  2445. callback(AdapterJS._iceConnectionStates.done);
  2446. }, 1000);
  2447. }
  2448. callback(iceConnectionState);
  2449. }
  2450. return;
  2451. };
  2452. // Firefox:
  2453. // - Creates iceServer from the url for Firefox.
  2454. // - Create iceServer with stun url.
  2455. // - Create iceServer with turn url.
  2456. // - Ignore the transport parameter from TURN url for FF version <=27.
  2457. // - Return null for createIceServer if transport=tcp.
  2458. // - FF 27 and above supports transport parameters in TURN url,
  2459. // - So passing in the full url to create iceServer.
  2460. // Chrome:
  2461. // - Creates iceServer from the url for Chrome M33 and earlier.
  2462. // - Create iceServer with stun url.
  2463. // - Chrome M28 & above uses below TURN format.
  2464. // Plugin:
  2465. // - Creates Ice Server for Plugin Browsers
  2466. // - If Stun - Create iceServer with stun url.
  2467. // - Else - Create iceServer with turn url
  2468. // - This is a WebRTC Function
  2469. createIceServer = null;
  2470. // Firefox:
  2471. // - Creates IceServers for Firefox
  2472. // - Use .url for FireFox.
  2473. // - Multiple Urls support
  2474. // Chrome:
  2475. // - Creates iceServers from the urls for Chrome M34 and above.
  2476. // - .urls is supported since Chrome M34.
  2477. // - Multiple Urls support
  2478. // Plugin:
  2479. // - Creates Ice Servers for Plugin Browsers
  2480. // - Multiple Urls support
  2481. // - This is a WebRTC Function
  2482. createIceServers = null;
  2483. //------------------------------------------------------------
  2484. //The RTCPeerConnection object.
  2485. RTCPeerConnection = null;
  2486. // Creates RTCSessionDescription object for Plugin Browsers
  2487. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  2488. RTCSessionDescription : null;
  2489. // Creates RTCIceCandidate object for Plugin Browsers
  2490. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  2491. RTCIceCandidate : null;
  2492. // Get UserMedia (only difference is the prefix).
  2493. // Code from Adam Barth.
  2494. getUserMedia = null;
  2495. // Attach a media stream to an element.
  2496. attachMediaStream = null;
  2497. // Re-attach a media stream to an element.
  2498. reattachMediaStream = null;
  2499. // Detected browser agent name. Types are:
  2500. // - 'firefox': Firefox browser.
  2501. // - 'chrome': Chrome browser.
  2502. // - 'opera': Opera browser.
  2503. // - 'safari': Safari browser.
  2504. // - 'IE' - Internet Explorer browser.
  2505. webrtcDetectedBrowser = null;
  2506. // Detected browser version.
  2507. webrtcDetectedVersion = null;
  2508. // Check for browser types and react accordingly
  2509. if (navigator.mozGetUserMedia) {
  2510. webrtcDetectedBrowser = 'firefox';
  2511. webrtcDetectedVersion = parseInt(navigator
  2512. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2513. webrtcDetectedType = 'moz';
  2514. webrtcDetectedDCSupport = 'SCTP';
  2515. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2516. AdapterJS.maybeFixConfiguration(pcConfig);
  2517. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  2518. };
  2519. // The RTCSessionDescription object.
  2520. RTCSessionDescription = mozRTCSessionDescription;
  2521. window.RTCSessionDescription = RTCSessionDescription;
  2522. // The RTCIceCandidate object.
  2523. RTCIceCandidate = mozRTCIceCandidate;
  2524. window.RTCIceCandidate = RTCIceCandidate;
  2525. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  2526. navigator.getUserMedia = window.getUserMedia;
  2527. // Shim for MediaStreamTrack.getSources.
  2528. MediaStreamTrack.getSources = function(successCb) {
  2529. setTimeout(function() {
  2530. var infos = [
  2531. { kind: 'audio', id: 'default', label:'', facing:'' },
  2532. { kind: 'video', id: 'default', label:'', facing:'' }
  2533. ];
  2534. successCb(infos);
  2535. }, 0);
  2536. };
  2537. createIceServer = function (url, username, password) {
  2538. var iceServer = null;
  2539. var url_parts = url.split(':');
  2540. if (url_parts[0].indexOf('stun') === 0) {
  2541. iceServer = { url : url };
  2542. } else if (url_parts[0].indexOf('turn') === 0) {
  2543. if (webrtcDetectedVersion < 27) {
  2544. var turn_url_parts = url.split('?');
  2545. if (turn_url_parts.length === 1 ||
  2546. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2547. iceServer = {
  2548. url : turn_url_parts[0],
  2549. credential : password,
  2550. username : username
  2551. };
  2552. }
  2553. } else {
  2554. iceServer = {
  2555. url : url,
  2556. credential : password,
  2557. username : username
  2558. };
  2559. }
  2560. }
  2561. return iceServer;
  2562. };
  2563. createIceServers = function (urls, username, password) {
  2564. var iceServers = [];
  2565. for (i = 0; i < urls.length; i++) {
  2566. var iceServer = createIceServer(urls[i], username, password);
  2567. if (iceServer !== null) {
  2568. iceServers.push(iceServer);
  2569. }
  2570. }
  2571. return iceServers;
  2572. };
  2573. attachMediaStream = function (element, stream) {
  2574. element.mozSrcObject = stream;
  2575. if (stream !== null)
  2576. element.play();
  2577. return element;
  2578. };
  2579. reattachMediaStream = function (to, from) {
  2580. to.mozSrcObject = from.mozSrcObject;
  2581. to.play();
  2582. return to;
  2583. };
  2584. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2585. if (!callback) {
  2586. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2587. ': 1 argument required, but only 0 present.');
  2588. }
  2589. return callback([]);
  2590. };
  2591. // Fake get{Video,Audio}Tracks
  2592. if (!MediaStream.prototype.getVideoTracks) {
  2593. MediaStream.prototype.getVideoTracks = function () {
  2594. return [];
  2595. };
  2596. }
  2597. if (!MediaStream.prototype.getAudioTracks) {
  2598. MediaStream.prototype.getAudioTracks = function () {
  2599. return [];
  2600. };
  2601. }
  2602. AdapterJS.maybeThroughWebRTCReady();
  2603. } else if (navigator.webkitGetUserMedia) {
  2604. webrtcDetectedBrowser = 'chrome';
  2605. webrtcDetectedType = 'webkit';
  2606. webrtcDetectedVersion = parseInt(navigator
  2607. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2608. // check if browser is opera 20+
  2609. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2610. if (checkIfOpera !== null) {
  2611. webrtcDetectedBrowser = 'opera';
  2612. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2613. }
  2614. // check browser datachannel support
  2615. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2616. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2617. webrtcDetectedDCSupport = 'SCTP';
  2618. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2619. webrtcDetectedVersion > 24) {
  2620. webrtcDetectedDCSupport = 'RTP';
  2621. } else {
  2622. webrtcDetectedDCSupport = '';
  2623. }
  2624. createIceServer = function (url, username, password) {
  2625. var iceServer = null;
  2626. var url_parts = url.split(':');
  2627. if (url_parts[0].indexOf('stun') === 0) {
  2628. iceServer = { 'url' : url };
  2629. } else if (url_parts[0].indexOf('turn') === 0) {
  2630. iceServer = {
  2631. 'url' : url,
  2632. 'credential' : password,
  2633. 'username' : username
  2634. };
  2635. }
  2636. return iceServer;
  2637. };
  2638. createIceServers = function (urls, username, password) {
  2639. var iceServers = [];
  2640. if (webrtcDetectedVersion >= 34) {
  2641. iceServers = {
  2642. 'urls' : urls,
  2643. 'credential' : password,
  2644. 'username' : username
  2645. };
  2646. } else {
  2647. for (i = 0; i < urls.length; i++) {
  2648. var iceServer = createIceServer(urls[i], username, password);
  2649. if (iceServer !== null) {
  2650. iceServers.push(iceServer);
  2651. }
  2652. }
  2653. }
  2654. return iceServers;
  2655. };
  2656. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2657. if (webrtcDetectedVersion < 34) {
  2658. AdapterJS.maybeFixConfiguration(pcConfig);
  2659. }
  2660. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2661. };
  2662. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2663. navigator.getUserMedia = window.getUserMedia;
  2664. attachMediaStream = function (element, stream) {
  2665. if (typeof element.srcObject !== 'undefined') {
  2666. element.srcObject = stream;
  2667. } else if (typeof element.mozSrcObject !== 'undefined') {
  2668. element.mozSrcObject = stream;
  2669. } else if (typeof element.src !== 'undefined') {
  2670. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2671. } else {
  2672. console.log('Error attaching stream to element.');
  2673. }
  2674. return element;
  2675. };
  2676. reattachMediaStream = function (to, from) {
  2677. to.src = from.src;
  2678. return to;
  2679. };
  2680. AdapterJS.maybeThroughWebRTCReady();
  2681. } else { // TRY TO USE PLUGIN
  2682. // IE 9 is not offering an implementation of console.log until you open a console
  2683. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2684. /* jshint -W020 */
  2685. console = {} || console;
  2686. // Implemented based on console specs from MDN
  2687. // You may override these functions
  2688. console.log = function (arg) {};
  2689. console.info = function (arg) {};
  2690. console.error = function (arg) {};
  2691. console.dir = function (arg) {};
  2692. console.exception = function (arg) {};
  2693. console.trace = function (arg) {};
  2694. console.warn = function (arg) {};
  2695. console.count = function (arg) {};
  2696. console.debug = function (arg) {};
  2697. console.count = function (arg) {};
  2698. console.time = function (arg) {};
  2699. console.timeEnd = function (arg) {};
  2700. console.group = function (arg) {};
  2701. console.groupCollapsed = function (arg) {};
  2702. console.groupEnd = function (arg) {};
  2703. /* jshint +W020 */
  2704. }
  2705. webrtcDetectedType = 'plugin';
  2706. webrtcDetectedDCSupport = 'plugin';
  2707. AdapterJS.parseWebrtcDetectedBrowser();
  2708. isIE = webrtcDetectedBrowser === 'IE';
  2709. /* jshint -W035 */
  2710. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2711. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2712. /* empty because it needs to prevent the function from running. */
  2713. }
  2714. };
  2715. /* jshint +W035 */
  2716. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2717. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2718. // Call immediately if possible
  2719. // Once the plugin is set, the code will always take this path
  2720. callback();
  2721. } else {
  2722. // otherwise start a 100ms interval
  2723. var checkPluginReadyState = setInterval(function () {
  2724. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2725. clearInterval(checkPluginReadyState);
  2726. callback();
  2727. }
  2728. }, 100);
  2729. }
  2730. };
  2731. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2732. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2733. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2734. });
  2735. };
  2736. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2737. // only inject once the page is ready
  2738. if (document.readyState !== 'complete') {
  2739. return;
  2740. }
  2741. // Prevent multiple injections
  2742. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2743. return;
  2744. }
  2745. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2746. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2747. var frag = document.createDocumentFragment();
  2748. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2749. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2750. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2751. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2752. '<param name="pluginId" value="' +
  2753. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2754. '<param name="windowless" value="false" /> ' +
  2755. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2756. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload +
  2757. '" />' +
  2758. // uncomment to be able to use virtual cams
  2759. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2760. '</object>';
  2761. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2762. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2763. }
  2764. document.body.appendChild(frag);
  2765. // Need to re-fetch the plugin
  2766. AdapterJS.WebRTCPlugin.plugin =
  2767. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2768. } else {
  2769. // Load Plugin
  2770. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2771. AdapterJS.WebRTCPlugin.plugin.id =
  2772. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2773. // IE will only start the plugin if it's ACTUALLY visible
  2774. if (isIE) {
  2775. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2776. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2777. } else { // The size of the plugin on Safari should be 0x0px
  2778. // so that the autorisation prompt is at the top
  2779. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2780. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2781. }
  2782. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2783. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2784. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2785. '<param name="pluginId" value="' +
  2786. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2787. '<param name="windowless" value="false" /> ' +
  2788. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2789. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">';
  2790. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2791. }
  2792. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2793. };
  2794. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2795. function (comName, plugName, installedCb, notInstalledCb) {
  2796. if (!isIE) {
  2797. var pluginArray = navigator.plugins;
  2798. for (var i = 0; i < pluginArray.length; i++) {
  2799. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2800. installedCb();
  2801. return;
  2802. }
  2803. }
  2804. notInstalledCb();
  2805. } else {
  2806. try {
  2807. var axo = new ActiveXObject(comName + '.' + plugName);
  2808. } catch (e) {
  2809. notInstalledCb();
  2810. return;
  2811. }
  2812. installedCb();
  2813. }
  2814. };
  2815. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2816. if (AdapterJS.WebRTCPlugin.pluginState ===
  2817. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2818. console.error("WebRTC interface has been defined already");
  2819. return;
  2820. }
  2821. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2822. AdapterJS.isDefined = function (variable) {
  2823. return variable !== null && variable !== undefined;
  2824. };
  2825. createIceServer = function (url, username, password) {
  2826. var iceServer = null;
  2827. var url_parts = url.split(':');
  2828. if (url_parts[0].indexOf('stun') === 0) {
  2829. iceServer = {
  2830. 'url' : url,
  2831. 'hasCredentials' : false
  2832. };
  2833. } else if (url_parts[0].indexOf('turn') === 0) {
  2834. iceServer = {
  2835. 'url' : url,
  2836. 'hasCredentials' : true,
  2837. 'credential' : password,
  2838. 'username' : username
  2839. };
  2840. }
  2841. return iceServer;
  2842. };
  2843. createIceServers = function (urls, username, password) {
  2844. var iceServers = [];
  2845. for (var i = 0; i < urls.length; ++i) {
  2846. iceServers.push(createIceServer(urls[i], username, password));
  2847. }
  2848. return iceServers;
  2849. };
  2850. RTCSessionDescription = function (info) {
  2851. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2852. return AdapterJS.WebRTCPlugin.plugin.
  2853. ConstructSessionDescription(info.type, info.sdp);
  2854. };
  2855. RTCPeerConnection = function (servers, constraints) {
  2856. var iceServers = null;
  2857. if (servers) {
  2858. iceServers = servers.iceServers;
  2859. for (var i = 0; i < iceServers.length; i++) {
  2860. if (iceServers[i].urls && !iceServers[i].url) {
  2861. iceServers[i].url = iceServers[i].urls;
  2862. }
  2863. iceServers[i].hasCredentials = AdapterJS.
  2864. isDefined(iceServers[i].username) &&
  2865. AdapterJS.isDefined(iceServers[i].credential);
  2866. }
  2867. }
  2868. var mandatory = (constraints && constraints.mandatory) ?
  2869. constraints.mandatory : null;
  2870. var optional = (constraints && constraints.optional) ?
  2871. constraints.optional : null;
  2872. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2873. return AdapterJS.WebRTCPlugin.plugin.
  2874. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2875. iceServers, mandatory, optional);
  2876. };
  2877. MediaStreamTrack = {};
  2878. MediaStreamTrack.getSources = function (callback) {
  2879. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2880. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2881. });
  2882. };
  2883. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2884. constraints.audio = constraints.audio || false;
  2885. constraints.video = constraints.video || false;
  2886. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2887. AdapterJS.WebRTCPlugin.plugin.
  2888. getUserMedia(constraints, successCallback, failureCallback);
  2889. });
  2890. };
  2891. window.navigator.getUserMedia = window.getUserMedia;
  2892. attachMediaStream = function (element, stream) {
  2893. if (!element || !element.parentNode) {
  2894. return;
  2895. }
  2896. var streamId
  2897. if (stream === null) {
  2898. streamId = '';
  2899. }
  2900. else {
  2901. stream.enableSoundTracks(true);
  2902. streamId = stream.id;
  2903. }
  2904. if (element.nodeName.toLowerCase() !== 'audio') {
  2905. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2906. if (!element.isWebRTCPlugin || !element.isWebRTCPlugin()) {
  2907. var frag = document.createDocumentFragment();
  2908. var temp = document.createElement('div');
  2909. var classHTML = '';
  2910. if (element.className) {
  2911. classHTML = 'class="' + element.className + '" ';
  2912. } else if (element.attributes && element.attributes['class']) {
  2913. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2914. }
  2915. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2916. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2917. '<param name="pluginId" value="' + elementId + '" /> ' +
  2918. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2919. '<param name="windowless" value="true" /> ' +
  2920. '<param name="streamId" value="' + streamId + '" /> ' +
  2921. '</object>';
  2922. while (temp.firstChild) {
  2923. frag.appendChild(temp.firstChild);
  2924. }
  2925. var height = '';
  2926. var width = '';
  2927. if (element.getBoundingClientRect) {
  2928. var rectObject = element.getBoundingClientRect();
  2929. width = rectObject.width + 'px';
  2930. height = rectObject.height + 'px';
  2931. }
  2932. else if (element.width) {
  2933. width = element.width;
  2934. height = element.height;
  2935. } else {
  2936. // TODO: What scenario could bring us here?
  2937. }
  2938. element.parentNode.insertBefore(frag, element);
  2939. frag = document.getElementById(elementId);
  2940. frag.width = width;
  2941. frag.height = height;
  2942. element.parentNode.removeChild(element);
  2943. } else {
  2944. var children = element.children;
  2945. for (var i = 0; i !== children.length; ++i) {
  2946. if (children[i].name === 'streamId') {
  2947. children[i].value = streamId;
  2948. break;
  2949. }
  2950. }
  2951. element.setStreamId(streamId);
  2952. }
  2953. var newElement = document.getElementById(elementId);
  2954. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2955. if (isIE) { // on IE the event needs to be plugged manually
  2956. newElement.attachEvent('onplaying', newElement.onplaying);
  2957. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2958. newElement._TemOnClick = function (id) {
  2959. var arg = {
  2960. srcElement : document.getElementById(id)
  2961. };
  2962. newElement.onclick(arg);
  2963. };
  2964. }
  2965. return newElement;
  2966. } else {
  2967. return element;
  2968. }
  2969. };
  2970. reattachMediaStream = function (to, from) {
  2971. var stream = null;
  2972. var children = from.children;
  2973. for (var i = 0; i !== children.length; ++i) {
  2974. if (children[i].name === 'streamId') {
  2975. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2976. stream = AdapterJS.WebRTCPlugin.plugin
  2977. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2978. break;
  2979. }
  2980. }
  2981. if (stream !== null) {
  2982. return attachMediaStream(to, stream);
  2983. } else {
  2984. console.log('Could not find the stream associated with this element');
  2985. }
  2986. };
  2987. RTCIceCandidate = function (candidate) {
  2988. if (!candidate.sdpMid) {
  2989. candidate.sdpMid = '';
  2990. }
  2991. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2992. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2993. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2994. );
  2995. };
  2996. // inject plugin
  2997. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2998. AdapterJS.WebRTCPlugin.injectPlugin();
  2999. };
  3000. // This function will be called if the plugin is needed (browser different
  3001. // from Chrome or Firefox), but the plugin is not installed.
  3002. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  3003. function() {
  3004. AdapterJS.addEvent(document,
  3005. 'readystatechange',
  3006. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  3007. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  3008. };
  3009. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  3010. if (AdapterJS.options.hidePluginInstallPrompt) {
  3011. return;
  3012. }
  3013. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  3014. if(downloadLink) { // if download link
  3015. var popupString;
  3016. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  3017. popupString = 'This website requires you to install the ' +
  3018. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  3019. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  3020. ' WebRTC Plugin</a>' +
  3021. ' to work on this browser.';
  3022. } else { // no portal link, just print a generic explanation
  3023. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  3024. }
  3025. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  3026. } else { // no download link, just print a generic explanation
  3027. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  3028. }
  3029. };
  3030. // Try to detect the plugin and act accordingly
  3031. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3032. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3033. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3034. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  3035. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  3036. }
  3037. (function () {
  3038. 'use strict';
  3039. var baseGetUserMedia = null;
  3040. AdapterJS.TEXT.EXTENSION = {
  3041. REQUIRE_INSTALLATION_FF: 'To enable screensharing you need to install the Skylink WebRTC tools Firefox Add-on.',
  3042. REQUIRE_INSTALLATION_CHROME: 'To enable screensharing you need to install the Skylink WebRTC tools Chrome Extension.',
  3043. REQUIRE_REFRESH: 'Please refresh this page after the Skylink WebRTC tools extension has been installed.',
  3044. BUTTON_FF: 'Install Now',
  3045. BUTTON_CHROME: 'Go to Chrome Web Store'
  3046. };
  3047. var clone = function(obj) {
  3048. if (null == obj || "object" != typeof obj) return obj;
  3049. var copy = obj.constructor();
  3050. for (var attr in obj) {
  3051. if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  3052. }
  3053. return copy;
  3054. };
  3055. if (window.navigator.mozGetUserMedia) {
  3056. baseGetUserMedia = window.navigator.getUserMedia;
  3057. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  3058. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  3059. // intercepting screensharing requests
  3060. if (constraints.video.mediaSource !== 'screen' && constraints.video.mediaSource !== 'window') {
  3061. throw new Error('Only "screen" and "window" option is available as mediaSource');
  3062. }
  3063. var updatedConstraints = clone(constraints);
  3064. //constraints.video.mediaSource = constraints.video.mediaSource;
  3065. updatedConstraints.video.mozMediaSource = updatedConstraints.video.mediaSource;
  3066. // so generally, it requires for document.readyState to be completed before the getUserMedia could be invoked.
  3067. // strange but this works anyway
  3068. var checkIfReady = setInterval(function () {
  3069. if (document.readyState === 'complete') {
  3070. clearInterval(checkIfReady);
  3071. baseGetUserMedia(updatedConstraints, successCb, function (error) {
  3072. if (error.name === 'PermissionDeniedError' && window.parent.location.protocol === 'https:') {
  3073. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_FF,
  3074. AdapterJS.TEXT.EXTENSION.BUTTON_FF,
  3075. 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname, false, true);
  3076. //window.location.href = 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname;
  3077. } else {
  3078. failureCb(error);
  3079. }
  3080. });
  3081. }
  3082. }, 1);
  3083. } else { // regular GetUserMediaRequest
  3084. baseGetUserMedia(constraints, successCb, failureCb);
  3085. }
  3086. };
  3087. getUserMedia = navigator.getUserMedia;
  3088. } else if (window.navigator.webkitGetUserMedia) {
  3089. baseGetUserMedia = window.navigator.getUserMedia;
  3090. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  3091. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  3092. if (window.webrtcDetectedBrowser !== 'chrome') {
  3093. throw new Error('Current browser does not support screensharing');
  3094. }
  3095. // would be fine since no methods
  3096. var updatedConstraints = clone(constraints);
  3097. var chromeCallback = function(error, sourceId) {
  3098. if(!error) {
  3099. updatedConstraints.video.mandatory = updatedConstraints.video.mandatory || {};
  3100. updatedConstraints.video.mandatory.chromeMediaSource = 'desktop';
  3101. updatedConstraints.video.mandatory.maxWidth = window.screen.width > 1920 ? window.screen.width : 1920;
  3102. updatedConstraints.video.mandatory.maxHeight = window.screen.height > 1080 ? window.screen.height : 1080;
  3103. if (sourceId) {
  3104. updatedConstraints.video.mandatory.chromeMediaSourceId = sourceId;
  3105. }
  3106. delete updatedConstraints.video.mediaSource;
  3107. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  3108. } else {
  3109. if (error === 'permission-denied') {
  3110. throw new Error('Permission denied for screen retrieval');
  3111. } else {
  3112. throw new Error('Failed retrieving selected screen');
  3113. }
  3114. }
  3115. };
  3116. var onIFrameCallback = function (event) {
  3117. if (!event.data) {
  3118. return;
  3119. }
  3120. if (event.data.chromeMediaSourceId) {
  3121. if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
  3122. chromeCallback('permission-denied');
  3123. } else {
  3124. chromeCallback(null, event.data.chromeMediaSourceId);
  3125. }
  3126. }
  3127. if (event.data.chromeExtensionStatus) {
  3128. if (event.data.chromeExtensionStatus === 'not-installed') {
  3129. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_CHROME,
  3130. AdapterJS.TEXT.EXTENSION.BUTTON_CHROME,
  3131. event.data.data, true, true);
  3132. } else {
  3133. chromeCallback(event.data.chromeExtensionStatus, null);
  3134. }
  3135. }
  3136. // this event listener is no more needed
  3137. window.removeEventListener('message', onIFrameCallback);
  3138. };
  3139. window.addEventListener('message', onIFrameCallback);
  3140. postFrameMessage({
  3141. captureSourceId: true
  3142. });
  3143. } else {
  3144. baseGetUserMedia(constraints, successCb, failureCb);
  3145. }
  3146. };
  3147. getUserMedia = navigator.getUserMedia;
  3148. } else {
  3149. baseGetUserMedia = window.navigator.getUserMedia;
  3150. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  3151. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  3152. // would be fine since no methods
  3153. var updatedConstraints = clone(constraints);
  3154. // wait for plugin to be ready
  3155. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3156. // check if screensharing feature is available
  3157. if (!!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature &&
  3158. !!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3159. // set the constraints
  3160. updatedConstraints.video.optional = updatedConstraints.video.optional || [];
  3161. updatedConstraints.video.optional.push({
  3162. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey || 'Screensharing'
  3163. });
  3164. delete updatedConstraints.video.mediaSource;
  3165. } else {
  3166. throw new Error('Your WebRTC plugin does not support screensharing');
  3167. }
  3168. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  3169. });
  3170. } else {
  3171. baseGetUserMedia(constraints, successCb, failureCb);
  3172. }
  3173. };
  3174. getUserMedia = window.navigator.getUserMedia;
  3175. }
  3176. if (window.webrtcDetectedBrowser === 'chrome') {
  3177. var iframe = document.createElement('iframe');
  3178. iframe.onload = function() {
  3179. iframe.isLoaded = true;
  3180. };
  3181. iframe.src = 'https://cdn.temasys.com.sg/skylink/extensions/detectRTC.html';
  3182. //'https://temasys-cdn.s3.amazonaws.com/skylink/extensions/detection-script-dev/detectRTC.html';
  3183. iframe.style.display = 'none';
  3184. (document.body || document.documentElement).appendChild(iframe);
  3185. var postFrameMessage = function (object) {
  3186. object = object || {};
  3187. if (!iframe.isLoaded) {
  3188. setTimeout(function () {
  3189. iframe.contentWindow.postMessage(object, '*');
  3190. }, 100);
  3191. return;
  3192. }
  3193. iframe.contentWindow.postMessage(object, '*');
  3194. };
  3195. }
  3196. })();
  3197. },{}],17:[function(require,module,exports){
  3198. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  3199. getUserMediaWithConstraints */
  3200. /**
  3201. * Indicates that desktop stream is currently in use(for toggle purpose).
  3202. * @type {boolean}
  3203. */
  3204. var isUsingScreenStream = false;
  3205. /**
  3206. * Indicates that switch stream operation is in progress and prevent from
  3207. * triggering new events.
  3208. * @type {boolean}
  3209. */
  3210. var switchInProgress = false;
  3211. /**
  3212. * Method used to get screen sharing stream.
  3213. *
  3214. * @type {function (stream_callback, failure_callback}
  3215. */
  3216. var obtainDesktopStream = null;
  3217. /**
  3218. * Indicates whether desktop sharing extension is installed.
  3219. * @type {boolean}
  3220. */
  3221. var extInstalled = false;
  3222. /**
  3223. * Indicates whether update of desktop sharing extension is required.
  3224. * @type {boolean}
  3225. */
  3226. var extUpdateRequired = false;
  3227. var AdapterJS = require("../RTC/adapter.screenshare");
  3228. var EventEmitter = require("events");
  3229. var eventEmitter = new EventEmitter();
  3230. var DesktopSharingEventTypes
  3231. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  3232. var RTCBrowserType = require("../RTC/RTCBrowserType");
  3233. var RTCEvents = require("../../service/RTC/RTCEvents");
  3234. /**
  3235. * Method obtains desktop stream from WebRTC 'screen' source.
  3236. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  3237. */
  3238. function obtainWebRTCScreen(streamCallback, failCallback) {
  3239. APP.RTC.getUserMediaWithConstraints(
  3240. ['screen'],
  3241. streamCallback,
  3242. failCallback
  3243. );
  3244. }
  3245. /**
  3246. * Constructs inline install URL for Chrome desktop streaming extension.
  3247. * The 'chromeExtensionId' must be defined in config.js.
  3248. * @returns {string}
  3249. */
  3250. function getWebStoreInstallUrl()
  3251. {
  3252. return "https://chrome.google.com/webstore/detail/" +
  3253. config.chromeExtensionId;
  3254. }
  3255. /**
  3256. * Checks whether extension update is required.
  3257. * @param minVersion minimal required version
  3258. * @param extVersion current extension version
  3259. * @returns {boolean}
  3260. */
  3261. function isUpdateRequired(minVersion, extVersion)
  3262. {
  3263. try
  3264. {
  3265. var s1 = minVersion.split('.');
  3266. var s2 = extVersion.split('.');
  3267. var len = Math.max(s1.length, s2.length);
  3268. for (var i = 0; i < len; i++)
  3269. {
  3270. var n1 = 0,
  3271. n2 = 0;
  3272. if (i < s1.length)
  3273. n1 = parseInt(s1[i]);
  3274. if (i < s2.length)
  3275. n2 = parseInt(s2[i]);
  3276. if (isNaN(n1) || isNaN(n2))
  3277. {
  3278. return true;
  3279. }
  3280. else if (n1 !== n2)
  3281. {
  3282. return n1 > n2;
  3283. }
  3284. }
  3285. // will happen if boths version has identical numbers in
  3286. // their components (even if one of them is longer, has more components)
  3287. return false;
  3288. }
  3289. catch (e)
  3290. {
  3291. console.error("Failed to parse extension version", e);
  3292. APP.UI.messageHandler.showError("dialog.error",
  3293. "dialog.detectext");
  3294. return true;
  3295. }
  3296. }
  3297. function checkChromeExtInstalled(callback) {
  3298. if (!chrome.runtime) {
  3299. // No API, so no extension for sure
  3300. callback(false, false);
  3301. return;
  3302. }
  3303. chrome.runtime.sendMessage(
  3304. config.chromeExtensionId,
  3305. { getVersion: true },
  3306. function (response) {
  3307. if (!response || !response.version) {
  3308. // Communication failure - assume that no endpoint exists
  3309. console.warn(
  3310. "Extension not installed?: ", chrome.runtime.lastError);
  3311. callback(false, false);
  3312. return;
  3313. }
  3314. // Check installed extension version
  3315. var extVersion = response.version;
  3316. console.log('Extension version is: ' + extVersion);
  3317. var updateRequired
  3318. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  3319. callback(!updateRequired, updateRequired);
  3320. }
  3321. );
  3322. }
  3323. function doGetStreamFromExtension(streamCallback, failCallback) {
  3324. // Sends 'getStream' msg to the extension.
  3325. // Extension id must be defined in the config.
  3326. chrome.runtime.sendMessage(
  3327. config.chromeExtensionId,
  3328. { getStream: true, sources: config.desktopSharingSources },
  3329. function (response) {
  3330. if (!response) {
  3331. failCallback(chrome.runtime.lastError);
  3332. return;
  3333. }
  3334. console.log("Response from extension: " + response);
  3335. if (response.streamId) {
  3336. APP.RTC.getUserMediaWithConstraints(
  3337. ['desktop'],
  3338. function (stream) {
  3339. streamCallback(stream);
  3340. },
  3341. failCallback,
  3342. null, null, null,
  3343. response.streamId);
  3344. } else {
  3345. failCallback("Extension failed to get the stream");
  3346. }
  3347. }
  3348. );
  3349. }
  3350. /**
  3351. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  3352. * stream for returned stream token.
  3353. */
  3354. function obtainScreenFromExtension(streamCallback, failCallback) {
  3355. if (extInstalled) {
  3356. doGetStreamFromExtension(streamCallback, failCallback);
  3357. } else {
  3358. if (extUpdateRequired) {
  3359. alert(
  3360. 'Jitsi Desktop Streamer requires update. ' +
  3361. 'Changes will take effect after next Chrome restart.');
  3362. }
  3363. chrome.webstore.install(
  3364. getWebStoreInstallUrl(),
  3365. function (arg) {
  3366. console.log("Extension installed successfully", arg);
  3367. extInstalled = true;
  3368. // We need to give a moment for the endpoint to become available
  3369. window.setTimeout(function () {
  3370. doGetStreamFromExtension(streamCallback, failCallback);
  3371. }, 500);
  3372. },
  3373. function (arg) {
  3374. console.log("Failed to install the extension", arg);
  3375. failCallback(arg);
  3376. APP.UI.messageHandler.showError("dialog.error",
  3377. "dialog.failtoinstall");
  3378. }
  3379. );
  3380. }
  3381. }
  3382. /**
  3383. * Call this method to toggle desktop sharing feature.
  3384. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  3385. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  3386. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  3387. * enabled), pass any other string or nothing in order to disable this
  3388. * feature completely.
  3389. */
  3390. function setDesktopSharing(method) {
  3391. obtainDesktopStream = null;
  3392. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  3393. // care about 'method' parameter
  3394. if (RTCBrowserType.isTemasysPluginUsed()) {
  3395. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  3396. console.info("Screensharing not supported by this plugin version");
  3397. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3398. console.info(
  3399. "Screensharing not available with Temasys plugin on this site");
  3400. } else {
  3401. obtainDesktopStream = obtainWebRTCScreen;
  3402. console.info("Using Temasys plugin for desktop sharing");
  3403. }
  3404. } else if (RTCBrowserType.isChrome()) {
  3405. if (method == "ext") {
  3406. if (RTCBrowserType.getChromeVersion() >= 34) {
  3407. obtainDesktopStream = obtainScreenFromExtension;
  3408. console.info("Using Chrome extension for desktop sharing");
  3409. initChromeExtension();
  3410. } else {
  3411. console.info("Chrome extension not supported until ver 34");
  3412. }
  3413. } else if (method == "webrtc") {
  3414. obtainDesktopStream = obtainWebRTCScreen;
  3415. console.info("Using Chrome WebRTC for desktop sharing");
  3416. }
  3417. }
  3418. if (!obtainDesktopStream) {
  3419. console.info("Desktop sharing disabled");
  3420. }
  3421. }
  3422. /**
  3423. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3424. * config.js to support inline installs. Host site must be selected as main
  3425. * website of published extension.
  3426. */
  3427. function initInlineInstalls()
  3428. {
  3429. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  3430. }
  3431. function initChromeExtension() {
  3432. // Initialize Chrome extension inline installs
  3433. initInlineInstalls();
  3434. // Check if extension is installed
  3435. checkChromeExtInstalled(function (installed, updateRequired) {
  3436. extInstalled = installed;
  3437. extUpdateRequired = updateRequired;
  3438. console.info(
  3439. "Chrome extension installed: " + extInstalled +
  3440. " updateRequired: " + extUpdateRequired);
  3441. });
  3442. }
  3443. function getVideoStreamFailed(error) {
  3444. console.error("Failed to obtain the stream to switch to", error);
  3445. switchInProgress = false;
  3446. isUsingScreenStream = false;
  3447. newStreamCreated(null);
  3448. }
  3449. function getDesktopStreamFailed(error) {
  3450. console.error("Failed to obtain the stream to switch to", error);
  3451. switchInProgress = false;
  3452. }
  3453. function streamSwitchDone() {
  3454. switchInProgress = false;
  3455. eventEmitter.emit(
  3456. DesktopSharingEventTypes.SWITCHING_DONE,
  3457. isUsingScreenStream);
  3458. }
  3459. function newStreamCreated(stream)
  3460. {
  3461. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  3462. stream, isUsingScreenStream, streamSwitchDone);
  3463. }
  3464. function onEndedHandler(stream) {
  3465. if (!switchInProgress && isUsingScreenStream) {
  3466. APP.desktopsharing.toggleScreenSharing();
  3467. }
  3468. //FIXME: to be verified
  3469. if (stream.removeEventListener) {
  3470. stream.removeEventListener('ended', onEndedHandler);
  3471. } else {
  3472. stream.detachEvent('ended', onEndedHandler);
  3473. }
  3474. }
  3475. // Called when RTC finishes initialization
  3476. function onWebRtcReady() {
  3477. setDesktopSharing(config.desktopSharing);
  3478. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  3479. }
  3480. module.exports = {
  3481. isUsingScreenStream: function () {
  3482. return isUsingScreenStream;
  3483. },
  3484. /**
  3485. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  3486. * and enabled.
  3487. */
  3488. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  3489. init: function () {
  3490. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  3491. },
  3492. addListener: function (listener, type)
  3493. {
  3494. eventEmitter.on(type, listener);
  3495. },
  3496. removeListener: function (listener, type) {
  3497. eventEmitter.removeListener(type, listener);
  3498. },
  3499. /*
  3500. * Toggles screen sharing.
  3501. */
  3502. toggleScreenSharing: function () {
  3503. if (switchInProgress || !obtainDesktopStream) {
  3504. console.warn("Switch in progress or no method defined");
  3505. return;
  3506. }
  3507. switchInProgress = true;
  3508. if (!isUsingScreenStream)
  3509. {
  3510. // Switch to desktop stream
  3511. obtainDesktopStream(
  3512. function (stream) {
  3513. // We now use screen stream
  3514. isUsingScreenStream = true;
  3515. // Hook 'ended' event to restore camera
  3516. // when screen stream stops
  3517. //FIXME: to be verified
  3518. if (stream.addEventListener) {
  3519. stream.addEventListener('ended', function () {
  3520. onEndedHandler(stream);
  3521. });
  3522. } else {
  3523. stream.attachEvent('ended', function () {
  3524. onEndedHandler(stream);
  3525. });
  3526. }
  3527. newStreamCreated(stream);
  3528. },
  3529. getDesktopStreamFailed);
  3530. } else {
  3531. // Disable screen stream
  3532. APP.RTC.getUserMediaWithConstraints(
  3533. ['video'],
  3534. function (stream) {
  3535. // We are now using camera stream
  3536. isUsingScreenStream = false;
  3537. newStreamCreated(stream);
  3538. },
  3539. getVideoStreamFailed, config.resolution || '360'
  3540. );
  3541. }
  3542. }
  3543. };
  3544. },{"../../service/RTC/RTCEvents":71,"../../service/desktopsharing/DesktopSharingEventTypes":75,"../RTC/RTCBrowserType":14,"../RTC/adapter.screenshare":16,"events":77}],18:[function(require,module,exports){
  3545. function supportsLocalStorage() {
  3546. try {
  3547. return 'localStorage' in window && window.localStorage !== null;
  3548. } catch (e) {
  3549. console.log("localstorage is not supported");
  3550. return false;
  3551. }
  3552. }
  3553. function generateUniqueId() {
  3554. function _p8() {
  3555. return (Math.random().toString(16) + "000000000").substr(2, 8);
  3556. }
  3557. return _p8() + _p8() + _p8() + _p8();
  3558. }
  3559. function Settings(conferenceID) {
  3560. this.email = '';
  3561. this.displayName = '';
  3562. this.userId;
  3563. this.language = null;
  3564. this.confSettings = null;
  3565. this.conferenceID = conferenceID;
  3566. if (supportsLocalStorage()) {
  3567. if(!window.localStorage.getItem(conferenceID))
  3568. this.confSettings = {};
  3569. else
  3570. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  3571. if(!this.confSettings.jitsiMeetId) {
  3572. this.confSettings.jitsiMeetId = generateUniqueId();
  3573. console.log("generated id",
  3574. this.confSettings.jitsiMeetId);
  3575. this.save();
  3576. }
  3577. this.userId = this.confSettings.jitsiMeetId || '';
  3578. this.email = this.confSettings.email || '';
  3579. this.displayName = this.confSettings.displayname || '';
  3580. this.language = this.confSettings.language;
  3581. } else {
  3582. console.log("local storage is not supported");
  3583. this.userId = generateUniqueId();
  3584. }
  3585. }
  3586. Settings.prototype.save = function () {
  3587. if(!supportsLocalStorage())
  3588. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  3589. }
  3590. Settings.prototype.setDisplayName = function (newDisplayName) {
  3591. this.displayName = newDisplayName;
  3592. if(this.confSettings != null)
  3593. this.confSettings.displayname = displayName;
  3594. this.save();
  3595. return this.displayName;
  3596. },
  3597. Settings.prototype.setEmail = function (newEmail) {
  3598. this.email = newEmail;
  3599. if(this.confSettings != null)
  3600. this.confSettings.email = newEmail;
  3601. this.save();
  3602. return this.email;
  3603. },
  3604. Settings.prototype.getSettings = function () {
  3605. return {
  3606. email: this.email,
  3607. displayName: this.displayName,
  3608. uid: this.userId,
  3609. language: this.language
  3610. };
  3611. },
  3612. Settings.prototype.setLanguage = function (lang) {
  3613. this.language = lang;
  3614. if(this.confSettings != null)
  3615. this.confSettings.language = lang;
  3616. this.save();
  3617. }
  3618. module.exports = Settings;
  3619. },{}],19:[function(require,module,exports){
  3620. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  3621. var Moderator = require("./moderator");
  3622. var EventEmitter = require("events");
  3623. var parser = {
  3624. packet2JSON: function (packet, nodes) {
  3625. var self = this;
  3626. $(packet).children().each(function (index) {
  3627. var tagName = $(this).prop("tagName");
  3628. var node = {}
  3629. node["tagName"] = tagName;
  3630. node.attributes = {};
  3631. $($(this)[0].attributes).each(function( index, attr ) {
  3632. node.attributes[ attr.name ] = attr.value;
  3633. } );
  3634. var text = Strophe.getText($(this)[0]);
  3635. if(text)
  3636. node.value = text;
  3637. node.children = [];
  3638. nodes.push(node);
  3639. self.packet2JSON($(this), node.children);
  3640. })
  3641. },
  3642. JSON2packet: function (nodes, packet) {
  3643. for(var i = 0; i < nodes.length; i++)
  3644. {
  3645. var node = nodes[i];
  3646. if(!node || node === null){
  3647. continue;
  3648. }
  3649. packet.c(node.tagName, node.attributes);
  3650. if(node.value)
  3651. packet.t(node.value);
  3652. if(node.children)
  3653. this.JSON2packet(node.children, packet);
  3654. packet.up();
  3655. }
  3656. packet.up();
  3657. }
  3658. };
  3659. /**
  3660. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  3661. * @param pres the presence JSON
  3662. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  3663. */
  3664. function filterNodeFromPresenceJSON(pres, nodeName){
  3665. var res = [];
  3666. for(var i = 0; i < pres.length; i++)
  3667. if(pres[i].tagName === nodeName)
  3668. res.push(pres[i]);
  3669. return res;
  3670. }
  3671. function ChatRoom(connection, jid, password, XMPP, options) {
  3672. this.eventEmitter = new EventEmitter();
  3673. this.xmpp = XMPP;
  3674. this.connection = connection;
  3675. this.roomjid = Strophe.getBareJidFromJid(jid);
  3676. this.myroomjid = jid;
  3677. this.password = password;
  3678. console.info("Joined MUC as " + this.myroomjid);
  3679. this.members = {};
  3680. this.presMap = {};
  3681. this.presHandlers = {};
  3682. this.joined = false;
  3683. this.role = null;
  3684. this.focusMucJid = null;
  3685. this.bridgeIsDown = false;
  3686. this.options = options || {};
  3687. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter);
  3688. this.initPresenceMap();
  3689. this.session = null;
  3690. var self = this;
  3691. this.lastPresences = {};
  3692. }
  3693. ChatRoom.prototype.initPresenceMap = function () {
  3694. this.presMap['to'] = this.myroomjid;
  3695. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  3696. this.presMap["nodes"] = [];
  3697. this.presMap["nodes"].push( {
  3698. "tagName": "user-agent",
  3699. "value": navigator.userAgent,
  3700. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  3701. });
  3702. };
  3703. ChatRoom.prototype.join = function (password) {
  3704. if(password)
  3705. this.password = password;
  3706. this.moderator.allocateConferenceFocus(function()
  3707. {
  3708. this.sendPresence();
  3709. }.bind(this));
  3710. }
  3711. ChatRoom.prototype.sendPresence = function () {
  3712. if (!this.presMap['to']) {
  3713. // Too early to send presence - not initialized
  3714. return;
  3715. }
  3716. var pres = $pres({to: this.presMap['to'] });
  3717. pres.c('x', {xmlns: this.presMap['xns']});
  3718. if (this.password) {
  3719. pres.c('password').t(this.password).up();
  3720. }
  3721. pres.up();
  3722. // Send XEP-0115 'c' stanza that contains our capabilities info
  3723. if (this.connection.caps) {
  3724. this.connection.caps.node = this.xmpp.options.clientNode;
  3725. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  3726. }
  3727. parser.JSON2packet(this.presMap.nodes, pres);
  3728. this.connection.send(pres);
  3729. };
  3730. ChatRoom.prototype.doLeave = function () {
  3731. console.log("do leave", this.myroomjid);
  3732. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  3733. this.presMap.length = 0;
  3734. this.connection.send(pres);
  3735. };
  3736. ChatRoom.prototype.createNonAnonymousRoom = function () {
  3737. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  3738. var getForm = $iq({type: 'get', to: this.roomjid})
  3739. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  3740. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  3741. var self = this;
  3742. this.connection.sendIQ(getForm, function (form) {
  3743. if (!$(form).find(
  3744. '>query>x[xmlns="jabber:x:data"]' +
  3745. '>field[var="muc#roomconfig_whois"]').length) {
  3746. console.error('non-anonymous rooms not supported');
  3747. return;
  3748. }
  3749. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  3750. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  3751. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  3752. formSubmit.c('field', {'var': 'FORM_TYPE'})
  3753. .c('value')
  3754. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  3755. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  3756. .c('value').t('anyone').up().up();
  3757. self.connection.sendIQ(formSubmit);
  3758. }, function (error) {
  3759. console.error("Error getting room configuration form");
  3760. });
  3761. };
  3762. ChatRoom.prototype.onPresence = function (pres) {
  3763. var from = pres.getAttribute('from');
  3764. // Parse roles.
  3765. var member = {};
  3766. member.show = $(pres).find('>show').text();
  3767. member.status = $(pres).find('>status').text();
  3768. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  3769. member.affiliation = tmp.attr('affiliation');
  3770. member.role = tmp.attr('role');
  3771. // Focus recognition
  3772. member.jid = tmp.attr('jid');
  3773. member.isFocus = false;
  3774. if (member.jid
  3775. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") == 0) {
  3776. member.isFocus = true;
  3777. }
  3778. $(pres).find(">x").remove();
  3779. var nodes = [];
  3780. parser.packet2JSON(pres, nodes);
  3781. this.lastPresences[from] = nodes;
  3782. for(var i = 0; i < nodes.length; i++)
  3783. {
  3784. var node = nodes[i];
  3785. switch(node.tagName)
  3786. {
  3787. case "nick":
  3788. member.nick = node.value;
  3789. if(!member.isFocus) {
  3790. var displayName = !this.xmpp.options.displayJids
  3791. ? member.nick : Strophe.getResourceFromJid(from);
  3792. if (displayName && displayName.length > 0) {
  3793. this.eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  3794. }
  3795. console.info("Display name: " + displayName, pres);
  3796. }
  3797. break;
  3798. case "userId":
  3799. member.id = node.value;
  3800. break;
  3801. case "email":
  3802. member.email = node.value;
  3803. break;
  3804. case "bridgeIsDown":
  3805. if(!this.bridgeIsDown) {
  3806. this.bridgeIsDown = true;
  3807. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  3808. }
  3809. break;
  3810. default :
  3811. this.processNode(node, from);
  3812. }
  3813. }
  3814. if (from == this.myroomjid) {
  3815. if (member.affiliation == 'owner')
  3816. if (this.role !== member.role) {
  3817. this.role = member.role;
  3818. this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  3819. member, this.isModerator());
  3820. }
  3821. if (!this.joined) {
  3822. this.joined = true;
  3823. this.eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  3824. }
  3825. } else if (this.members[from] === undefined) {
  3826. // new participant
  3827. this.members[from] = member;
  3828. console.log('entered', from, member);
  3829. if (member.isFocus) {
  3830. this.focusMucJid = from;
  3831. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  3832. }
  3833. else {
  3834. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, member.id || member.email, member.nick);
  3835. }
  3836. } else {
  3837. // Presence update for existing participant
  3838. // Watch role change:
  3839. if (this.members[from].role != member.role) {
  3840. this.members[from].role = member.role;
  3841. this.eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  3842. member.role, member.nick);
  3843. }
  3844. }
  3845. if(!member.isFocus)
  3846. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id || member.email);
  3847. // Trigger status message update
  3848. if (member.status) {
  3849. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  3850. }
  3851. };
  3852. ChatRoom.prototype.processNode = function (node, from) {
  3853. if(this.presHandlers[node.tagName])
  3854. this.presHandlers[node.tagName](node, from);
  3855. };
  3856. ChatRoom.prototype.sendMessage = function (body, nickname) {
  3857. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  3858. msg.c('body', body).up();
  3859. if (nickname) {
  3860. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  3861. }
  3862. this.connection.send(msg);
  3863. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  3864. };
  3865. ChatRoom.prototype.setSubject = function (subject) {
  3866. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  3867. msg.c('subject', subject);
  3868. this.connection.send(msg);
  3869. console.log("topic changed to " + subject);
  3870. };
  3871. ChatRoom.prototype.onParticipantLeft = function (jid) {
  3872. delete this.lastPresences[jid];
  3873. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  3874. this.moderator.onMucMemberLeft(jid);
  3875. };
  3876. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  3877. // room destroyed ?
  3878. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  3879. '>destroy').length) {
  3880. var reason;
  3881. var reasonSelect = $(pres).find(
  3882. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  3883. '>destroy>reason');
  3884. if (reasonSelect.length) {
  3885. reason = reasonSelect.text();
  3886. }
  3887. this.xmpp.disposeConference(false);
  3888. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  3889. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(jid)];
  3890. return true;
  3891. }
  3892. // Status code 110 indicates that this notification is "self-presence".
  3893. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  3894. delete this.members[from];
  3895. this.onParticipantLeft(from);
  3896. }
  3897. // If the status code is 110 this means we're leaving and we would like
  3898. // to remove everyone else from our view, so we trigger the event.
  3899. else if (Object.keys(this.members).length > 1) {
  3900. for (var i in this.members) {
  3901. var member = this.members[i];
  3902. delete this.members[i];
  3903. this.onParticipantLeft(member);
  3904. }
  3905. }
  3906. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  3907. if (this.myroomjid === from) {
  3908. this.xmpp.disposeConference(false);
  3909. this.eventEmitter.emit(XMPPEvents.KICKED);
  3910. }
  3911. }
  3912. };
  3913. ChatRoom.prototype.onMessage = function (msg, from) {
  3914. var nick =
  3915. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  3916. .text() ||
  3917. Strophe.getResourceFromJid(from);
  3918. var txt = $(msg).find('>body').text();
  3919. var type = msg.getAttribute("type");
  3920. if (type == "error") {
  3921. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  3922. $(msg).find('>text').text(), txt);
  3923. return true;
  3924. }
  3925. var subject = $(msg).find('>subject');
  3926. if (subject.length) {
  3927. var subjectText = subject.text();
  3928. if (subjectText || subjectText == "") {
  3929. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  3930. console.log("Subject is changed to " + subjectText);
  3931. }
  3932. }
  3933. // xep-0203 delay
  3934. var stamp = $(msg).find('>delay').attr('stamp');
  3935. if (!stamp) {
  3936. // or xep-0091 delay, UTC timestamp
  3937. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  3938. if (stamp) {
  3939. // the format is CCYYMMDDThh:mm:ss
  3940. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  3941. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  3942. }
  3943. }
  3944. if (txt) {
  3945. console.log('chat', nick, txt);
  3946. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  3947. from, nick, txt, this.myroomjid, stamp);
  3948. }
  3949. }
  3950. ChatRoom.prototype.onPresenceError = function (pres, from) {
  3951. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  3952. console.log('on password required', from);
  3953. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  3954. } else if ($(pres).find(
  3955. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  3956. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  3957. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  3958. // enter the room by replying with 'not-authorized'. This would
  3959. // result in reconnection from authorized domain.
  3960. // We're either missing Jicofo/Prosody config for anonymous
  3961. // domains or something is wrong.
  3962. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  3963. } else {
  3964. console.warn('onPresError ', pres);
  3965. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  3966. }
  3967. } else {
  3968. console.warn('onPresError ', pres);
  3969. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  3970. }
  3971. };
  3972. ChatRoom.prototype.kick = function (jid) {
  3973. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  3974. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  3975. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  3976. .c('reason').t('You have been kicked.').up().up().up();
  3977. this.connection.sendIQ(
  3978. kickIQ,
  3979. function (result) {
  3980. console.log('Kick participant with jid: ', jid, result);
  3981. },
  3982. function (error) {
  3983. console.log('Kick participant error: ', error);
  3984. });
  3985. };
  3986. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  3987. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  3988. var ob = this;
  3989. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  3990. function (res) {
  3991. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  3992. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  3993. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  3994. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  3995. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  3996. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  3997. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  3998. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  3999. ob.connection.sendIQ(formsubmit,
  4000. onSuccess,
  4001. onError);
  4002. } else {
  4003. onNotSupported();
  4004. }
  4005. }, onError);
  4006. };
  4007. ChatRoom.prototype.addToPresence = function (key, values) {
  4008. values.tagName = key;
  4009. this.presMap["nodes"].push(values);
  4010. };
  4011. ChatRoom.prototype.removeFromPresence = function (key) {
  4012. for(var i = 0; i < this.presMap.nodes.length; i++)
  4013. {
  4014. if(key === this.presMap.nodes[i].tagName)
  4015. this.presMap.nodes.splice(i, 1);
  4016. }
  4017. };
  4018. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  4019. this.presHandlers[name] = handler;
  4020. }
  4021. ChatRoom.prototype.removePresenceListener = function (name) {
  4022. delete this.presHandlers[name];
  4023. }
  4024. ChatRoom.prototype.isModerator = function (jid) {
  4025. return this.role === 'moderator';
  4026. };
  4027. ChatRoom.prototype.getMemberRole = function (peerJid) {
  4028. if (this.members[peerJid]) {
  4029. return this.members[peerJid].role;
  4030. }
  4031. return null;
  4032. };
  4033. ChatRoom.prototype.setJingleSession = function(session){
  4034. this.session = session;
  4035. this.session.room = this;
  4036. };
  4037. ChatRoom.prototype.removeStream = function (stream) {
  4038. if(!this.session)
  4039. return;
  4040. this.session.peerconnection.removeStream(stream)
  4041. }
  4042. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  4043. if(this.session) {
  4044. // FIXME: will block switchInProgress on true value in case of exception
  4045. this.session.switchStreams(stream, oldStream, callback, isAudio);
  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.addStream = function (stream, callback) {
  4053. if(this.session) {
  4054. // FIXME: will block switchInProgress on true value in case of exception
  4055. this.session.addStream(stream, callback);
  4056. } else {
  4057. // We are done immediately
  4058. console.warn("No conference handler or conference not started yet");
  4059. callback();
  4060. }
  4061. }
  4062. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  4063. var self = this;
  4064. var localCallback = function (mute) {
  4065. self.sendVideoInfoPresence(mute);
  4066. if(callback)
  4067. callback(mute)
  4068. };
  4069. if(this.session)
  4070. {
  4071. this.session.setVideoMute(
  4072. mute, localCallback, options);
  4073. }
  4074. else {
  4075. localCallback(mute);
  4076. }
  4077. };
  4078. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  4079. //This will be for remote streams only
  4080. // if (this.forceMuted && !mute) {
  4081. // console.info("Asking focus for unmute");
  4082. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  4083. // // FIXME: wait for result before resetting muted status
  4084. // this.forceMuted = false;
  4085. // }
  4086. return this.sendAudioInfoPresence(mute, callback);
  4087. };
  4088. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  4089. this.removeFromPresence("audiomuted");
  4090. this.addToPresence("audiomuted",
  4091. {attributes:
  4092. {"audions": "http://jitsi.org/jitmeet/audio"},
  4093. value: mute.toString()});
  4094. }
  4095. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  4096. this.addAudioInfoToPresence(mute);
  4097. if(this.connection) {
  4098. this.sendPresence();
  4099. }
  4100. if(callback)
  4101. callback();
  4102. };
  4103. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  4104. this.removeFromPresence("videomuted");
  4105. this.addToPresence("videomuted",
  4106. {attributes:
  4107. {"videons": "http://jitsi.org/jitmeet/video"},
  4108. value: mute.toString()});
  4109. }
  4110. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  4111. this.addVideoInfoToPresence(mute);
  4112. if(!this.connection)
  4113. return;
  4114. this.sendPresence();
  4115. };
  4116. ChatRoom.prototype.addListener = function(type, listener) {
  4117. this.eventEmitter.on(type, listener);
  4118. };
  4119. ChatRoom.prototype.removeListener = function (type, listener) {
  4120. this.eventEmitter.removeListener(type, listener);
  4121. };
  4122. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  4123. if(this.lastPresences[data.peerjid])
  4124. {
  4125. var pres = this.lastPresences[data.peerjid];
  4126. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  4127. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  4128. data.videomuted = ((videomuted.length > 0
  4129. && videomuted[0]
  4130. && videomuted[0]["value"] === "true")? true : false);
  4131. data.audiomuted = ((audiomuted.length > 0
  4132. && audiomuted[0]
  4133. && audiomuted[0]["value"] === "true")? true : false);
  4134. }
  4135. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  4136. }
  4137. ChatRoom.prototype.addLocalStreams = function (localStreams) {
  4138. this.session.addLocalStreams(localStreams);
  4139. }
  4140. module.exports = ChatRoom;
  4141. },{"../../service/xmpp/XMPPEvents":76,"./moderator":27,"events":77}],20:[function(require,module,exports){
  4142. /*
  4143. * JingleSession provides an API to manage a single Jingle session. We will
  4144. * have different implementations depending on the underlying interface used
  4145. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  4146. */
  4147. function JingleSession(me, sid, connection, service, eventEmitter) {
  4148. /**
  4149. * Our JID.
  4150. */
  4151. this.me = me;
  4152. /**
  4153. * The Jingle session identifier.
  4154. */
  4155. this.sid = sid;
  4156. /**
  4157. * The XMPP connection.
  4158. */
  4159. this.connection = connection;
  4160. /**
  4161. * The XMPP service.
  4162. */
  4163. this.service = service;
  4164. /**
  4165. * The event emitter.
  4166. */
  4167. this.eventEmitter = eventEmitter;
  4168. /**
  4169. * Whether to use dripping or not. Dripping is sending trickle candidates
  4170. * not one-by-one.
  4171. * Note: currently we do not support 'false'.
  4172. */
  4173. this.usedrip = true;
  4174. /**
  4175. * When dripping is used, stores ICE candidates which are to be sent.
  4176. */
  4177. this.drip_container = [];
  4178. // Media constraints. Is this WebRTC only?
  4179. this.media_constraints = null;
  4180. // ICE servers config (RTCConfiguration?).
  4181. this.ice_config = {};
  4182. // The chat room instance associated with the session.
  4183. this.room = null;
  4184. }
  4185. /**
  4186. * Prepares this object to initiate a session.
  4187. * @param peerjid the JID of the remote peer.
  4188. * @param isInitiator whether we will be the Jingle initiator.
  4189. * @param media_constraints
  4190. * @param ice_config
  4191. */
  4192. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  4193. media_constraints, ice_config) {
  4194. this.media_constraints = media_constraints;
  4195. this.ice_config = ice_config;
  4196. if (this.state !== null) {
  4197. console.error('attempt to initiate on session ' + this.sid +
  4198. 'in state ' + this.state);
  4199. return;
  4200. }
  4201. this.state = 'pending';
  4202. this.initiator = isInitiator ? this.me : peerjid;
  4203. this.responder = !isInitiator ? this.me : peerjid;
  4204. this.peerjid = peerjid;
  4205. this.doInitialize();
  4206. };
  4207. /**
  4208. * Finishes initialization.
  4209. */
  4210. JingleSession.prototype.doInitialize = function() {};
  4211. /**
  4212. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  4213. * Note: currently only used on transport-info
  4214. */
  4215. JingleSession.prototype.addIceCandidates = function(contents) {};
  4216. /**
  4217. * Handles an 'add-source' event.
  4218. *
  4219. * @param contents an array of Jingle 'content' elements.
  4220. */
  4221. JingleSession.prototype.addSources = function(contents) {};
  4222. /**
  4223. * Handles a 'remove-source' event.
  4224. *
  4225. * @param contents an array of Jingle 'content' elements.
  4226. */
  4227. JingleSession.prototype.removeSources = function(contents) {};
  4228. /**
  4229. * Terminates this Jingle session (stops sending media and closes the streams?)
  4230. */
  4231. JingleSession.prototype.terminate = function() {};
  4232. /**
  4233. * Sends a Jingle session-terminate message to the peer and terminates the
  4234. * session.
  4235. * @param reason
  4236. * @param text
  4237. */
  4238. JingleSession.prototype.sendTerminate = function(reason, text) {};
  4239. /**
  4240. * Handles an offer from the remote peer (prepares to accept a session).
  4241. * @param jingle the 'jingle' XML element.
  4242. */
  4243. JingleSession.prototype.setOffer = function(jingle) {};
  4244. /**
  4245. * Handles an answer from the remote peer (prepares to accept a session).
  4246. * @param jingle the 'jingle' XML element.
  4247. */
  4248. JingleSession.prototype.setAnswer = function(jingle) {};
  4249. module.exports = JingleSession;
  4250. },{}],21:[function(require,module,exports){
  4251. /* jshint -W117 */
  4252. var JingleSession = require("./JingleSession");
  4253. var TraceablePeerConnection = require("./TraceablePeerConnection");
  4254. var SDPDiffer = require("./SDPDiffer");
  4255. var SDPUtil = require("./SDPUtil");
  4256. var SDP = require("./SDP");
  4257. var async = require("async");
  4258. var transform = require("sdp-transform");
  4259. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  4260. var RTCBrowserType = require("../RTC/RTCBrowserType");
  4261. var SSRCReplacement = require("./LocalSSRCReplacement");
  4262. var RTC = require("../RTC/RTC");
  4263. // Jingle stuff
  4264. function JingleSessionPC(me, sid, connection, service) {
  4265. JingleSession.call(this, me, sid, connection, service);
  4266. this.initiator = null;
  4267. this.responder = null;
  4268. this.peerjid = null;
  4269. this.state = null;
  4270. this.localSDP = null;
  4271. this.remoteSDP = null;
  4272. this.relayedStreams = [];
  4273. this.usetrickle = true;
  4274. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  4275. this.hadstuncandidate = false;
  4276. this.hadturncandidate = false;
  4277. this.lasticecandidate = false;
  4278. this.statsinterval = null;
  4279. this.reason = null;
  4280. this.addssrc = [];
  4281. this.removessrc = [];
  4282. this.pendingop = null;
  4283. this.switchstreams = false;
  4284. this.addingStreams = false;
  4285. this.wait = true;
  4286. this.localStreamsSSRC = null;
  4287. this.ssrcOwners = {};
  4288. this.ssrcVideoTypes = {};
  4289. /**
  4290. * The indicator which determines whether the (local) video has been muted
  4291. * in response to a user command in contrast to an automatic decision made
  4292. * by the application logic.
  4293. */
  4294. this.videoMuteByUser = false;
  4295. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  4296. // We start with the queue paused. We resume it when the signaling state is
  4297. // stable and the ice connection state is connected.
  4298. this.modifySourcesQueue.pause();
  4299. }
  4300. JingleSessionPC.prototype = JingleSession.prototype;
  4301. JingleSessionPC.prototype.constructor = JingleSessionPC;
  4302. JingleSessionPC.prototype.setOffer = function(offer) {
  4303. this.setRemoteDescription(offer, 'offer');
  4304. };
  4305. JingleSessionPC.prototype.setAnswer = function(answer) {
  4306. this.setRemoteDescription(answer, 'answer');
  4307. };
  4308. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  4309. var signalingState = this.peerconnection.signalingState;
  4310. var iceConnectionState = this.peerconnection.iceConnectionState;
  4311. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  4312. this.modifySourcesQueue.resume();
  4313. } else {
  4314. this.modifySourcesQueue.pause();
  4315. }
  4316. };
  4317. JingleSessionPC.prototype.doInitialize = function () {
  4318. var self = this;
  4319. this.hadstuncandidate = false;
  4320. this.hadturncandidate = false;
  4321. this.lasticecandidate = false;
  4322. this.isreconnect = false;
  4323. this.peerconnection = new TraceablePeerConnection(
  4324. this.connection.jingle.ice_config,
  4325. RTC.getPCConstraints(),
  4326. this);
  4327. this.peerconnection.onicecandidate = function (event) {
  4328. self.sendIceCandidate(event.candidate);
  4329. };
  4330. this.peerconnection.onaddstream = function (event) {
  4331. if (event.stream.id !== 'default') {
  4332. console.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  4333. self.remoteStreamAdded(event);
  4334. } else {
  4335. // This is a recvonly stream. Clients that implement Unified Plan,
  4336. // such as Firefox use recvonly "streams/channels/tracks" for
  4337. // receiving remote stream/tracks, as opposed to Plan B where there
  4338. // are only 3 channels: audio, video and data.
  4339. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  4340. }
  4341. };
  4342. this.peerconnection.onremovestream = function (event) {
  4343. // Remove the stream from remoteStreams
  4344. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  4345. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  4346. };
  4347. this.peerconnection.onsignalingstatechange = function (event) {
  4348. if (!(self && self.peerconnection)) return;
  4349. self.updateModifySourcesQueue();
  4350. };
  4351. /**
  4352. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  4353. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  4354. * RTCPeerConnection.iceConnectionState changes.
  4355. *
  4356. * @param event the event containing information about the change
  4357. */
  4358. this.peerconnection.oniceconnectionstatechange = function (event) {
  4359. if (!(self && self.peerconnection)) return;
  4360. self.updateModifySourcesQueue();
  4361. switch (self.peerconnection.iceConnectionState) {
  4362. case 'connected':
  4363. // Informs interested parties that the connection has been restored.
  4364. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  4365. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  4366. self.isreconnect = false;
  4367. break;
  4368. case 'disconnected':
  4369. self.isreconnect = true;
  4370. // Informs interested parties that the connection has been interrupted.
  4371. if (self.peerconnection.signalingState === 'stable')
  4372. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  4373. break;
  4374. case 'failed':
  4375. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4376. break;
  4377. }
  4378. onIceConnectionStateChange(self.sid, self);
  4379. };
  4380. this.peerconnection.onnegotiationneeded = function (event) {
  4381. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  4382. };
  4383. this.relayedStreams.forEach(function(stream) {
  4384. self.peerconnection.addStream(stream);
  4385. });
  4386. };
  4387. JingleSessionPC.prototype.addLocalStreams = function (localStreams) {
  4388. var self = this;
  4389. // add any local and relayed stream
  4390. localStreams.forEach(function(stream) {
  4391. if(!stream.isStarted())
  4392. return;
  4393. self.peerconnection.addStream(stream.getOriginalStream());
  4394. });
  4395. }
  4396. function onIceConnectionStateChange(sid, session) {
  4397. switch (session.peerconnection.iceConnectionState) {
  4398. case 'checking':
  4399. session.timeChecking = (new Date()).getTime();
  4400. session.firstconnect = true;
  4401. break;
  4402. case 'completed': // on caller side
  4403. case 'connected':
  4404. if (session.firstconnect) {
  4405. session.firstconnect = false;
  4406. var metadata = {};
  4407. metadata.setupTime
  4408. = (new Date()).getTime() - session.timeChecking;
  4409. session.peerconnection.getStats(function (res) {
  4410. if(res && res.result) {
  4411. res.result().forEach(function (report) {
  4412. if (report.type == 'googCandidatePair' &&
  4413. report.stat('googActiveConnection') == 'true') {
  4414. metadata.localCandidateType
  4415. = report.stat('googLocalCandidateType');
  4416. metadata.remoteCandidateType
  4417. = report.stat('googRemoteCandidateType');
  4418. // log pair as well so we can get nice pie
  4419. // charts
  4420. metadata.candidatePair
  4421. = report.stat('googLocalCandidateType') +
  4422. ';' +
  4423. report.stat('googRemoteCandidateType');
  4424. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  4425. {
  4426. metadata.ipv6 = true;
  4427. }
  4428. }
  4429. });
  4430. }
  4431. });
  4432. }
  4433. break;
  4434. }
  4435. }
  4436. JingleSessionPC.prototype.accept = function () {
  4437. this.state = 'active';
  4438. var pranswer = this.peerconnection.localDescription;
  4439. if (!pranswer || pranswer.type != 'pranswer') {
  4440. return;
  4441. }
  4442. console.log('going from pranswer to answer');
  4443. if (this.usetrickle) {
  4444. // remove candidates already sent from session-accept
  4445. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  4446. for (var i = 0; i < lines.length; i++) {
  4447. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  4448. }
  4449. }
  4450. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  4451. // FIXME: change any inactive to sendrecv or whatever they were originally
  4452. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  4453. }
  4454. var prsdp = new SDP(pranswer.sdp);
  4455. var accept = $iq({to: this.peerjid,
  4456. type: 'set'})
  4457. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4458. action: 'session-accept',
  4459. initiator: this.initiator,
  4460. responder: this.responder,
  4461. sid: this.sid });
  4462. // FIXME why do we generate session-accept in 3 different places ?
  4463. prsdp.toJingle(
  4464. accept,
  4465. this.initiator == this.me ? 'initiator' : 'responder',
  4466. this.localStreamsSSRC);
  4467. var sdp = this.peerconnection.localDescription.sdp;
  4468. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  4469. // FIXME: change any inactive to sendrecv or whatever they were originally
  4470. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  4471. }
  4472. var self = this;
  4473. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  4474. function () {
  4475. //console.log('setLocalDescription success');
  4476. self.setLocalDescription();
  4477. SSRCReplacement.processSessionInit(accept);
  4478. self.connection.sendIQ(accept,
  4479. function () {
  4480. var ack = {};
  4481. ack.source = 'answer';
  4482. $(document).trigger('ack.jingle', [self.sid, ack]);
  4483. },
  4484. function (stanza) {
  4485. var error = ($(stanza).find('error').length) ? {
  4486. code: $(stanza).find('error').attr('code'),
  4487. reason: $(stanza).find('error :first')[0].tagName
  4488. }:{};
  4489. error.source = 'answer';
  4490. JingleSessionPC.onJingleError(self.sid, error);
  4491. },
  4492. 10000);
  4493. },
  4494. function (e) {
  4495. console.error('setLocalDescription failed', e);
  4496. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4497. }
  4498. );
  4499. };
  4500. JingleSessionPC.prototype.terminate = function (reason) {
  4501. this.state = 'ended';
  4502. this.reason = reason;
  4503. this.peerconnection.close();
  4504. if (this.statsinterval !== null) {
  4505. window.clearInterval(this.statsinterval);
  4506. this.statsinterval = null;
  4507. }
  4508. };
  4509. JingleSessionPC.prototype.active = function () {
  4510. return this.state == 'active';
  4511. };
  4512. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  4513. var self = this;
  4514. if (candidate && !this.lasticecandidate) {
  4515. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  4516. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  4517. if (!(ice && jcand)) {
  4518. console.error('failed to get ice && jcand');
  4519. return;
  4520. }
  4521. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  4522. if (jcand.type === 'srflx') {
  4523. this.hadstuncandidate = true;
  4524. } else if (jcand.type === 'relay') {
  4525. this.hadturncandidate = true;
  4526. }
  4527. if (this.usetrickle) {
  4528. if (this.usedrip) {
  4529. if (this.drip_container.length === 0) {
  4530. // start 20ms callout
  4531. window.setTimeout(function () {
  4532. if (self.drip_container.length === 0) return;
  4533. self.sendIceCandidates(self.drip_container);
  4534. self.drip_container = [];
  4535. }, 20);
  4536. }
  4537. this.drip_container.push(candidate);
  4538. return;
  4539. } else {
  4540. self.sendIceCandidate([candidate]);
  4541. }
  4542. }
  4543. } else {
  4544. //console.log('sendIceCandidate: last candidate.');
  4545. if (!this.usetrickle) {
  4546. //console.log('should send full offer now...');
  4547. //FIXME why do we generate session-accept in 3 different places ?
  4548. var init = $iq({to: this.peerjid,
  4549. type: 'set'})
  4550. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4551. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  4552. initiator: this.initiator,
  4553. sid: this.sid});
  4554. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  4555. var sendJingle = function (ssrc) {
  4556. if(!ssrc)
  4557. ssrc = {};
  4558. self.localSDP.toJingle(
  4559. init,
  4560. self.initiator == self.me ? 'initiator' : 'responder',
  4561. ssrc);
  4562. SSRCReplacement.processSessionInit(init);
  4563. self.connection.sendIQ(init,
  4564. function () {
  4565. //console.log('session initiate ack');
  4566. var ack = {};
  4567. ack.source = 'offer';
  4568. $(document).trigger('ack.jingle', [self.sid, ack]);
  4569. },
  4570. function (stanza) {
  4571. self.state = 'error';
  4572. self.peerconnection.close();
  4573. var error = ($(stanza).find('error').length) ? {
  4574. code: $(stanza).find('error').attr('code'),
  4575. reason: $(stanza).find('error :first')[0].tagName,
  4576. }:{};
  4577. error.source = 'offer';
  4578. JingleSessionPC.onJingleError(self.sid, error);
  4579. },
  4580. 10000);
  4581. };
  4582. sendJingle();
  4583. }
  4584. this.lasticecandidate = true;
  4585. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  4586. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  4587. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  4588. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  4589. }
  4590. }
  4591. };
  4592. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  4593. console.log('sendIceCandidates', candidates);
  4594. var cand = $iq({to: this.peerjid, type: 'set'})
  4595. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4596. action: 'transport-info',
  4597. initiator: this.initiator,
  4598. sid: this.sid});
  4599. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  4600. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  4601. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  4602. if (cands.length > 0) {
  4603. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  4604. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  4605. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  4606. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  4607. }).c('transport', ice);
  4608. for (var i = 0; i < cands.length; i++) {
  4609. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  4610. }
  4611. // add fingerprint
  4612. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  4613. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  4614. tmp.required = true;
  4615. cand.c(
  4616. 'fingerprint',
  4617. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  4618. .t(tmp.fingerprint);
  4619. delete tmp.fingerprint;
  4620. cand.attrs(tmp);
  4621. cand.up();
  4622. }
  4623. cand.up(); // transport
  4624. cand.up(); // content
  4625. }
  4626. }
  4627. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  4628. //console.log('was this the last candidate', this.lasticecandidate);
  4629. this.connection.sendIQ(cand,
  4630. function () {
  4631. var ack = {};
  4632. ack.source = 'transportinfo';
  4633. $(document).trigger('ack.jingle', [this.sid, ack]);
  4634. },
  4635. function (stanza) {
  4636. var error = ($(stanza).find('error').length) ? {
  4637. code: $(stanza).find('error').attr('code'),
  4638. reason: $(stanza).find('error :first')[0].tagName,
  4639. }:{};
  4640. error.source = 'transportinfo';
  4641. JingleSessionPC.onJingleError(this.sid, error);
  4642. },
  4643. 10000);
  4644. };
  4645. JingleSessionPC.prototype.sendOffer = function () {
  4646. //console.log('sendOffer...');
  4647. var self = this;
  4648. this.peerconnection.createOffer(function (sdp) {
  4649. self.createdOffer(sdp);
  4650. },
  4651. function (e) {
  4652. console.error('createOffer failed', e);
  4653. },
  4654. this.media_constraints
  4655. );
  4656. };
  4657. // FIXME createdOffer is never used in jitsi-meet
  4658. JingleSessionPC.prototype.createdOffer = function (sdp) {
  4659. //console.log('createdOffer', sdp);
  4660. var self = this;
  4661. this.localSDP = new SDP(sdp.sdp);
  4662. //this.localSDP.mangle();
  4663. var sendJingle = function () {
  4664. var init = $iq({to: this.peerjid,
  4665. type: 'set'})
  4666. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4667. action: 'session-initiate',
  4668. initiator: this.initiator,
  4669. sid: this.sid});
  4670. self.localSDP.toJingle(
  4671. init,
  4672. this.initiator == this.me ? 'initiator' : 'responder',
  4673. this.localStreamsSSRC);
  4674. SSRCReplacement.processSessionInit(init);
  4675. self.connection.sendIQ(init,
  4676. function () {
  4677. var ack = {};
  4678. ack.source = 'offer';
  4679. $(document).trigger('ack.jingle', [self.sid, ack]);
  4680. },
  4681. function (stanza) {
  4682. self.state = 'error';
  4683. self.peerconnection.close();
  4684. var error = ($(stanza).find('error').length) ? {
  4685. code: $(stanza).find('error').attr('code'),
  4686. reason: $(stanza).find('error :first')[0].tagName,
  4687. }:{};
  4688. error.source = 'offer';
  4689. JingleSessionPC.onJingleError(self.sid, error);
  4690. },
  4691. 10000);
  4692. }
  4693. sdp.sdp = this.localSDP.raw;
  4694. this.peerconnection.setLocalDescription(sdp,
  4695. function () {
  4696. if(self.usetrickle)
  4697. {
  4698. sendJingle();
  4699. }
  4700. self.setLocalDescription();
  4701. //console.log('setLocalDescription success');
  4702. },
  4703. function (e) {
  4704. console.error('setLocalDescription failed', e);
  4705. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4706. }
  4707. );
  4708. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  4709. for (var i = 0; i < cands.length; i++) {
  4710. var cand = SDPUtil.parse_icecandidate(cands[i]);
  4711. if (cand.type == 'srflx') {
  4712. this.hadstuncandidate = true;
  4713. } else if (cand.type == 'relay') {
  4714. this.hadturncandidate = true;
  4715. }
  4716. }
  4717. };
  4718. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  4719. var self = this;
  4720. $(contents).each(function (idx, content) {
  4721. var name = $(content).attr('name');
  4722. var mediaType = this.getAttribute('name');
  4723. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  4724. ssrcs.each(function () {
  4725. var ssrc = this.getAttribute('ssrc');
  4726. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  4727. function () {
  4728. var owner = this.getAttribute('owner');
  4729. self.ssrcOwners[ssrc] = owner;
  4730. }
  4731. );
  4732. });
  4733. });
  4734. };
  4735. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  4736. return this.ssrcOwners[ssrc];
  4737. };
  4738. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  4739. //console.log('setting remote description... ', desctype);
  4740. this.remoteSDP = new SDP('');
  4741. this.remoteSDP.fromJingle(elem);
  4742. this.readSsrcInfo($(elem).find(">content"));
  4743. if (this.peerconnection.remoteDescription !== null) {
  4744. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  4745. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  4746. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  4747. for (var i = 0; i < pranswer.media.length; i++) {
  4748. // make sure we have ice ufrag and pwd
  4749. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  4750. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  4751. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  4752. } else {
  4753. console.warn('no ice ufrag?');
  4754. }
  4755. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  4756. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  4757. } else {
  4758. console.warn('no ice pwd?');
  4759. }
  4760. }
  4761. // copy over candidates
  4762. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  4763. for (var j = 0; j < lines.length; j++) {
  4764. this.remoteSDP.media[i] += lines[j] + '\r\n';
  4765. }
  4766. }
  4767. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  4768. }
  4769. }
  4770. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  4771. this.peerconnection.setRemoteDescription(remotedesc,
  4772. function () {
  4773. //console.log('setRemoteDescription success');
  4774. },
  4775. function (e) {
  4776. console.error('setRemoteDescription error', e);
  4777. JingleSessionPC.onJingleFatalError(self, e);
  4778. }
  4779. );
  4780. };
  4781. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  4782. var self = this;
  4783. if (this.peerconnection.signalingState == 'closed') {
  4784. return;
  4785. }
  4786. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  4787. console.log('trickle ice candidate arriving before session accept...');
  4788. // create a PRANSWER for setRemoteDescription
  4789. if (!this.remoteSDP) {
  4790. var cobbled = 'v=0\r\n' +
  4791. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  4792. 's=-\r\n' +
  4793. 't=0 0\r\n';
  4794. // first, take some things from the local description
  4795. for (var i = 0; i < this.localSDP.media.length; i++) {
  4796. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  4797. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  4798. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  4799. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  4800. }
  4801. cobbled += 'a=inactive\r\n';
  4802. }
  4803. this.remoteSDP = new SDP(cobbled);
  4804. }
  4805. // then add things like ice and dtls from remote candidate
  4806. elem.each(function () {
  4807. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  4808. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  4809. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  4810. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  4811. var tmp = $(this).find('transport');
  4812. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  4813. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  4814. tmp = $(this).find('transport>fingerprint');
  4815. if (tmp.length) {
  4816. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  4817. } else {
  4818. console.log('no dtls fingerprint (webrtc issue #1718?)');
  4819. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  4820. }
  4821. break;
  4822. }
  4823. }
  4824. }
  4825. });
  4826. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  4827. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  4828. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  4829. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  4830. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  4831. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  4832. }).length == this.remoteSDP.media.length;
  4833. if (iscomplete) {
  4834. console.log('setting pranswer');
  4835. try {
  4836. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  4837. function() {
  4838. },
  4839. function(e) {
  4840. console.log('setRemoteDescription pranswer failed', e.toString());
  4841. });
  4842. } catch (e) {
  4843. console.error('setting pranswer failed', e);
  4844. }
  4845. } else {
  4846. //console.log('not yet setting pranswer');
  4847. }
  4848. }
  4849. // operate on each content element
  4850. elem.each(function () {
  4851. // would love to deactivate this, but firefox still requires it
  4852. var idx = -1;
  4853. var i;
  4854. for (i = 0; i < self.remoteSDP.media.length; i++) {
  4855. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  4856. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  4857. idx = i;
  4858. break;
  4859. }
  4860. }
  4861. if (idx == -1) { // fall back to localdescription
  4862. for (i = 0; i < self.localSDP.media.length; i++) {
  4863. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  4864. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  4865. idx = i;
  4866. break;
  4867. }
  4868. }
  4869. }
  4870. var name = $(this).attr('name');
  4871. // TODO: check ice-pwd and ice-ufrag?
  4872. $(this).find('transport>candidate').each(function () {
  4873. var line, candidate;
  4874. line = SDPUtil.candidateFromJingle(this);
  4875. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  4876. sdpMid: name,
  4877. candidate: line});
  4878. try {
  4879. self.peerconnection.addIceCandidate(candidate);
  4880. } catch (e) {
  4881. console.error('addIceCandidate failed', e.toString(), line);
  4882. }
  4883. });
  4884. });
  4885. };
  4886. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  4887. //console.log('createAnswer', provisional);
  4888. var self = this;
  4889. this.peerconnection.createAnswer(
  4890. function (sdp) {
  4891. self.createdAnswer(sdp, provisional);
  4892. },
  4893. function (e) {
  4894. console.error('createAnswer failed', e);
  4895. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4896. },
  4897. this.media_constraints
  4898. );
  4899. };
  4900. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  4901. //console.log('createAnswer callback');
  4902. var self = this;
  4903. this.localSDP = new SDP(sdp.sdp);
  4904. //this.localSDP.mangle();
  4905. this.usepranswer = provisional === true;
  4906. if (this.usetrickle) {
  4907. if (this.usepranswer) {
  4908. sdp.type = 'pranswer';
  4909. for (var i = 0; i < this.localSDP.media.length; i++) {
  4910. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  4911. }
  4912. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  4913. }
  4914. }
  4915. var self = this;
  4916. var sendJingle = function (ssrcs) {
  4917. // FIXME why do we generate session-accept in 3 different places ?
  4918. var accept = $iq({to: self.peerjid,
  4919. type: 'set'})
  4920. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4921. action: 'session-accept',
  4922. initiator: self.initiator,
  4923. responder: self.responder,
  4924. sid: self.sid });
  4925. self.localSDP.toJingle(
  4926. accept,
  4927. self.initiator == self.me ? 'initiator' : 'responder',
  4928. ssrcs);
  4929. SSRCReplacement.processSessionInit(accept);
  4930. self.connection.sendIQ(accept,
  4931. function () {
  4932. var ack = {};
  4933. ack.source = 'answer';
  4934. $(document).trigger('ack.jingle', [self.sid, ack]);
  4935. },
  4936. function (stanza) {
  4937. var error = ($(stanza).find('error').length) ? {
  4938. code: $(stanza).find('error').attr('code'),
  4939. reason: $(stanza).find('error :first')[0].tagName,
  4940. }:{};
  4941. error.source = 'answer';
  4942. JingleSessionPC.onJingleError(self.sid, error);
  4943. },
  4944. 10000);
  4945. }
  4946. sdp.sdp = this.localSDP.raw;
  4947. this.peerconnection.setLocalDescription(sdp,
  4948. function () {
  4949. //console.log('setLocalDescription success');
  4950. if (self.usetrickle && !self.usepranswer) {
  4951. sendJingle();
  4952. }
  4953. self.setLocalDescription();
  4954. },
  4955. function (e) {
  4956. console.error('setLocalDescription failed', e);
  4957. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4958. }
  4959. );
  4960. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  4961. for (var j = 0; j < cands.length; j++) {
  4962. var cand = SDPUtil.parse_icecandidate(cands[j]);
  4963. if (cand.type == 'srflx') {
  4964. this.hadstuncandidate = true;
  4965. } else if (cand.type == 'relay') {
  4966. this.hadturncandidate = true;
  4967. }
  4968. }
  4969. };
  4970. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  4971. var self = this,
  4972. term = $iq({to: this.peerjid,
  4973. type: 'set'})
  4974. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4975. action: 'session-terminate',
  4976. initiator: this.initiator,
  4977. sid: this.sid})
  4978. .c('reason')
  4979. .c(reason || 'success');
  4980. if (text) {
  4981. term.up().c('text').t(text);
  4982. }
  4983. this.connection.sendIQ(term,
  4984. function () {
  4985. self.peerconnection.close();
  4986. self.peerconnection = null;
  4987. self.terminate();
  4988. var ack = {};
  4989. ack.source = 'terminate';
  4990. $(document).trigger('ack.jingle', [self.sid, ack]);
  4991. },
  4992. function (stanza) {
  4993. var error = ($(stanza).find('error').length) ? {
  4994. code: $(stanza).find('error').attr('code'),
  4995. reason: $(stanza).find('error :first')[0].tagName,
  4996. }:{};
  4997. $(document).trigger('ack.jingle', [self.sid, error]);
  4998. },
  4999. 10000);
  5000. if (this.statsinterval !== null) {
  5001. window.clearInterval(this.statsinterval);
  5002. this.statsinterval = null;
  5003. }
  5004. };
  5005. JingleSessionPC.prototype.addSource = function (elem, fromJid) {
  5006. var self = this;
  5007. // FIXME: dirty waiting
  5008. if (!this.peerconnection.localDescription)
  5009. {
  5010. console.warn("addSource - localDescription not ready yet")
  5011. setTimeout(function()
  5012. {
  5013. self.addSource(elem, fromJid);
  5014. },
  5015. 200
  5016. );
  5017. return;
  5018. }
  5019. console.log('addssrc', new Date().getTime());
  5020. console.log('ice', this.peerconnection.iceConnectionState);
  5021. this.readSsrcInfo(elem);
  5022. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  5023. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  5024. $(elem).each(function (idx, content) {
  5025. var name = $(content).attr('name');
  5026. var lines = '';
  5027. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  5028. var semantics = this.getAttribute('semantics');
  5029. var ssrcs = $(this).find('>source').map(function () {
  5030. return this.getAttribute('ssrc');
  5031. }).get();
  5032. if (ssrcs.length != 0) {
  5033. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  5034. }
  5035. });
  5036. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  5037. tmp.each(function () {
  5038. var ssrc = $(this).attr('ssrc');
  5039. if(mySdp.containsSSRC(ssrc)){
  5040. /**
  5041. * This happens when multiple participants change their streams at the same time and
  5042. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  5043. * addssrc are scheduled for update IQ. See
  5044. */
  5045. console.warn("Got add stream request for my own ssrc: "+ssrc);
  5046. return;
  5047. }
  5048. if (sdp.containsSSRC(ssrc)) {
  5049. console.warn("Source-add request for existing SSRC: " + ssrc);
  5050. return;
  5051. }
  5052. $(this).find('>parameter').each(function () {
  5053. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  5054. if ($(this).attr('value') && $(this).attr('value').length)
  5055. lines += ':' + $(this).attr('value');
  5056. lines += '\r\n';
  5057. });
  5058. });
  5059. sdp.media.forEach(function(media, idx) {
  5060. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  5061. return;
  5062. sdp.media[idx] += lines;
  5063. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  5064. self.addssrc[idx] += lines;
  5065. });
  5066. sdp.raw = sdp.session + sdp.media.join('');
  5067. });
  5068. this.modifySourcesQueue.push(function() {
  5069. // When a source is added and if this is FF, a new channel is allocated
  5070. // for receiving the added source. We need to diffuse the SSRC of this
  5071. // new recvonly channel to the rest of the peers.
  5072. console.log('modify sources done');
  5073. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  5074. console.log("SDPs", mySdp, newSdp);
  5075. self.notifyMySSRCUpdate(mySdp, newSdp);
  5076. });
  5077. };
  5078. JingleSessionPC.prototype.removeSource = function (elem, fromJid) {
  5079. var self = this;
  5080. // FIXME: dirty waiting
  5081. if (!this.peerconnection.localDescription)
  5082. {
  5083. console.warn("removeSource - localDescription not ready yet")
  5084. setTimeout(function()
  5085. {
  5086. self.removeSource(elem, fromJid);
  5087. },
  5088. 200
  5089. );
  5090. return;
  5091. }
  5092. console.log('removessrc', new Date().getTime());
  5093. console.log('ice', this.peerconnection.iceConnectionState);
  5094. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  5095. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  5096. $(elem).each(function (idx, content) {
  5097. var name = $(content).attr('name');
  5098. var lines = '';
  5099. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  5100. var semantics = this.getAttribute('semantics');
  5101. var ssrcs = $(this).find('>source').map(function () {
  5102. return this.getAttribute('ssrc');
  5103. }).get();
  5104. if (ssrcs.length != 0) {
  5105. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  5106. }
  5107. });
  5108. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  5109. tmp.each(function () {
  5110. var ssrc = $(this).attr('ssrc');
  5111. // This should never happen, but can be useful for bug detection
  5112. if(mySdp.containsSSRC(ssrc)){
  5113. console.error("Got remove stream request for my own ssrc: "+ssrc);
  5114. return;
  5115. }
  5116. $(this).find('>parameter').each(function () {
  5117. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  5118. if ($(this).attr('value') && $(this).attr('value').length)
  5119. lines += ':' + $(this).attr('value');
  5120. lines += '\r\n';
  5121. });
  5122. });
  5123. sdp.media.forEach(function(media, idx) {
  5124. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  5125. return;
  5126. sdp.media[idx] += lines;
  5127. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  5128. self.removessrc[idx] += lines;
  5129. });
  5130. sdp.raw = sdp.session + sdp.media.join('');
  5131. });
  5132. this.modifySourcesQueue.push(function() {
  5133. // When a source is removed and if this is FF, the recvonly channel that
  5134. // receives the remote stream is deactivated . We need to diffuse the
  5135. // recvonly SSRC removal to the rest of the peers.
  5136. console.log('modify sources done');
  5137. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  5138. console.log("SDPs", mySdp, newSdp);
  5139. self.notifyMySSRCUpdate(mySdp, newSdp);
  5140. });
  5141. };
  5142. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  5143. var self = this;
  5144. if (this.peerconnection.signalingState == 'closed') return;
  5145. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  5146. || this.switchstreams || this.addingStreams)){
  5147. // There is nothing to do since scheduled job might have been executed by another succeeding call
  5148. this.setLocalDescription();
  5149. if(successCallback){
  5150. successCallback();
  5151. }
  5152. queueCallback();
  5153. return;
  5154. }
  5155. // Reset switch streams flags
  5156. this.switchstreams = false;
  5157. this.addingStreams = false;
  5158. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  5159. // add sources
  5160. this.addssrc.forEach(function(lines, idx) {
  5161. sdp.media[idx] += lines;
  5162. });
  5163. this.addssrc = [];
  5164. // remove sources
  5165. this.removessrc.forEach(function(lines, idx) {
  5166. lines = lines.split('\r\n');
  5167. lines.pop(); // remove empty last element;
  5168. lines.forEach(function(line) {
  5169. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  5170. });
  5171. });
  5172. this.removessrc = [];
  5173. sdp.raw = sdp.session + sdp.media.join('');
  5174. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  5175. function() {
  5176. if(self.signalingState == 'closed') {
  5177. console.error("createAnswer attempt on closed state");
  5178. queueCallback("createAnswer attempt on closed state");
  5179. return;
  5180. }
  5181. self.peerconnection.createAnswer(
  5182. function(modifiedAnswer) {
  5183. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  5184. if (self.pendingop !== null) {
  5185. var sdp = new SDP(modifiedAnswer.sdp);
  5186. if (sdp.media.length > 1) {
  5187. switch(self.pendingop) {
  5188. case 'mute':
  5189. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  5190. break;
  5191. case 'unmute':
  5192. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  5193. break;
  5194. }
  5195. sdp.raw = sdp.session + sdp.media.join('');
  5196. modifiedAnswer.sdp = sdp.raw;
  5197. }
  5198. self.pendingop = null;
  5199. }
  5200. // FIXME: pushing down an answer while ice connection state
  5201. // is still checking is bad...
  5202. //console.log(self.peerconnection.iceConnectionState);
  5203. // trying to work around another chrome bug
  5204. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  5205. self.peerconnection.setLocalDescription(modifiedAnswer,
  5206. function() {
  5207. //console.log('modified setLocalDescription ok');
  5208. self.setLocalDescription();
  5209. if(successCallback){
  5210. successCallback();
  5211. }
  5212. queueCallback();
  5213. },
  5214. function(error) {
  5215. console.error('modified setLocalDescription failed', error);
  5216. queueCallback(error);
  5217. }
  5218. );
  5219. },
  5220. function(error) {
  5221. console.error('modified answer failed', error);
  5222. queueCallback(error);
  5223. }
  5224. );
  5225. },
  5226. function(error) {
  5227. console.error('modify failed', error);
  5228. queueCallback(error);
  5229. }
  5230. );
  5231. };
  5232. /**
  5233. * Switches video streams.
  5234. * @param new_stream new stream that will be used as video of this session.
  5235. * @param oldStream old video stream of this session.
  5236. * @param success_callback callback executed after successful stream switch.
  5237. */
  5238. JingleSessionPC.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  5239. var self = this;
  5240. // Remember SDP to figure out added/removed SSRCs
  5241. var oldSdp = null;
  5242. if(self.peerconnection) {
  5243. if(self.peerconnection.localDescription) {
  5244. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  5245. }
  5246. self.peerconnection.removeStream(oldStream, true);
  5247. if(new_stream)
  5248. self.peerconnection.addStream(new_stream);
  5249. }
  5250. // Conference is not active
  5251. if(!oldSdp || !self.peerconnection) {
  5252. success_callback();
  5253. return;
  5254. }
  5255. self.switchstreams = true;
  5256. self.modifySourcesQueue.push(function() {
  5257. console.log('modify sources done');
  5258. success_callback();
  5259. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  5260. console.log("SDPs", oldSdp, newSdp);
  5261. self.notifyMySSRCUpdate(oldSdp, newSdp);
  5262. });
  5263. };
  5264. /**
  5265. * Adds streams.
  5266. * @param stream new stream that will be added.
  5267. * @param success_callback callback executed after successful stream addition.
  5268. */
  5269. JingleSessionPC.prototype.addStream = function (stream, callback) {
  5270. var self = this;
  5271. // Remember SDP to figure out added/removed SSRCs
  5272. var oldSdp = null;
  5273. if(this.peerconnection) {
  5274. if(this.peerconnection.localDescription) {
  5275. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  5276. }
  5277. if(stream)
  5278. this.peerconnection.addStream(stream);
  5279. }
  5280. // Conference is not active
  5281. if(!oldSdp || !this.peerconnection) {
  5282. callback();
  5283. return;
  5284. }
  5285. this.addingStreams = true;
  5286. this.modifySourcesQueue.push(function() {
  5287. console.log('modify sources done');
  5288. callback();
  5289. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  5290. console.log("SDPs", oldSdp, newSdp);
  5291. self.notifyMySSRCUpdate(oldSdp, newSdp);
  5292. });
  5293. }
  5294. /**
  5295. * Figures out added/removed ssrcs and send update IQs.
  5296. * @param old_sdp SDP object for old description.
  5297. * @param new_sdp SDP object for new description.
  5298. */
  5299. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  5300. if (!(this.peerconnection.signalingState == 'stable' &&
  5301. this.peerconnection.iceConnectionState == 'connected')){
  5302. console.log("Too early to send updates");
  5303. return;
  5304. }
  5305. // send source-remove IQ.
  5306. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  5307. var remove = $iq({to: this.peerjid, type: 'set'})
  5308. .c('jingle', {
  5309. xmlns: 'urn:xmpp:jingle:1',
  5310. action: 'source-remove',
  5311. initiator: this.initiator,
  5312. sid: this.sid
  5313. }
  5314. );
  5315. var removed = sdpDiffer.toJingle(remove);
  5316. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  5317. // it in the current form
  5318. if (removed)
  5319. remove = SSRCReplacement.processSourceRemove(remove);
  5320. if (removed && remove) {
  5321. console.info("Sending source-remove", remove);
  5322. this.connection.sendIQ(remove,
  5323. function (res) {
  5324. console.info('got remove result', res);
  5325. },
  5326. function (err) {
  5327. console.error('got remove error', err);
  5328. }
  5329. );
  5330. } else {
  5331. console.log('removal not necessary');
  5332. }
  5333. // send source-add IQ.
  5334. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  5335. var add = $iq({to: this.peerjid, type: 'set'})
  5336. .c('jingle', {
  5337. xmlns: 'urn:xmpp:jingle:1',
  5338. action: 'source-add',
  5339. initiator: this.initiator,
  5340. sid: this.sid
  5341. }
  5342. );
  5343. var added = sdpDiffer.toJingle(add);
  5344. // Let 'source-add' IQ through the hack and see if we're allowed to send
  5345. // it in the current form
  5346. if (added)
  5347. add = SSRCReplacement.processSourceAdd(add);
  5348. if (added && add) {
  5349. console.info("Sending source-add", add);
  5350. this.connection.sendIQ(add,
  5351. function (res) {
  5352. console.info('got add result', res);
  5353. },
  5354. function (err) {
  5355. console.error('got add error', err);
  5356. }
  5357. );
  5358. } else {
  5359. console.log('addition not necessary');
  5360. }
  5361. };
  5362. /**
  5363. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  5364. *
  5365. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  5366. * tracks; otherwise, <tt>false</tt>
  5367. * @param callback a function to be invoked with <tt>mute</tt> after all video
  5368. * tracks have been enabled/disabled. The function may, optionally, return
  5369. * another function which is to be invoked after the whole mute/unmute operation
  5370. * has completed successfully.
  5371. * @param options an object which specifies optional arguments such as the
  5372. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  5373. * specifies whether the method was initiated in response to a user command (in
  5374. * contrast to an automatic decision made by the application logic)
  5375. */
  5376. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  5377. var byUser;
  5378. if (options) {
  5379. byUser = options.byUser;
  5380. if (typeof byUser === 'undefined') {
  5381. byUser = true;
  5382. }
  5383. } else {
  5384. byUser = true;
  5385. }
  5386. // The user's command to mute the (local) video takes precedence over any
  5387. // automatic decision made by the application logic.
  5388. if (byUser) {
  5389. this.videoMuteByUser = mute;
  5390. } else if (this.videoMuteByUser) {
  5391. return;
  5392. }
  5393. this.hardMuteVideo(mute);
  5394. var self = this;
  5395. var oldSdp = null;
  5396. if(self.peerconnection) {
  5397. if(self.peerconnection.localDescription) {
  5398. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  5399. }
  5400. }
  5401. this.modifySourcesQueue.push(function() {
  5402. console.log('modify sources done');
  5403. callback(mute);
  5404. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  5405. console.log("SDPs", oldSdp, newSdp);
  5406. self.notifyMySSRCUpdate(oldSdp, newSdp);
  5407. });
  5408. };
  5409. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  5410. this.pendingop = muted ? 'mute' : 'unmute';
  5411. };
  5412. JingleSessionPC.prototype.sendMute = function (muted, content) {
  5413. var info = $iq({to: this.peerjid,
  5414. type: 'set'})
  5415. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5416. action: 'session-info',
  5417. initiator: this.initiator,
  5418. sid: this.sid });
  5419. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  5420. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  5421. if (content) {
  5422. info.attrs({'name': content});
  5423. }
  5424. this.connection.send(info);
  5425. };
  5426. JingleSessionPC.prototype.sendRinging = function () {
  5427. var info = $iq({to: this.peerjid,
  5428. type: 'set'})
  5429. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5430. action: 'session-info',
  5431. initiator: this.initiator,
  5432. sid: this.sid });
  5433. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  5434. this.connection.send(info);
  5435. };
  5436. JingleSessionPC.prototype.getStats = function (interval) {
  5437. var self = this;
  5438. var recv = {audio: 0, video: 0};
  5439. var lost = {audio: 0, video: 0};
  5440. var lastrecv = {audio: 0, video: 0};
  5441. var lastlost = {audio: 0, video: 0};
  5442. var loss = {audio: 0, video: 0};
  5443. var delta = {audio: 0, video: 0};
  5444. this.statsinterval = window.setInterval(function () {
  5445. if (self && self.peerconnection && self.peerconnection.getStats) {
  5446. self.peerconnection.getStats(function (stats) {
  5447. var results = stats.result();
  5448. // TODO: there are so much statistics you can get from this..
  5449. for (var i = 0; i < results.length; ++i) {
  5450. if (results[i].type == 'ssrc') {
  5451. var packetsrecv = results[i].stat('packetsReceived');
  5452. var packetslost = results[i].stat('packetsLost');
  5453. if (packetsrecv && packetslost) {
  5454. packetsrecv = parseInt(packetsrecv, 10);
  5455. packetslost = parseInt(packetslost, 10);
  5456. if (results[i].stat('googFrameRateReceived')) {
  5457. lastlost.video = lost.video;
  5458. lastrecv.video = recv.video;
  5459. recv.video = packetsrecv;
  5460. lost.video = packetslost;
  5461. } else {
  5462. lastlost.audio = lost.audio;
  5463. lastrecv.audio = recv.audio;
  5464. recv.audio = packetsrecv;
  5465. lost.audio = packetslost;
  5466. }
  5467. }
  5468. }
  5469. }
  5470. delta.audio = recv.audio - lastrecv.audio;
  5471. delta.video = recv.video - lastrecv.video;
  5472. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  5473. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  5474. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  5475. });
  5476. }
  5477. }, interval || 3000);
  5478. return this.statsinterval;
  5479. };
  5480. JingleSessionPC.onJingleError = function (session, error)
  5481. {
  5482. console.error("Jingle error", error);
  5483. }
  5484. JingleSessionPC.onJingleFatalError = function (session, error)
  5485. {
  5486. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5487. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  5488. }
  5489. JingleSessionPC.prototype.setLocalDescription = function () {
  5490. var self = this;
  5491. var newssrcs = [];
  5492. var session = transform.parse(this.peerconnection.localDescription.sdp);
  5493. session.media.forEach(function (media) {
  5494. if (media.ssrcs != null && media.ssrcs.length > 0) {
  5495. // TODO(gp) maybe exclude FID streams?
  5496. media.ssrcs.forEach(function (ssrc) {
  5497. if (ssrc.attribute !== 'cname') {
  5498. return;
  5499. }
  5500. newssrcs.push({
  5501. 'ssrc': ssrc.id,
  5502. 'type': media.type
  5503. });
  5504. });
  5505. }
  5506. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  5507. {
  5508. newssrcs.push({
  5509. 'ssrc': self.localStreamsSSRC[media.type],
  5510. 'type': media.type
  5511. });
  5512. }
  5513. });
  5514. console.log('new ssrcs', newssrcs);
  5515. // Bind us as local SSRCs owner
  5516. if (newssrcs.length > 0) {
  5517. for (var i = 1; i <= newssrcs.length; i ++) {
  5518. var ssrc = newssrcs[i-1].ssrc;
  5519. var myJid = self.connection.emuc.myroomjid;
  5520. self.ssrcOwners[ssrc] = myJid;
  5521. }
  5522. }
  5523. }
  5524. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  5525. JingleSessionPC.prototype.sendKeyframe = function () {
  5526. var pc = this.peerconnection;
  5527. console.log('sendkeyframe', pc.iceConnectionState);
  5528. if (pc.iceConnectionState !== 'connected') return; // safe...
  5529. var self = this;
  5530. pc.setRemoteDescription(
  5531. pc.remoteDescription,
  5532. function () {
  5533. pc.createAnswer(
  5534. function (modifiedAnswer) {
  5535. pc.setLocalDescription(
  5536. modifiedAnswer,
  5537. function () {
  5538. // noop
  5539. },
  5540. function (error) {
  5541. console.log('triggerKeyframe setLocalDescription failed', error);
  5542. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  5543. }
  5544. );
  5545. },
  5546. function (error) {
  5547. console.log('triggerKeyframe createAnswer failed', error);
  5548. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  5549. }
  5550. );
  5551. },
  5552. function (error) {
  5553. console.log('triggerKeyframe setRemoteDescription failed', error);
  5554. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  5555. }
  5556. );
  5557. }
  5558. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  5559. var self = this;
  5560. var thessrc;
  5561. var streamId = RTC.getStreamID(data.stream);
  5562. // look up an associated JID for a stream id
  5563. if (!streamId) {
  5564. console.error("No stream ID for", data.stream);
  5565. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  5566. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  5567. var ssrclines
  5568. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  5569. ssrclines = ssrclines.filter(function (line) {
  5570. // NOTE(gp) previously we filtered on the mslabel, but that property
  5571. // is not always present.
  5572. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  5573. if (RTCBrowserType.isTemasysPluginUsed()) {
  5574. return ((line.indexOf('mslabel:' + streamId) !== -1));
  5575. } else {
  5576. return ((line.indexOf('msid:' + streamId) !== -1));
  5577. }
  5578. });
  5579. if (ssrclines.length) {
  5580. thessrc = ssrclines[0].substring(7).split(' ')[0];
  5581. if (!self.ssrcOwners[thessrc]) {
  5582. console.error("No SSRC owner known for: " + thessrc);
  5583. return;
  5584. }
  5585. data.peerjid = self.ssrcOwners[thessrc];
  5586. console.log('associated jid', self.ssrcOwners[thessrc]);
  5587. } else {
  5588. console.error("No SSRC lines for ", streamId);
  5589. }
  5590. }
  5591. this.room.remoteStreamAdded(data, this.sid, thessrc);
  5592. var isVideo = data.stream.getVideoTracks().length > 0;
  5593. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  5594. if (isVideo &&
  5595. data.peerjid && this.peerjid === data.peerjid &&
  5596. data.stream.getVideoTracks().length === 0 &&
  5597. RTC.localVideo.getTracks().length > 0) {
  5598. window.setTimeout(function () {
  5599. self.sendKeyframe();
  5600. }, 3000);
  5601. }
  5602. }
  5603. module.exports = JingleSessionPC;
  5604. },{"../../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){
  5605. /* global $ */
  5606. /*
  5607. Here we do modifications of local video SSRCs. There are 2 situations we have
  5608. to handle:
  5609. 1. We generate SSRC for local recvonly video stream. This is the case when we
  5610. have no local camera and it is not generated automatically, but SSRC=1 is
  5611. used implicitly. If that happens RTCP packets will be dropped by the JVB
  5612. and we won't be able to request video key frames correctly.
  5613. 2. A hack to re-use SSRC of the first video stream for any new stream created
  5614. in future. It turned out that Chrome may keep on using the SSRC of removed
  5615. video stream in RTCP even though a new one has been created. So we just
  5616. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  5617. notifications are blocked once first video SSRC is advertised to the focus.
  5618. What this hack does:
  5619. 1. Stores the SSRC of the first video stream created by
  5620. a) scanning Jingle session-accept/session-invite for existing video SSRC
  5621. b) watching for 'source-add' for new video stream if it has not been
  5622. created in step a)
  5623. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  5624. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  5625. returned to the other parts of the application.
  5626. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  5627. blocks those notifications. This makes Jicofo and all participants think
  5628. that it exists all the time even if the video stream has been removed or
  5629. replaced locally. Thanks to that there is no additional signaling activity
  5630. on video mute or when switching to the desktop stream.
  5631. */
  5632. var SDP = require('./SDP');
  5633. var RTCBrowserType = require('../RTC/RTCBrowserType');
  5634. /**
  5635. * The hack is enabled on all browsers except FF by default
  5636. * FIXME finish the hack once removeStream method is implemented in FF
  5637. * @type {boolean}
  5638. */
  5639. var isEnabled = !RTCBrowserType.isFirefox();
  5640. /**
  5641. * Stored SSRC of local video stream.
  5642. */
  5643. var localVideoSSRC;
  5644. /**
  5645. * SSRC used for recvonly video stream when we have no local camera.
  5646. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  5647. * instead of 1.
  5648. */
  5649. var localRecvOnlySSRC, localRecvOnlyMSID, localRecvOnlyMSLabel, localRecvOnlyLabel;
  5650. /**
  5651. * cname for <tt>localRecvOnlySSRC</tt>
  5652. */
  5653. var localRecvOnlyCName;
  5654. /**
  5655. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  5656. * from given Jingle IQ.
  5657. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  5658. * @param actionName display name of the action which will be printed in log
  5659. * messages.
  5660. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  5661. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  5662. * other SSRCs left to be signaled after removing it.
  5663. */
  5664. var filterOutSource = function (modifyIq, actionName) {
  5665. var modifyIqTree = $(modifyIq.tree());
  5666. if (!localVideoSSRC)
  5667. return modifyIqTree[0];
  5668. var videoSSRC = modifyIqTree.find(
  5669. '>jingle>content[name="video"]' +
  5670. '>description>source[ssrc="' + localVideoSSRC + '"]');
  5671. if (!videoSSRC.length) {
  5672. return modifyIqTree[0];
  5673. }
  5674. console.info(
  5675. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  5676. videoSSRC.remove();
  5677. // Check if any sources still left to be added/removed
  5678. if (modifyIqTree.find('>jingle>content>description>source').length) {
  5679. return modifyIqTree[0];
  5680. } else {
  5681. return null;
  5682. }
  5683. };
  5684. /**
  5685. * Scans given Jingle IQ for video SSRC and stores it.
  5686. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  5687. */
  5688. var storeLocalVideoSSRC = function (jingleIq) {
  5689. var videoSSRCs =
  5690. $(jingleIq.tree())
  5691. .find('>jingle>content[name="video"]>description>source');
  5692. videoSSRCs.each(function (idx, ssrcElem) {
  5693. if (localVideoSSRC)
  5694. return;
  5695. // We consider SSRC real only if it has msid attribute
  5696. // recvonly streams in FF do not have it as well as local SSRCs
  5697. // we generate for recvonly streams in Chrome
  5698. var ssrSel = $(ssrcElem);
  5699. var msid = ssrSel.find('>parameter[name="msid"]');
  5700. if (msid.length) {
  5701. var ssrcVal = ssrSel.attr('ssrc');
  5702. if (ssrcVal) {
  5703. localVideoSSRC = ssrcVal;
  5704. console.info('Stored local video SSRC' +
  5705. ' for future re-use: ' + localVideoSSRC);
  5706. }
  5707. }
  5708. });
  5709. };
  5710. function rangeRandomHex(min, max)
  5711. {
  5712. return Math.floor(Math.random() * (max - min) + min).toString(16);
  5713. }
  5714. var random4digitsHex = rangeRandomHex.bind(null, 4096, 65535);
  5715. var random8digitsHex = rangeRandomHex.bind(null, 268435456, 4294967295);
  5716. var random12digitsHex = rangeRandomHex.bind(null, 17592186044416, 281474976710655);
  5717. function generateLabel() {
  5718. //4294967295 - ffffffff
  5719. //65535 - ffff
  5720. //281474976710655 - ffffffffffff
  5721. return random8digitsHex() + "-" + random4digitsHex() + "-" + random4digitsHex() + "-" + random4digitsHex() + "-" + random12digitsHex();
  5722. }
  5723. /**
  5724. * Generates new SSRC for local video recvonly stream.
  5725. * FIXME what about eventual SSRC collision ?
  5726. */
  5727. function generateRecvonlySSRC() {
  5728. //
  5729. localRecvOnlySSRC =
  5730. Math.random().toString(10).substring(2, 11);
  5731. localRecvOnlyCName =
  5732. Math.random().toString(36).substring(2);
  5733. localRecvOnlyMSLabel = generateLabel();
  5734. localRecvOnlyLabel = generateLabel();
  5735. localRecvOnlyMSID = localRecvOnlyMSLabel + " " + localRecvOnlyLabel;
  5736. console.info(
  5737. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  5738. ", cname: " + localRecvOnlyCName);
  5739. }
  5740. var LocalSSRCReplacement = {
  5741. /**
  5742. * Method must be called before 'session-initiate' or 'session-invite' is
  5743. * sent. Scans the IQ for local video SSRC and stores it if detected.
  5744. *
  5745. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  5746. * which will be scanned for local video SSRC.
  5747. */
  5748. processSessionInit: function (sessionInit) {
  5749. if (!isEnabled)
  5750. return;
  5751. if (localVideoSSRC) {
  5752. console.error("Local SSRC stored already: " + localVideoSSRC);
  5753. return;
  5754. }
  5755. storeLocalVideoSSRC(sessionInit);
  5756. },
  5757. /**
  5758. * If we have local video SSRC stored searched given
  5759. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  5760. * with the stored one.
  5761. * @param localDescription local description object that will have local
  5762. * video SSRC replaced with the stored one
  5763. * @returns modified <tt>localDescription</tt> object.
  5764. */
  5765. mungeLocalVideoSSRC: function (localDescription) {
  5766. if (!isEnabled)
  5767. return localDescription;
  5768. if (!localDescription) {
  5769. console.warn("localDescription is null or undefined");
  5770. return localDescription;
  5771. }
  5772. // IF we have local video SSRC stored make sure it is replaced
  5773. // with old SSRC
  5774. if (localVideoSSRC) {
  5775. var newSdp = new SDP(localDescription.sdp);
  5776. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  5777. !newSdp.containsSSRC(localVideoSSRC)) {
  5778. // Get new video SSRC
  5779. var map = newSdp.getMediaSsrcMap();
  5780. var videoPart = map[1];
  5781. var videoSSRCs = videoPart.ssrcs;
  5782. var newSSRC = Object.keys(videoSSRCs)[0];
  5783. console.info(
  5784. "Replacing new video SSRC: " + newSSRC +
  5785. " with " + localVideoSSRC);
  5786. localDescription.sdp =
  5787. newSdp.raw.replace(
  5788. new RegExp('a=ssrc:' + newSSRC, 'g'),
  5789. 'a=ssrc:' + localVideoSSRC);
  5790. }
  5791. } else {
  5792. // Make sure we have any SSRC for recvonly video stream
  5793. var sdp = new SDP(localDescription.sdp);
  5794. if (sdp.media[1] && sdp.media[1].indexOf('a=ssrc:') === -1 &&
  5795. sdp.media[1].indexOf('a=recvonly') !== -1) {
  5796. if (!localRecvOnlySSRC) {
  5797. generateRecvonlySSRC();
  5798. }
  5799. localVideoSSRC = localRecvOnlySSRC;
  5800. console.info('No SSRC in video recvonly stream' +
  5801. ' - adding SSRC: ' + localRecvOnlySSRC);
  5802. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  5803. ' cname:' + localRecvOnlyCName + '\r\n' +
  5804. 'a=ssrc:' + localRecvOnlySSRC +
  5805. ' msid:' + localRecvOnlyMSID + '\r\n' +
  5806. 'a=ssrc:' + localRecvOnlySSRC +
  5807. ' mslabel:' + localRecvOnlyMSLabel + '\r\n' +
  5808. 'a=ssrc:' + localRecvOnlySSRC +
  5809. ' label:' + localRecvOnlyLabel + '\r\n';
  5810. localDescription.sdp = sdp.session + sdp.media.join('');
  5811. }
  5812. }
  5813. return localDescription;
  5814. },
  5815. /**
  5816. * Method must be called before 'source-add' notification is sent. In case
  5817. * we have local video SSRC advertised already it will be removed from the
  5818. * notification. If no other SSRCs are described by given IQ null will be
  5819. * returned which means that there is no point in sending the notification.
  5820. * @param sourceAdd 'source-add' Jingle IQ to be processed
  5821. * @returns modified 'source-add' IQ which can be sent to the focus or
  5822. * <tt>null</tt> if no notification shall be sent. It is no longer
  5823. * a Strophe IQ Builder instance, but DOM element tree.
  5824. */
  5825. processSourceAdd: function (sourceAdd) {
  5826. if (!isEnabled)
  5827. return sourceAdd;
  5828. if (!localVideoSSRC) {
  5829. // Store local SSRC if available
  5830. storeLocalVideoSSRC(sourceAdd);
  5831. return sourceAdd;
  5832. } else {
  5833. return filterOutSource(sourceAdd, 'source-add');
  5834. }
  5835. },
  5836. /**
  5837. * Method must be called before 'source-remove' notification is sent.
  5838. * Removes local video SSRC from the notification. If there are no other
  5839. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  5840. * means that there is no point in sending the notification.
  5841. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  5842. * @returns modified 'source-remove' IQ which can be sent to the focus or
  5843. * <tt>null</tt> if no notification shall be sent. It is no longer
  5844. * a Strophe IQ Builder instance, but DOM element tree.
  5845. */
  5846. processSourceRemove: function (sourceRemove) {
  5847. if (!isEnabled)
  5848. return sourceRemove;
  5849. return filterOutSource(sourceRemove, 'source-remove');
  5850. },
  5851. /**
  5852. * Turns the hack on or off
  5853. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  5854. * to disable it
  5855. */
  5856. setEnabled: function (enabled) {
  5857. isEnabled = enabled;
  5858. }
  5859. };
  5860. module.exports = LocalSSRCReplacement;
  5861. },{"../RTC/RTCBrowserType":14,"./SDP":23}],23:[function(require,module,exports){
  5862. /* jshint -W117 */
  5863. var SDPUtil = require("./SDPUtil");
  5864. // SDP STUFF
  5865. function SDP(sdp) {
  5866. this.media = sdp.split('\r\nm=');
  5867. for (var i = 1; i < this.media.length; i++) {
  5868. this.media[i] = 'm=' + this.media[i];
  5869. if (i != this.media.length - 1) {
  5870. this.media[i] += '\r\n';
  5871. }
  5872. }
  5873. this.session = this.media.shift() + '\r\n';
  5874. this.raw = this.session + this.media.join('');
  5875. }
  5876. /**
  5877. * Returns map of MediaChannel mapped per channel idx.
  5878. */
  5879. SDP.prototype.getMediaSsrcMap = function() {
  5880. var self = this;
  5881. var media_ssrcs = {};
  5882. var tmp;
  5883. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  5884. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  5885. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  5886. var media = {
  5887. mediaindex: mediaindex,
  5888. mid: mid,
  5889. ssrcs: {},
  5890. ssrcGroups: []
  5891. };
  5892. media_ssrcs[mediaindex] = media;
  5893. tmp.forEach(function (line) {
  5894. var linessrc = line.substring(7).split(' ')[0];
  5895. // allocate new ChannelSsrc
  5896. if(!media.ssrcs[linessrc]) {
  5897. media.ssrcs[linessrc] = {
  5898. ssrc: linessrc,
  5899. lines: []
  5900. };
  5901. }
  5902. media.ssrcs[linessrc].lines.push(line);
  5903. });
  5904. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  5905. tmp.forEach(function(line){
  5906. var semantics = line.substr(0, idx).substr(13);
  5907. var ssrcs = line.substr(14 + semantics.length).split(' ');
  5908. if (ssrcs.length != 0) {
  5909. media.ssrcGroups.push({
  5910. semantics: semantics,
  5911. ssrcs: ssrcs
  5912. });
  5913. }
  5914. });
  5915. }
  5916. return media_ssrcs;
  5917. };
  5918. /**
  5919. * Returns <tt>true</tt> if this SDP contains given SSRC.
  5920. * @param ssrc the ssrc to check.
  5921. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  5922. */
  5923. SDP.prototype.containsSSRC = function(ssrc) {
  5924. var medias = this.getMediaSsrcMap();
  5925. var contains = false;
  5926. Object.keys(medias).forEach(function(mediaindex){
  5927. var media = medias[mediaindex];
  5928. //console.log("Check", channel, ssrc);
  5929. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  5930. contains = true;
  5931. }
  5932. });
  5933. return contains;
  5934. };
  5935. // remove iSAC and CN from SDP
  5936. SDP.prototype.mangle = function () {
  5937. var i, j, mline, lines, rtpmap, newdesc;
  5938. for (i = 0; i < this.media.length; i++) {
  5939. lines = this.media[i].split('\r\n');
  5940. lines.pop(); // remove empty last element
  5941. mline = SDPUtil.parse_mline(lines.shift());
  5942. if (mline.media != 'audio')
  5943. continue;
  5944. newdesc = '';
  5945. mline.fmt.length = 0;
  5946. for (j = 0; j < lines.length; j++) {
  5947. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  5948. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  5949. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  5950. continue;
  5951. mline.fmt.push(rtpmap.id);
  5952. newdesc += lines[j] + '\r\n';
  5953. } else {
  5954. newdesc += lines[j] + '\r\n';
  5955. }
  5956. }
  5957. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  5958. this.media[i] += newdesc;
  5959. }
  5960. this.raw = this.session + this.media.join('');
  5961. };
  5962. // remove lines matching prefix from session section
  5963. SDP.prototype.removeSessionLines = function(prefix) {
  5964. var self = this;
  5965. var lines = SDPUtil.find_lines(this.session, prefix);
  5966. lines.forEach(function(line) {
  5967. self.session = self.session.replace(line + '\r\n', '');
  5968. });
  5969. this.raw = this.session + this.media.join('');
  5970. return lines;
  5971. }
  5972. // remove lines matching prefix from a media section specified by mediaindex
  5973. // TODO: non-numeric mediaindex could match mid
  5974. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  5975. var self = this;
  5976. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  5977. lines.forEach(function(line) {
  5978. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  5979. });
  5980. this.raw = this.session + this.media.join('');
  5981. return lines;
  5982. }
  5983. // add content's to a jingle element
  5984. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  5985. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  5986. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  5987. var self = this;
  5988. // new bundle plan
  5989. if (SDPUtil.find_line(this.session, 'a=group:')) {
  5990. lines = SDPUtil.find_lines(this.session, 'a=group:');
  5991. for (i = 0; i < lines.length; i++) {
  5992. tmp = lines[i].split(' ');
  5993. var semantics = tmp.shift().substr(8);
  5994. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  5995. for (j = 0; j < tmp.length; j++) {
  5996. elem.c('content', {name: tmp[j]}).up();
  5997. }
  5998. elem.up();
  5999. }
  6000. }
  6001. for (i = 0; i < this.media.length; i++) {
  6002. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  6003. if (!(mline.media === 'audio' ||
  6004. mline.media === 'video' ||
  6005. mline.media === 'application'))
  6006. {
  6007. continue;
  6008. }
  6009. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  6010. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  6011. } else {
  6012. if(ssrcs && ssrcs[mline.media])
  6013. {
  6014. ssrc = ssrcs[mline.media];
  6015. }
  6016. else
  6017. ssrc = false;
  6018. }
  6019. elem.c('content', {creator: thecreator, name: mline.media});
  6020. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  6021. // prefer identifier from a=mid if present
  6022. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  6023. elem.attrs({ name: mid });
  6024. }
  6025. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  6026. {
  6027. elem.c('description',
  6028. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  6029. media: mline.media });
  6030. if (ssrc) {
  6031. elem.attrs({ssrc: ssrc});
  6032. }
  6033. for (j = 0; j < mline.fmt.length; j++) {
  6034. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  6035. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  6036. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  6037. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  6038. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  6039. for (k = 0; k < tmp.length; k++) {
  6040. elem.c('parameter', tmp[k]).up();
  6041. }
  6042. }
  6043. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  6044. elem.up();
  6045. }
  6046. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  6047. elem.c('encryption', {required: 1});
  6048. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  6049. crypto.forEach(function(line) {
  6050. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  6051. });
  6052. elem.up(); // end of encryption
  6053. }
  6054. if (ssrc) {
  6055. // new style mapping
  6056. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  6057. // FIXME: group by ssrc and support multiple different ssrcs
  6058. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  6059. if(ssrclines.length > 0) {
  6060. ssrclines.forEach(function (line) {
  6061. idx = line.indexOf(' ');
  6062. var linessrc = line.substr(0, idx).substr(7);
  6063. if (linessrc != ssrc) {
  6064. elem.up();
  6065. ssrc = linessrc;
  6066. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  6067. }
  6068. var kv = line.substr(idx + 1);
  6069. elem.c('parameter');
  6070. if (kv.indexOf(':') == -1) {
  6071. elem.attrs({ name: kv });
  6072. } else {
  6073. var k = kv.split(':', 2)[0];
  6074. elem.attrs({ name: k });
  6075. var v = kv.split(':', 2)[1];
  6076. v = SDPUtil.filter_special_chars(v);
  6077. elem.attrs({ value: v });
  6078. }
  6079. elem.up();
  6080. });
  6081. }
  6082. else
  6083. {
  6084. elem.up();
  6085. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  6086. elem.c('parameter');
  6087. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  6088. elem.up();
  6089. var msid = null;
  6090. if(mline.media == "audio")
  6091. {
  6092. msid = APP.RTC.localAudio.getId();
  6093. }
  6094. else
  6095. {
  6096. msid = APP.RTC.localVideo.getId();
  6097. }
  6098. if(msid != null)
  6099. {
  6100. msid = SDPUtil.filter_special_chars(msid);
  6101. elem.c('parameter');
  6102. elem.attrs({name: "msid", value:msid});
  6103. elem.up();
  6104. elem.c('parameter');
  6105. elem.attrs({name: "mslabel", value:msid});
  6106. elem.up();
  6107. elem.c('parameter');
  6108. elem.attrs({name: "label", value:msid});
  6109. elem.up();
  6110. }
  6111. }
  6112. elem.up();
  6113. // XEP-0339 handle ssrc-group attributes
  6114. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  6115. ssrc_group_lines.forEach(function(line) {
  6116. idx = line.indexOf(' ');
  6117. var semantics = line.substr(0, idx).substr(13);
  6118. var ssrcs = line.substr(14 + semantics.length).split(' ');
  6119. if (ssrcs.length != 0) {
  6120. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  6121. ssrcs.forEach(function(ssrc) {
  6122. elem.c('source', { ssrc: ssrc })
  6123. .up();
  6124. });
  6125. elem.up();
  6126. }
  6127. });
  6128. }
  6129. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  6130. elem.c('rtcp-mux').up();
  6131. }
  6132. // XEP-0293 -- map a=rtcp-fb:*
  6133. this.RtcpFbToJingle(i, elem, '*');
  6134. // XEP-0294
  6135. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  6136. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  6137. for (j = 0; j < lines.length; j++) {
  6138. tmp = SDPUtil.parse_extmap(lines[j]);
  6139. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  6140. uri: tmp.uri,
  6141. id: tmp.value });
  6142. if (tmp.hasOwnProperty('direction')) {
  6143. switch (tmp.direction) {
  6144. case 'sendonly':
  6145. elem.attrs({senders: 'responder'});
  6146. break;
  6147. case 'recvonly':
  6148. elem.attrs({senders: 'initiator'});
  6149. break;
  6150. case 'sendrecv':
  6151. elem.attrs({senders: 'both'});
  6152. break;
  6153. case 'inactive':
  6154. elem.attrs({senders: 'none'});
  6155. break;
  6156. }
  6157. }
  6158. // TODO: handle params
  6159. elem.up();
  6160. }
  6161. }
  6162. elem.up(); // end of description
  6163. }
  6164. // map ice-ufrag/pwd, dtls fingerprint, candidates
  6165. this.TransportToJingle(i, elem);
  6166. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  6167. elem.attrs({senders: 'both'});
  6168. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  6169. elem.attrs({senders: 'initiator'});
  6170. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  6171. elem.attrs({senders: 'responder'});
  6172. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  6173. elem.attrs({senders: 'none'});
  6174. }
  6175. if (mline.port == '0') {
  6176. // estos hack to reject an m-line
  6177. elem.attrs({senders: 'rejected'});
  6178. }
  6179. elem.up(); // end of content
  6180. }
  6181. elem.up();
  6182. return elem;
  6183. };
  6184. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  6185. var i = mediaindex;
  6186. var tmp;
  6187. var self = this;
  6188. elem.c('transport');
  6189. // XEP-0343 DTLS/SCTP
  6190. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  6191. {
  6192. var sctpmap = SDPUtil.find_line(
  6193. this.media[i], 'a=sctpmap:', self.session);
  6194. if (sctpmap)
  6195. {
  6196. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  6197. elem.c('sctpmap',
  6198. {
  6199. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  6200. number: sctpAttrs[0], /* SCTP port */
  6201. protocol: sctpAttrs[1], /* protocol */
  6202. });
  6203. // Optional stream count attribute
  6204. if (sctpAttrs.length > 2)
  6205. elem.attrs({ streams: sctpAttrs[2]});
  6206. elem.up();
  6207. }
  6208. }
  6209. // XEP-0320
  6210. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  6211. fingerprints.forEach(function(line) {
  6212. tmp = SDPUtil.parse_fingerprint(line);
  6213. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  6214. elem.c('fingerprint').t(tmp.fingerprint);
  6215. delete tmp.fingerprint;
  6216. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  6217. if (line) {
  6218. tmp.setup = line.substr(8);
  6219. }
  6220. elem.attrs(tmp);
  6221. elem.up(); // end of fingerprint
  6222. });
  6223. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  6224. if (tmp) {
  6225. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6226. elem.attrs(tmp);
  6227. // XEP-0176
  6228. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  6229. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  6230. lines.forEach(function (line) {
  6231. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  6232. });
  6233. }
  6234. }
  6235. elem.up(); // end of transport
  6236. }
  6237. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  6238. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  6239. lines.forEach(function (line) {
  6240. var tmp = SDPUtil.parse_rtcpfb(line);
  6241. if (tmp.type == 'trr-int') {
  6242. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  6243. elem.up();
  6244. } else {
  6245. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  6246. if (tmp.params.length > 0) {
  6247. elem.attrs({'subtype': tmp.params[0]});
  6248. }
  6249. elem.up();
  6250. }
  6251. });
  6252. };
  6253. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  6254. var media = '';
  6255. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  6256. if (tmp.length) {
  6257. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  6258. if (tmp.attr('value')) {
  6259. media += tmp.attr('value');
  6260. } else {
  6261. media += '0';
  6262. }
  6263. media += '\r\n';
  6264. }
  6265. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  6266. tmp.each(function () {
  6267. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  6268. if ($(this).attr('subtype')) {
  6269. media += ' ' + $(this).attr('subtype');
  6270. }
  6271. media += '\r\n';
  6272. });
  6273. return media;
  6274. };
  6275. // construct an SDP from a jingle stanza
  6276. SDP.prototype.fromJingle = function (jingle) {
  6277. var self = this;
  6278. this.raw = 'v=0\r\n' +
  6279. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  6280. 's=-\r\n' +
  6281. 't=0 0\r\n';
  6282. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  6283. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  6284. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  6285. var contents = $(group).find('>content').map(function (idx, content) {
  6286. return content.getAttribute('name');
  6287. }).get();
  6288. if (contents.length > 0) {
  6289. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  6290. }
  6291. });
  6292. }
  6293. this.session = this.raw;
  6294. jingle.find('>content').each(function () {
  6295. var m = self.jingle2media($(this));
  6296. self.media.push(m);
  6297. });
  6298. // reconstruct msid-semantic -- apparently not necessary
  6299. /*
  6300. var msid = SDPUtil.parse_ssrc(this.raw);
  6301. if (msid.hasOwnProperty('mslabel')) {
  6302. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  6303. }
  6304. */
  6305. this.raw = this.session + this.media.join('');
  6306. };
  6307. // translate a jingle content element into an an SDP media part
  6308. SDP.prototype.jingle2media = function (content) {
  6309. var media = '',
  6310. desc = content.find('description'),
  6311. ssrc = desc.attr('ssrc'),
  6312. self = this,
  6313. tmp;
  6314. var sctp = content.find(
  6315. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  6316. tmp = { media: desc.attr('media') };
  6317. tmp.port = '1';
  6318. if (content.attr('senders') == 'rejected') {
  6319. // estos hack to reject an m-line.
  6320. tmp.port = '0';
  6321. }
  6322. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  6323. if (sctp.length)
  6324. tmp.proto = 'DTLS/SCTP';
  6325. else
  6326. tmp.proto = 'RTP/SAVPF';
  6327. } else {
  6328. tmp.proto = 'RTP/AVPF';
  6329. }
  6330. if (!sctp.length)
  6331. {
  6332. tmp.fmt = desc.find('payload-type').map(
  6333. function () { return this.getAttribute('id'); }).get();
  6334. media += SDPUtil.build_mline(tmp) + '\r\n';
  6335. }
  6336. else
  6337. {
  6338. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  6339. media += 'a=sctpmap:' + sctp.attr('number') +
  6340. ' ' + sctp.attr('protocol');
  6341. var streamCount = sctp.attr('streams');
  6342. if (streamCount)
  6343. media += ' ' + streamCount + '\r\n';
  6344. else
  6345. media += '\r\n';
  6346. }
  6347. media += 'c=IN IP4 0.0.0.0\r\n';
  6348. if (!sctp.length)
  6349. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  6350. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  6351. if (tmp.length) {
  6352. if (tmp.attr('ufrag')) {
  6353. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  6354. }
  6355. if (tmp.attr('pwd')) {
  6356. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  6357. }
  6358. tmp.find('>fingerprint').each(function () {
  6359. // FIXME: check namespace at some point
  6360. media += 'a=fingerprint:' + this.getAttribute('hash');
  6361. media += ' ' + $(this).text();
  6362. media += '\r\n';
  6363. if (this.getAttribute('setup')) {
  6364. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  6365. }
  6366. });
  6367. }
  6368. switch (content.attr('senders')) {
  6369. case 'initiator':
  6370. media += 'a=sendonly\r\n';
  6371. break;
  6372. case 'responder':
  6373. media += 'a=recvonly\r\n';
  6374. break;
  6375. case 'none':
  6376. media += 'a=inactive\r\n';
  6377. break;
  6378. case 'both':
  6379. media += 'a=sendrecv\r\n';
  6380. break;
  6381. }
  6382. media += 'a=mid:' + content.attr('name') + '\r\n';
  6383. // <description><rtcp-mux/></description>
  6384. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  6385. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  6386. if (desc.find('rtcp-mux').length) {
  6387. media += 'a=rtcp-mux\r\n';
  6388. }
  6389. if (desc.find('encryption').length) {
  6390. desc.find('encryption>crypto').each(function () {
  6391. media += 'a=crypto:' + this.getAttribute('tag');
  6392. media += ' ' + this.getAttribute('crypto-suite');
  6393. media += ' ' + this.getAttribute('key-params');
  6394. if (this.getAttribute('session-params')) {
  6395. media += ' ' + this.getAttribute('session-params');
  6396. }
  6397. media += '\r\n';
  6398. });
  6399. }
  6400. desc.find('payload-type').each(function () {
  6401. media += SDPUtil.build_rtpmap(this) + '\r\n';
  6402. if ($(this).find('>parameter').length) {
  6403. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  6404. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  6405. media += '\r\n';
  6406. }
  6407. // xep-0293
  6408. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  6409. });
  6410. // xep-0293
  6411. media += self.RtcpFbFromJingle(desc, '*');
  6412. // xep-0294
  6413. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  6414. tmp.each(function () {
  6415. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  6416. });
  6417. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  6418. media += SDPUtil.candidateFromJingle(this);
  6419. });
  6420. // XEP-0339 handle ssrc-group attributes
  6421. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6422. var semantics = this.getAttribute('semantics');
  6423. var ssrcs = $(this).find('>source').map(function() {
  6424. return this.getAttribute('ssrc');
  6425. }).get();
  6426. if (ssrcs.length != 0) {
  6427. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6428. }
  6429. });
  6430. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  6431. tmp.each(function () {
  6432. var ssrc = this.getAttribute('ssrc');
  6433. $(this).find('>parameter').each(function () {
  6434. var name = this.getAttribute('name');
  6435. var value = this.getAttribute('value');
  6436. value = SDPUtil.filter_special_chars(value);
  6437. media += 'a=ssrc:' + ssrc + ' ' + name;
  6438. if (value && value.length)
  6439. media += ':' + value;
  6440. media += '\r\n';
  6441. });
  6442. });
  6443. return media;
  6444. };
  6445. module.exports = SDP;
  6446. },{"./SDPUtil":25}],24:[function(require,module,exports){
  6447. var SDPUtil = require("./SDPUtil");
  6448. function SDPDiffer(mySDP, otherSDP) {
  6449. this.mySDP = mySDP;
  6450. this.otherSDP = otherSDP;
  6451. }
  6452. /**
  6453. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  6454. * @param otherSdp the other SDP to check ssrc with.
  6455. */
  6456. SDPDiffer.prototype.getNewMedia = function() {
  6457. // this could be useful in Array.prototype.
  6458. function arrayEquals(array) {
  6459. // if the other array is a falsy value, return
  6460. if (!array)
  6461. return false;
  6462. // compare lengths - can save a lot of time
  6463. if (this.length != array.length)
  6464. return false;
  6465. for (var i = 0, l=this.length; i < l; i++) {
  6466. // Check if we have nested arrays
  6467. if (this[i] instanceof Array && array[i] instanceof Array) {
  6468. // recurse into the nested arrays
  6469. if (!this[i].equals(array[i]))
  6470. return false;
  6471. }
  6472. else if (this[i] != array[i]) {
  6473. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  6474. return false;
  6475. }
  6476. }
  6477. return true;
  6478. }
  6479. var myMedias = this.mySDP.getMediaSsrcMap();
  6480. var othersMedias = this.otherSDP.getMediaSsrcMap();
  6481. var newMedia = {};
  6482. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  6483. var myMedia = myMedias[othersMediaIdx];
  6484. var othersMedia = othersMedias[othersMediaIdx];
  6485. if(!myMedia && othersMedia) {
  6486. // Add whole channel
  6487. newMedia[othersMediaIdx] = othersMedia;
  6488. return;
  6489. }
  6490. // Look for new ssrcs accross the channel
  6491. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  6492. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  6493. // Allocate channel if we've found ssrc that doesn't exist in our channel
  6494. if(!newMedia[othersMediaIdx]){
  6495. newMedia[othersMediaIdx] = {
  6496. mediaindex: othersMedia.mediaindex,
  6497. mid: othersMedia.mid,
  6498. ssrcs: {},
  6499. ssrcGroups: []
  6500. };
  6501. }
  6502. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  6503. }
  6504. });
  6505. // Look for new ssrc groups across the channels
  6506. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  6507. // try to match the other ssrc-group with an ssrc-group of ours
  6508. var matched = false;
  6509. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  6510. var mySsrcGroup = myMedia.ssrcGroups[i];
  6511. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  6512. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  6513. matched = true;
  6514. break;
  6515. }
  6516. }
  6517. if (!matched) {
  6518. // Allocate channel if we've found an ssrc-group that doesn't
  6519. // exist in our channel
  6520. if(!newMedia[othersMediaIdx]){
  6521. newMedia[othersMediaIdx] = {
  6522. mediaindex: othersMedia.mediaindex,
  6523. mid: othersMedia.mid,
  6524. ssrcs: {},
  6525. ssrcGroups: []
  6526. };
  6527. }
  6528. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  6529. }
  6530. });
  6531. });
  6532. return newMedia;
  6533. };
  6534. /**
  6535. * Sends SSRC update IQ.
  6536. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  6537. * @param sid session identifier that will be put into the IQ.
  6538. * @param initiator initiator identifier.
  6539. * @param toJid destination Jid
  6540. * @param isAdd indicates if this is remove or add operation.
  6541. */
  6542. SDPDiffer.prototype.toJingle = function(modify) {
  6543. var sdpMediaSsrcs = this.getNewMedia();
  6544. var self = this;
  6545. // FIXME: only announce video ssrcs since we mix audio and dont need
  6546. // the audio ssrcs therefore
  6547. var modified = false;
  6548. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  6549. modified = true;
  6550. var media = sdpMediaSsrcs[mediaindex];
  6551. modify.c('content', {name: media.mid});
  6552. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  6553. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  6554. // generate sources from lines
  6555. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  6556. var mediaSsrc = media.ssrcs[ssrcNum];
  6557. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  6558. modify.attrs({ssrc: mediaSsrc.ssrc});
  6559. // iterate over ssrc lines
  6560. mediaSsrc.lines.forEach(function (line) {
  6561. var idx = line.indexOf(' ');
  6562. var kv = line.substr(idx + 1);
  6563. modify.c('parameter');
  6564. if (kv.indexOf(':') == -1) {
  6565. modify.attrs({ name: kv });
  6566. } else {
  6567. var nv = kv.split(':', 2);
  6568. var name = nv[0];
  6569. var value = SDPUtil.filter_special_chars(nv[1]);
  6570. modify.attrs({ name: name });
  6571. modify.attrs({ value: value });
  6572. }
  6573. modify.up(); // end of parameter
  6574. });
  6575. modify.up(); // end of source
  6576. });
  6577. // generate source groups from lines
  6578. media.ssrcGroups.forEach(function(ssrcGroup) {
  6579. if (ssrcGroup.ssrcs.length != 0) {
  6580. modify.c('ssrc-group', {
  6581. semantics: ssrcGroup.semantics,
  6582. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  6583. });
  6584. ssrcGroup.ssrcs.forEach(function (ssrc) {
  6585. modify.c('source', { ssrc: ssrc })
  6586. .up(); // end of source
  6587. });
  6588. modify.up(); // end of ssrc-group
  6589. }
  6590. });
  6591. modify.up(); // end of description
  6592. modify.up(); // end of content
  6593. });
  6594. return modified;
  6595. };
  6596. module.exports = SDPDiffer;
  6597. },{"./SDPUtil":25}],25:[function(require,module,exports){
  6598. SDPUtil = {
  6599. filter_special_chars: function (text) {
  6600. return text.replace(/[\\\/\{,\}\+]/g, "");
  6601. },
  6602. iceparams: function (mediadesc, sessiondesc) {
  6603. var data = null;
  6604. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  6605. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  6606. data = {
  6607. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  6608. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  6609. };
  6610. }
  6611. return data;
  6612. },
  6613. parse_iceufrag: function (line) {
  6614. return line.substring(12);
  6615. },
  6616. build_iceufrag: function (frag) {
  6617. return 'a=ice-ufrag:' + frag;
  6618. },
  6619. parse_icepwd: function (line) {
  6620. return line.substring(10);
  6621. },
  6622. build_icepwd: function (pwd) {
  6623. return 'a=ice-pwd:' + pwd;
  6624. },
  6625. parse_mid: function (line) {
  6626. return line.substring(6);
  6627. },
  6628. parse_mline: function (line) {
  6629. var parts = line.substring(2).split(' '),
  6630. data = {};
  6631. data.media = parts.shift();
  6632. data.port = parts.shift();
  6633. data.proto = parts.shift();
  6634. if (parts[parts.length - 1] === '') { // trailing whitespace
  6635. parts.pop();
  6636. }
  6637. data.fmt = parts;
  6638. return data;
  6639. },
  6640. build_mline: function (mline) {
  6641. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  6642. },
  6643. parse_rtpmap: function (line) {
  6644. var parts = line.substring(9).split(' '),
  6645. data = {};
  6646. data.id = parts.shift();
  6647. parts = parts[0].split('/');
  6648. data.name = parts.shift();
  6649. data.clockrate = parts.shift();
  6650. data.channels = parts.length ? parts.shift() : '1';
  6651. return data;
  6652. },
  6653. /**
  6654. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  6655. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  6656. * @returns [SCTP port number, protocol, streams]
  6657. */
  6658. parse_sctpmap: function (line)
  6659. {
  6660. var parts = line.substring(10).split(' ');
  6661. var sctpPort = parts[0];
  6662. var protocol = parts[1];
  6663. // Stream count is optional
  6664. var streamCount = parts.length > 2 ? parts[2] : null;
  6665. return [sctpPort, protocol, streamCount];// SCTP port
  6666. },
  6667. build_rtpmap: function (el) {
  6668. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  6669. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  6670. line += '/' + el.getAttribute('channels');
  6671. }
  6672. return line;
  6673. },
  6674. parse_crypto: function (line) {
  6675. var parts = line.substring(9).split(' '),
  6676. data = {};
  6677. data.tag = parts.shift();
  6678. data['crypto-suite'] = parts.shift();
  6679. data['key-params'] = parts.shift();
  6680. if (parts.length) {
  6681. data['session-params'] = parts.join(' ');
  6682. }
  6683. return data;
  6684. },
  6685. parse_fingerprint: function (line) { // RFC 4572
  6686. var parts = line.substring(14).split(' '),
  6687. data = {};
  6688. data.hash = parts.shift();
  6689. data.fingerprint = parts.shift();
  6690. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  6691. return data;
  6692. },
  6693. parse_fmtp: function (line) {
  6694. var parts = line.split(' '),
  6695. i, key, value,
  6696. data = [];
  6697. parts.shift();
  6698. parts = parts.join(' ').split(';');
  6699. for (i = 0; i < parts.length; i++) {
  6700. key = parts[i].split('=')[0];
  6701. while (key.length && key[0] == ' ') {
  6702. key = key.substring(1);
  6703. }
  6704. value = parts[i].split('=')[1];
  6705. if (key && value) {
  6706. data.push({name: key, value: value});
  6707. } else if (key) {
  6708. // rfc 4733 (DTMF) style stuff
  6709. data.push({name: '', value: key});
  6710. }
  6711. }
  6712. return data;
  6713. },
  6714. parse_icecandidate: function (line) {
  6715. var candidate = {},
  6716. elems = line.split(' ');
  6717. candidate.foundation = elems[0].substring(12);
  6718. candidate.component = elems[1];
  6719. candidate.protocol = elems[2].toLowerCase();
  6720. candidate.priority = elems[3];
  6721. candidate.ip = elems[4];
  6722. candidate.port = elems[5];
  6723. // elems[6] => "typ"
  6724. candidate.type = elems[7];
  6725. candidate.generation = 0; // default value, may be overwritten below
  6726. for (var i = 8; i < elems.length; i += 2) {
  6727. switch (elems[i]) {
  6728. case 'raddr':
  6729. candidate['rel-addr'] = elems[i + 1];
  6730. break;
  6731. case 'rport':
  6732. candidate['rel-port'] = elems[i + 1];
  6733. break;
  6734. case 'generation':
  6735. candidate.generation = elems[i + 1];
  6736. break;
  6737. case 'tcptype':
  6738. candidate.tcptype = elems[i + 1];
  6739. break;
  6740. default: // TODO
  6741. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  6742. }
  6743. }
  6744. candidate.network = '1';
  6745. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  6746. return candidate;
  6747. },
  6748. build_icecandidate: function (cand) {
  6749. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  6750. line += ' ';
  6751. switch (cand.type) {
  6752. case 'srflx':
  6753. case 'prflx':
  6754. case 'relay':
  6755. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  6756. line += 'raddr';
  6757. line += ' ';
  6758. line += cand['rel-addr'];
  6759. line += ' ';
  6760. line += 'rport';
  6761. line += ' ';
  6762. line += cand['rel-port'];
  6763. line += ' ';
  6764. }
  6765. break;
  6766. }
  6767. if (cand.hasOwnAttribute('tcptype')) {
  6768. line += 'tcptype';
  6769. line += ' ';
  6770. line += cand.tcptype;
  6771. line += ' ';
  6772. }
  6773. line += 'generation';
  6774. line += ' ';
  6775. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  6776. return line;
  6777. },
  6778. parse_ssrc: function (desc) {
  6779. // proprietary mapping of a=ssrc lines
  6780. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  6781. // and parse according to that
  6782. var lines = desc.split('\r\n'),
  6783. data = {};
  6784. for (var i = 0; i < lines.length; i++) {
  6785. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  6786. var idx = lines[i].indexOf(' ');
  6787. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  6788. }
  6789. }
  6790. return data;
  6791. },
  6792. parse_rtcpfb: function (line) {
  6793. var parts = line.substr(10).split(' ');
  6794. var data = {};
  6795. data.pt = parts.shift();
  6796. data.type = parts.shift();
  6797. data.params = parts;
  6798. return data;
  6799. },
  6800. parse_extmap: function (line) {
  6801. var parts = line.substr(9).split(' ');
  6802. var data = {};
  6803. data.value = parts.shift();
  6804. if (data.value.indexOf('/') != -1) {
  6805. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  6806. data.value = data.value.substr(0, data.value.indexOf('/'));
  6807. } else {
  6808. data.direction = 'both';
  6809. }
  6810. data.uri = parts.shift();
  6811. data.params = parts;
  6812. return data;
  6813. },
  6814. find_line: function (haystack, needle, sessionpart) {
  6815. var lines = haystack.split('\r\n');
  6816. for (var i = 0; i < lines.length; i++) {
  6817. if (lines[i].substring(0, needle.length) == needle) {
  6818. return lines[i];
  6819. }
  6820. }
  6821. if (!sessionpart) {
  6822. return false;
  6823. }
  6824. // search session part
  6825. lines = sessionpart.split('\r\n');
  6826. for (var j = 0; j < lines.length; j++) {
  6827. if (lines[j].substring(0, needle.length) == needle) {
  6828. return lines[j];
  6829. }
  6830. }
  6831. return false;
  6832. },
  6833. find_lines: function (haystack, needle, sessionpart) {
  6834. var lines = haystack.split('\r\n'),
  6835. needles = [];
  6836. for (var i = 0; i < lines.length; i++) {
  6837. if (lines[i].substring(0, needle.length) == needle)
  6838. needles.push(lines[i]);
  6839. }
  6840. if (needles.length || !sessionpart) {
  6841. return needles;
  6842. }
  6843. // search session part
  6844. lines = sessionpart.split('\r\n');
  6845. for (var j = 0; j < lines.length; j++) {
  6846. if (lines[j].substring(0, needle.length) == needle) {
  6847. needles.push(lines[j]);
  6848. }
  6849. }
  6850. return needles;
  6851. },
  6852. candidateToJingle: function (line) {
  6853. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  6854. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  6855. if (line.indexOf('candidate:') === 0) {
  6856. line = 'a=' + line;
  6857. } else if (line.substring(0, 12) != 'a=candidate:') {
  6858. console.log('parseCandidate called with a line that is not a candidate line');
  6859. console.log(line);
  6860. return null;
  6861. }
  6862. if (line.substring(line.length - 2) == '\r\n') // chomp it
  6863. line = line.substring(0, line.length - 2);
  6864. var candidate = {},
  6865. elems = line.split(' '),
  6866. i;
  6867. if (elems[6] != 'typ') {
  6868. console.log('did not find typ in the right place');
  6869. console.log(line);
  6870. return null;
  6871. }
  6872. candidate.foundation = elems[0].substring(12);
  6873. candidate.component = elems[1];
  6874. candidate.protocol = elems[2].toLowerCase();
  6875. candidate.priority = elems[3];
  6876. candidate.ip = elems[4];
  6877. candidate.port = elems[5];
  6878. // elems[6] => "typ"
  6879. candidate.type = elems[7];
  6880. candidate.generation = '0'; // default, may be overwritten below
  6881. for (i = 8; i < elems.length; i += 2) {
  6882. switch (elems[i]) {
  6883. case 'raddr':
  6884. candidate['rel-addr'] = elems[i + 1];
  6885. break;
  6886. case 'rport':
  6887. candidate['rel-port'] = elems[i + 1];
  6888. break;
  6889. case 'generation':
  6890. candidate.generation = elems[i + 1];
  6891. break;
  6892. case 'tcptype':
  6893. candidate.tcptype = elems[i + 1];
  6894. break;
  6895. default: // TODO
  6896. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  6897. }
  6898. }
  6899. candidate.network = '1';
  6900. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  6901. return candidate;
  6902. },
  6903. candidateFromJingle: function (cand) {
  6904. var line = 'a=candidate:';
  6905. line += cand.getAttribute('foundation');
  6906. line += ' ';
  6907. line += cand.getAttribute('component');
  6908. line += ' ';
  6909. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  6910. line += ' ';
  6911. line += cand.getAttribute('priority');
  6912. line += ' ';
  6913. line += cand.getAttribute('ip');
  6914. line += ' ';
  6915. line += cand.getAttribute('port');
  6916. line += ' ';
  6917. line += 'typ';
  6918. line += ' ' + cand.getAttribute('type');
  6919. line += ' ';
  6920. switch (cand.getAttribute('type')) {
  6921. case 'srflx':
  6922. case 'prflx':
  6923. case 'relay':
  6924. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  6925. line += 'raddr';
  6926. line += ' ';
  6927. line += cand.getAttribute('rel-addr');
  6928. line += ' ';
  6929. line += 'rport';
  6930. line += ' ';
  6931. line += cand.getAttribute('rel-port');
  6932. line += ' ';
  6933. }
  6934. break;
  6935. }
  6936. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  6937. line += 'tcptype';
  6938. line += ' ';
  6939. line += cand.getAttribute('tcptype');
  6940. line += ' ';
  6941. }
  6942. line += 'generation';
  6943. line += ' ';
  6944. line += cand.getAttribute('generation') || '0';
  6945. return line + '\r\n';
  6946. }
  6947. };
  6948. module.exports = SDPUtil;
  6949. },{}],26:[function(require,module,exports){
  6950. var RTC = require('../RTC/RTC');
  6951. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  6952. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  6953. var SSRCReplacement = require("./LocalSSRCReplacement");
  6954. function TraceablePeerConnection(ice_config, constraints, session) {
  6955. var self = this;
  6956. this.session = session;
  6957. var RTCPeerConnectionType = null;
  6958. if (RTCBrowserType.isFirefox()) {
  6959. RTCPeerConnectionType = mozRTCPeerConnection;
  6960. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  6961. RTCPeerConnectionType = RTCPeerConnection;
  6962. } else {
  6963. RTCPeerConnectionType = webkitRTCPeerConnection;
  6964. }
  6965. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  6966. this.updateLog = [];
  6967. this.stats = {};
  6968. this.statsinterval = null;
  6969. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  6970. var Interop = require('sdp-interop').Interop;
  6971. this.interop = new Interop();
  6972. var Simulcast = require('sdp-simulcast');
  6973. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  6974. // override as desired
  6975. this.trace = function (what, info) {
  6976. console.debug(what + " - " + info);
  6977. /*console.warn('WTRACE', what, info);
  6978. if (info && RTCBrowserType.isIExplorer()) {
  6979. if (info.length > 1024) {
  6980. console.warn('WTRACE', what, info.substr(1024));
  6981. }
  6982. if (info.length > 2048) {
  6983. console.warn('WTRACE', what, info.substr(2048));
  6984. }
  6985. }*/
  6986. self.updateLog.push({
  6987. time: new Date(),
  6988. type: what,
  6989. value: info || ""
  6990. });
  6991. };
  6992. this.onicecandidate = null;
  6993. this.peerconnection.onicecandidate = function (event) {
  6994. // FIXME: this causes stack overflow with Temasys Plugin
  6995. if (!RTCBrowserType.isTemasysPluginUsed())
  6996. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  6997. if (self.onicecandidate !== null) {
  6998. self.onicecandidate(event);
  6999. }
  7000. };
  7001. this.onaddstream = null;
  7002. this.peerconnection.onaddstream = function (event) {
  7003. self.trace('onaddstream', event.stream.id);
  7004. if (self.onaddstream !== null) {
  7005. self.onaddstream(event);
  7006. }
  7007. };
  7008. this.onremovestream = null;
  7009. this.peerconnection.onremovestream = function (event) {
  7010. self.trace('onremovestream', event.stream.id);
  7011. if (self.onremovestream !== null) {
  7012. self.onremovestream(event);
  7013. }
  7014. };
  7015. this.onsignalingstatechange = null;
  7016. this.peerconnection.onsignalingstatechange = function (event) {
  7017. self.trace('onsignalingstatechange', self.signalingState);
  7018. if (self.onsignalingstatechange !== null) {
  7019. self.onsignalingstatechange(event);
  7020. }
  7021. };
  7022. this.oniceconnectionstatechange = null;
  7023. this.peerconnection.oniceconnectionstatechange = function (event) {
  7024. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  7025. if (self.oniceconnectionstatechange !== null) {
  7026. self.oniceconnectionstatechange(event);
  7027. }
  7028. };
  7029. this.onnegotiationneeded = null;
  7030. this.peerconnection.onnegotiationneeded = function (event) {
  7031. self.trace('onnegotiationneeded');
  7032. if (self.onnegotiationneeded !== null) {
  7033. self.onnegotiationneeded(event);
  7034. }
  7035. };
  7036. self.ondatachannel = null;
  7037. this.peerconnection.ondatachannel = function (event) {
  7038. self.trace('ondatachannel', event);
  7039. if (self.ondatachannel !== null) {
  7040. self.ondatachannel(event);
  7041. }
  7042. };
  7043. // XXX: do all non-firefox browsers which we support also support this?
  7044. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  7045. this.statsinterval = window.setInterval(function() {
  7046. self.peerconnection.getStats(function(stats) {
  7047. var results = stats.result();
  7048. var now = new Date();
  7049. for (var i = 0; i < results.length; ++i) {
  7050. results[i].names().forEach(function (name) {
  7051. var id = results[i].id + '-' + name;
  7052. if (!self.stats[id]) {
  7053. self.stats[id] = {
  7054. startTime: now,
  7055. endTime: now,
  7056. values: [],
  7057. times: []
  7058. };
  7059. }
  7060. self.stats[id].values.push(results[i].stat(name));
  7061. self.stats[id].times.push(now.getTime());
  7062. if (self.stats[id].values.length > self.maxstats) {
  7063. self.stats[id].values.shift();
  7064. self.stats[id].times.shift();
  7065. }
  7066. self.stats[id].endTime = now;
  7067. });
  7068. }
  7069. });
  7070. }, 1000);
  7071. }
  7072. }
  7073. /**
  7074. * Returns a string representation of a SessionDescription object.
  7075. */
  7076. var dumpSDP = function(description) {
  7077. if (typeof description === 'undefined' || description == null) {
  7078. return '';
  7079. }
  7080. return 'type: ' + description.type + '\r\n' + description.sdp;
  7081. };
  7082. /**
  7083. * Takes a SessionDescription object and returns a "normalized" version.
  7084. * Currently it only takes care of ordering the a=ssrc lines.
  7085. */
  7086. var normalizePlanB = function(desc) {
  7087. if (typeof desc !== 'object' || desc === null ||
  7088. typeof desc.sdp !== 'string') {
  7089. console.warn('An empty description was passed as an argument.');
  7090. return desc;
  7091. }
  7092. var transform = require('sdp-transform');
  7093. var session = transform.parse(desc.sdp);
  7094. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  7095. Array.isArray(session.media)) {
  7096. session.media.forEach(function (mLine) {
  7097. // Chrome appears to be picky about the order in which a=ssrc lines
  7098. // are listed in an m-line when rtx is enabled (and thus there are
  7099. // a=ssrc-group lines with FID semantics). Specifically if we have
  7100. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  7101. // the "a=ssrc:S1" lines, SRD fails.
  7102. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  7103. // first.
  7104. var firstSsrcs = [];
  7105. var newSsrcLines = [];
  7106. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  7107. mLine.ssrcGroups.forEach(function (group) {
  7108. if (typeof group.semantics !== 'undefined' &&
  7109. group.semantics === 'FID') {
  7110. if (typeof group.ssrcs !== 'undefined') {
  7111. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  7112. }
  7113. }
  7114. });
  7115. }
  7116. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  7117. for (var i = 0; i<mLine.ssrcs.length; i++){
  7118. if (typeof mLine.ssrcs[i] === 'object'
  7119. && typeof mLine.ssrcs[i].id !== 'undefined'
  7120. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  7121. newSsrcLines.push(mLine.ssrcs[i]);
  7122. delete mLine.ssrcs[i];
  7123. }
  7124. }
  7125. for (var i = 0; i<mLine.ssrcs.length; i++){
  7126. if (typeof mLine.ssrcs[i] !== 'undefined') {
  7127. newSsrcLines.push(mLine.ssrcs[i]);
  7128. }
  7129. }
  7130. mLine.ssrcs = newSsrcLines;
  7131. }
  7132. });
  7133. }
  7134. var resStr = transform.write(session);
  7135. return new RTCSessionDescription({
  7136. type: desc.type,
  7137. sdp: resStr
  7138. });
  7139. };
  7140. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  7141. TraceablePeerConnection.prototype.__defineGetter__(
  7142. 'signalingState',
  7143. function() { return this.peerconnection.signalingState; });
  7144. TraceablePeerConnection.prototype.__defineGetter__(
  7145. 'iceConnectionState',
  7146. function() { return this.peerconnection.iceConnectionState; });
  7147. TraceablePeerConnection.prototype.__defineGetter__(
  7148. 'localDescription',
  7149. function() {
  7150. var desc = this.peerconnection.localDescription;
  7151. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  7152. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  7153. // if we're running on FF, transform to Plan B first.
  7154. if (RTCBrowserType.usesUnifiedPlan()) {
  7155. desc = this.interop.toPlanB(desc);
  7156. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  7157. }
  7158. return desc;
  7159. });
  7160. TraceablePeerConnection.prototype.__defineGetter__(
  7161. 'remoteDescription',
  7162. function() {
  7163. var desc = this.peerconnection.remoteDescription;
  7164. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  7165. // if we're running on FF, transform to Plan B first.
  7166. if (RTCBrowserType.usesUnifiedPlan()) {
  7167. desc = this.interop.toPlanB(desc);
  7168. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  7169. }
  7170. return desc;
  7171. });
  7172. }
  7173. TraceablePeerConnection.prototype.addStream = function (stream) {
  7174. this.trace('addStream', stream.id);
  7175. try
  7176. {
  7177. this.peerconnection.addStream(stream);
  7178. }
  7179. catch (e)
  7180. {
  7181. console.error(e);
  7182. }
  7183. };
  7184. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  7185. this.trace('removeStream', stream.id);
  7186. if(stopStreams) {
  7187. stream.getAudioTracks().forEach(function (track) {
  7188. // stop() not supported with IE
  7189. if (track.stop) {
  7190. track.stop();
  7191. }
  7192. });
  7193. stream.getVideoTracks().forEach(function (track) {
  7194. // stop() not supported with IE
  7195. if (track.stop) {
  7196. track.stop();
  7197. }
  7198. });
  7199. if (stream.stop) {
  7200. stream.stop();
  7201. }
  7202. }
  7203. try {
  7204. // FF doesn't support this yet.
  7205. if (this.peerconnection.removeStream)
  7206. this.peerconnection.removeStream(stream);
  7207. } catch (e) {
  7208. console.error(e);
  7209. }
  7210. };
  7211. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  7212. this.trace('createDataChannel', label, opts);
  7213. return this.peerconnection.createDataChannel(label, opts);
  7214. };
  7215. TraceablePeerConnection.prototype.setLocalDescription
  7216. = function (description, successCallback, failureCallback) {
  7217. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  7218. // if we're running on FF, transform to Plan A first.
  7219. if (RTCBrowserType.usesUnifiedPlan()) {
  7220. description = this.interop.toUnifiedPlan(description);
  7221. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  7222. }
  7223. var self = this;
  7224. this.peerconnection.setLocalDescription(description,
  7225. function () {
  7226. self.trace('setLocalDescriptionOnSuccess');
  7227. successCallback();
  7228. },
  7229. function (err) {
  7230. self.trace('setLocalDescriptionOnFailure', err);
  7231. failureCallback(err);
  7232. }
  7233. );
  7234. /*
  7235. if (this.statsinterval === null && this.maxstats > 0) {
  7236. // start gathering stats
  7237. }
  7238. */
  7239. };
  7240. TraceablePeerConnection.prototype.setRemoteDescription
  7241. = function (description, successCallback, failureCallback) {
  7242. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  7243. // TODO the focus should squeze or explode the remote simulcast
  7244. description = this.simulcast.mungeRemoteDescription(description);
  7245. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  7246. // if we're running on FF, transform to Plan A first.
  7247. if (RTCBrowserType.usesUnifiedPlan()) {
  7248. description = this.interop.toUnifiedPlan(description);
  7249. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  7250. }
  7251. if (RTCBrowserType.usesPlanB()) {
  7252. description = normalizePlanB(description);
  7253. }
  7254. var self = this;
  7255. this.peerconnection.setRemoteDescription(description,
  7256. function () {
  7257. self.trace('setRemoteDescriptionOnSuccess');
  7258. successCallback();
  7259. },
  7260. function (err) {
  7261. self.trace('setRemoteDescriptionOnFailure', err);
  7262. failureCallback(err);
  7263. }
  7264. );
  7265. /*
  7266. if (this.statsinterval === null && this.maxstats > 0) {
  7267. // start gathering stats
  7268. }
  7269. */
  7270. };
  7271. TraceablePeerConnection.prototype.close = function () {
  7272. this.trace('stop');
  7273. if (this.statsinterval !== null) {
  7274. window.clearInterval(this.statsinterval);
  7275. this.statsinterval = null;
  7276. }
  7277. this.peerconnection.close();
  7278. };
  7279. TraceablePeerConnection.prototype.createOffer
  7280. = function (successCallback, failureCallback, constraints) {
  7281. var self = this;
  7282. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  7283. this.peerconnection.createOffer(
  7284. function (offer) {
  7285. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  7286. // NOTE this is not tested because in meet the focus generates the
  7287. // offer.
  7288. // if we're running on FF, transform to Plan B first.
  7289. if (RTCBrowserType.usesUnifiedPlan()) {
  7290. offer = self.interop.toPlanB(offer);
  7291. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  7292. }
  7293. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  7294. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  7295. offer = self.simulcast.mungeLocalDescription(offer);
  7296. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  7297. }
  7298. successCallback(offer);
  7299. },
  7300. function(err) {
  7301. self.trace('createOfferOnFailure', err);
  7302. failureCallback(err);
  7303. },
  7304. constraints
  7305. );
  7306. };
  7307. TraceablePeerConnection.prototype.createAnswer
  7308. = function (successCallback, failureCallback, constraints) {
  7309. var self = this;
  7310. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  7311. this.peerconnection.createAnswer(
  7312. function (answer) {
  7313. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  7314. // if we're running on FF, transform to Plan A first.
  7315. if (RTCBrowserType.usesUnifiedPlan()) {
  7316. answer = self.interop.toPlanB(answer);
  7317. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  7318. }
  7319. // munge local video SSRC
  7320. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  7321. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  7322. answer = self.simulcast.mungeLocalDescription(answer);
  7323. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  7324. }
  7325. successCallback(answer);
  7326. },
  7327. function(err) {
  7328. self.trace('createAnswerOnFailure', err);
  7329. failureCallback(err);
  7330. },
  7331. constraints
  7332. );
  7333. };
  7334. TraceablePeerConnection.prototype.addIceCandidate
  7335. = function (candidate, successCallback, failureCallback) {
  7336. //var self = this;
  7337. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  7338. this.peerconnection.addIceCandidate(candidate);
  7339. /* maybe later
  7340. this.peerconnection.addIceCandidate(candidate,
  7341. function () {
  7342. self.trace('addIceCandidateOnSuccess');
  7343. successCallback();
  7344. },
  7345. function (err) {
  7346. self.trace('addIceCandidateOnFailure', err);
  7347. failureCallback(err);
  7348. }
  7349. );
  7350. */
  7351. };
  7352. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  7353. // TODO: Is this the correct way to handle Opera, Temasys?
  7354. if (RTCBrowserType.isFirefox()) {
  7355. // ignore for now...
  7356. if(!errback)
  7357. errback = function () {};
  7358. this.peerconnection.getStats(null, callback, errback);
  7359. } else {
  7360. this.peerconnection.getStats(callback);
  7361. }
  7362. };
  7363. module.exports = TraceablePeerConnection;
  7364. },{"../../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){
  7365. /* global $, $iq, APP, config, messageHandler,
  7366. roomName, sessionTerminated, Strophe, Util */
  7367. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7368. var Settings = require("../settings/Settings");
  7369. var AuthenticationEvents
  7370. = require("../../service/authentication/AuthenticationEvents");
  7371. function createExpBackoffTimer(step) {
  7372. var count = 1;
  7373. return function (reset) {
  7374. // Reset call
  7375. if (reset) {
  7376. count = 1;
  7377. return;
  7378. }
  7379. // Calculate next timeout
  7380. var timeout = Math.pow(2, count - 1);
  7381. count += 1;
  7382. return timeout * step;
  7383. };
  7384. }
  7385. function Moderator(roomName, xmpp, emitter) {
  7386. this.roomName = roomName;
  7387. this.xmppService = xmpp;
  7388. this.getNextTimeout = createExpBackoffTimer(1000);
  7389. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  7390. // External authentication stuff
  7391. this.externalAuthEnabled = false;
  7392. this.settings = new Settings(roomName);
  7393. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  7394. // it will be enabled automatically if focus detects the component through
  7395. // service discovery.
  7396. this.sipGatewayEnabled = this.xmppService.options.hosts.call_control !== undefined;
  7397. this.eventEmitter = emitter;
  7398. this.connection = this.xmppService.connection;
  7399. this.focusUserJid;
  7400. //FIXME:
  7401. // Message listener that talks to POPUP window
  7402. function listener(event) {
  7403. if (event.data && event.data.sessionId) {
  7404. if (event.origin !== window.location.origin) {
  7405. console.warn("Ignoring sessionId from different origin: " +
  7406. event.origin);
  7407. return;
  7408. }
  7409. localStorage.setItem('sessionId', event.data.sessionId);
  7410. // After popup is closed we will authenticate
  7411. }
  7412. }
  7413. // Register
  7414. if (window.addEventListener) {
  7415. window.addEventListener("message", listener, false);
  7416. } else {
  7417. window.attachEvent("onmessage", listener);
  7418. }
  7419. }
  7420. Moderator.prototype.isExternalAuthEnabled = function () {
  7421. return this.externalAuthEnabled;
  7422. };
  7423. Moderator.prototype.isSipGatewayEnabled = function () {
  7424. return this.sipGatewayEnabled;
  7425. };
  7426. Moderator.prototype.onMucMemberLeft = function (jid) {
  7427. console.info("Someone left is it focus ? " + jid);
  7428. var resource = Strophe.getResourceFromJid(jid);
  7429. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  7430. console.info(
  7431. "Focus has left the room - leaving conference");
  7432. //hangUp();
  7433. // We'd rather reload to have everything re-initialized
  7434. //FIXME: show some message before reload
  7435. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  7436. }
  7437. };
  7438. Moderator.prototype.setFocusUserJid = function (focusJid) {
  7439. if (!this.focusUserJid) {
  7440. this.focusUserJid = focusJid;
  7441. console.info("Focus jid set to: " + this.focusUserJid);
  7442. }
  7443. };
  7444. Moderator.prototype.getFocusUserJid = function () {
  7445. return this.focusUserJid;
  7446. };
  7447. Moderator.prototype.getFocusComponent = function () {
  7448. // Get focus component address
  7449. var focusComponent = this.xmppService.options.hosts.focus;
  7450. // If not specified use default: 'focus.domain'
  7451. if (!focusComponent) {
  7452. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  7453. }
  7454. return focusComponent;
  7455. };
  7456. Moderator.prototype.createConferenceIq = function () {
  7457. // Generate create conference IQ
  7458. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  7459. // Session Id used for authentication
  7460. var sessionId = localStorage.getItem('sessionId');
  7461. var machineUID = this.settings.getSettings().uid;
  7462. console.info(
  7463. "Session ID: " + sessionId + " machine UID: " + machineUID);
  7464. elem.c('conference', {
  7465. xmlns: 'http://jitsi.org/protocol/focus',
  7466. room: this.roomName,
  7467. 'machine-uid': machineUID
  7468. });
  7469. if (sessionId) {
  7470. elem.attrs({ 'session-id': sessionId});
  7471. }
  7472. if (this.xmppService.options.hosts.bridge !== undefined) {
  7473. elem.c(
  7474. 'property',
  7475. {name: 'bridge',value: this.xmppService.options.hosts.bridge})
  7476. .up();
  7477. }
  7478. // Tell the focus we have Jigasi configured
  7479. if (this.xmppService.options.hosts.call_control !== undefined) {
  7480. elem.c(
  7481. 'property',
  7482. {name: 'call_control',value: this.xmppService.options.hosts.call_control})
  7483. .up();
  7484. }
  7485. if (this.xmppService.options.channelLastN !== undefined) {
  7486. elem.c(
  7487. 'property',
  7488. {name: 'channelLastN',value: this.xmppService.options.channelLastN})
  7489. .up();
  7490. }
  7491. if (this.xmppService.options.adaptiveLastN !== undefined) {
  7492. elem.c(
  7493. 'property',
  7494. {name: 'adaptiveLastN',value: this.xmppService.options.adaptiveLastN})
  7495. .up();
  7496. }
  7497. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  7498. elem.c(
  7499. 'property',
  7500. {name: 'adaptiveSimulcast',value: this.xmppService.options.adaptiveSimulcast})
  7501. .up();
  7502. }
  7503. if (this.xmppService.options.openSctp !== undefined) {
  7504. elem.c(
  7505. 'property',
  7506. {name: 'openSctp',value: this.xmppService.options.openSctp})
  7507. .up();
  7508. }
  7509. if(this.xmppService.options.startAudioMuted !== undefined)
  7510. {
  7511. elem.c(
  7512. 'property',
  7513. {name: 'startAudioMuted',value: this.xmppService.options.startAudioMuted})
  7514. .up();
  7515. }
  7516. if(this.xmppService.options.startVideoMuted !== undefined)
  7517. {
  7518. elem.c(
  7519. 'property',
  7520. {name: 'startVideoMuted',value: this.xmppService.options.startVideoMuted})
  7521. .up();
  7522. }
  7523. elem.c(
  7524. 'property',
  7525. {name: 'simulcastMode',value: 'rewriting'})
  7526. .up();
  7527. elem.up();
  7528. return elem;
  7529. };
  7530. Moderator.prototype.parseSessionId = function (resultIq) {
  7531. var sessionId = $(resultIq).find('conference').attr('session-id');
  7532. if (sessionId) {
  7533. console.info('Received sessionId: ' + sessionId);
  7534. localStorage.setItem('sessionId', sessionId);
  7535. }
  7536. };
  7537. Moderator.prototype.parseConfigOptions = function (resultIq) {
  7538. this.setFocusUserJid(
  7539. $(resultIq).find('conference').attr('focusjid'));
  7540. var authenticationEnabled
  7541. = $(resultIq).find(
  7542. '>conference>property' +
  7543. '[name=\'authentication\'][value=\'true\']').length > 0;
  7544. console.info("Authentication enabled: " + authenticationEnabled);
  7545. this.externalAuthEnabled = $(resultIq).find(
  7546. '>conference>property' +
  7547. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  7548. console.info('External authentication enabled: ' + this.externalAuthEnabled);
  7549. if (!this.externalAuthEnabled) {
  7550. // We expect to receive sessionId in 'internal' authentication mode
  7551. this.parseSessionId(resultIq);
  7552. }
  7553. var authIdentity = $(resultIq).find('>conference').attr('identity');
  7554. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  7555. authenticationEnabled, authIdentity);
  7556. // Check if focus has auto-detected Jigasi component(this will be also
  7557. // included if we have passed our host from the config)
  7558. if ($(resultIq).find(
  7559. '>conference>property' +
  7560. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  7561. this.sipGatewayEnabled = true;
  7562. }
  7563. console.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  7564. };
  7565. // FIXME = we need to show the fact that we're waiting for the focus
  7566. // to the user(or that focus is not available)
  7567. Moderator.prototype.allocateConferenceFocus = function ( callback) {
  7568. // Try to use focus user JID from the config
  7569. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  7570. // Send create conference IQ
  7571. var iq = this.createConferenceIq();
  7572. var self = this;
  7573. this.connection.sendIQ(
  7574. iq,
  7575. function (result) {
  7576. // Setup config options
  7577. self.parseConfigOptions(result);
  7578. if ('true' === $(result).find('conference').attr('ready')) {
  7579. // Reset both timers
  7580. self.getNextTimeout(true);
  7581. self.getNextErrorTimeout(true);
  7582. // Exec callback
  7583. callback();
  7584. } else {
  7585. var waitMs = self.getNextTimeout();
  7586. console.info("Waiting for the focus... " + waitMs);
  7587. // Reset error timeout
  7588. self.getNextErrorTimeout(true);
  7589. window.setTimeout(
  7590. function () {
  7591. self.allocateConferenceFocus(callback);
  7592. }, waitMs);
  7593. }
  7594. },
  7595. function (error) {
  7596. // Invalid session ? remove and try again
  7597. // without session ID to get a new one
  7598. var invalidSession
  7599. = $(error).find('>error>session-invalid').length;
  7600. if (invalidSession) {
  7601. console.info("Session expired! - removing");
  7602. localStorage.removeItem("sessionId");
  7603. }
  7604. if ($(error).find('>error>graceful-shutdown').length) {
  7605. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  7606. return;
  7607. }
  7608. // Check for error returned by the reservation system
  7609. var reservationErr = $(error).find('>error>reservation-error');
  7610. if (reservationErr.length) {
  7611. // Trigger error event
  7612. var errorCode = reservationErr.attr('error-code');
  7613. var errorMsg;
  7614. if ($(error).find('>error>text')) {
  7615. errorMsg = $(error).find('>error>text').text();
  7616. }
  7617. self.eventEmitter.emit(
  7618. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  7619. return;
  7620. }
  7621. // Not authorized to create new room
  7622. if ($(error).find('>error>not-authorized').length) {
  7623. console.warn("Unauthorized to start the conference", error);
  7624. var toDomain
  7625. = Strophe.getDomainFromJid(error.getAttribute('to'));
  7626. if (toDomain !== this.xmppService.options.hosts.anonymousdomain) {
  7627. //FIXME: "is external" should come either from
  7628. // the focus or config.js
  7629. self.externalAuthEnabled = true;
  7630. }
  7631. self.eventEmitter.emit(
  7632. XMPPEvents.AUTHENTICATION_REQUIRED,
  7633. function () {
  7634. self.allocateConferenceFocus(
  7635. callback);
  7636. });
  7637. return;
  7638. }
  7639. var waitMs = self.getNextErrorTimeout();
  7640. console.error("Focus error, retry after " + waitMs, error);
  7641. // Show message
  7642. var focusComponent = self.getFocusComponent();
  7643. var retrySec = waitMs / 1000;
  7644. //FIXME: message is duplicated ?
  7645. // Do not show in case of session invalid
  7646. // which means just a retry
  7647. if (!invalidSession) {
  7648. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  7649. focusComponent, retrySec);
  7650. }
  7651. // Reset response timeout
  7652. self.getNextTimeout(true);
  7653. window.setTimeout(
  7654. function () {
  7655. self.allocateConferenceFocus(callback);
  7656. }, waitMs);
  7657. }
  7658. );
  7659. };
  7660. Moderator.prototype.getLoginUrl = function (urlCallback) {
  7661. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  7662. iq.c('login-url', {
  7663. xmlns: 'http://jitsi.org/protocol/focus',
  7664. room: this.roomName,
  7665. 'machine-uid': this.settings.getSettings().uid
  7666. });
  7667. this.connection.sendIQ(
  7668. iq,
  7669. function (result) {
  7670. var url = $(result).find('login-url').attr('url');
  7671. url = url = decodeURIComponent(url);
  7672. if (url) {
  7673. console.info("Got auth url: " + url);
  7674. urlCallback(url);
  7675. } else {
  7676. console.error(
  7677. "Failed to get auth url from the focus", result);
  7678. }
  7679. },
  7680. function (error) {
  7681. console.error("Get auth url error", error);
  7682. }
  7683. );
  7684. };
  7685. Moderator.prototype.getPopupLoginUrl = function (urlCallback) {
  7686. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  7687. iq.c('login-url', {
  7688. xmlns: 'http://jitsi.org/protocol/focus',
  7689. room: this.roomName,
  7690. 'machine-uid': this.settings.getSettings().uid,
  7691. popup: true
  7692. });
  7693. this.connection.sendIQ(
  7694. iq,
  7695. function (result) {
  7696. var url = $(result).find('login-url').attr('url');
  7697. url = url = decodeURIComponent(url);
  7698. if (url) {
  7699. console.info("Got POPUP auth url: " + url);
  7700. urlCallback(url);
  7701. } else {
  7702. console.error(
  7703. "Failed to get POPUP auth url from the focus", result);
  7704. }
  7705. },
  7706. function (error) {
  7707. console.error('Get POPUP auth url error', error);
  7708. }
  7709. );
  7710. };
  7711. Moderator.prototype.logout = function (callback) {
  7712. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  7713. var sessionId = localStorage.getItem('sessionId');
  7714. if (!sessionId) {
  7715. callback();
  7716. return;
  7717. }
  7718. iq.c('logout', {
  7719. xmlns: 'http://jitsi.org/protocol/focus',
  7720. 'session-id': sessionId
  7721. });
  7722. this.connection.sendIQ(
  7723. iq,
  7724. function (result) {
  7725. var logoutUrl = $(result).find('logout').attr('logout-url');
  7726. if (logoutUrl) {
  7727. logoutUrl = decodeURIComponent(logoutUrl);
  7728. }
  7729. console.info("Log out OK, url: " + logoutUrl, result);
  7730. localStorage.removeItem('sessionId');
  7731. callback(logoutUrl);
  7732. },
  7733. function (error) {
  7734. console.error("Logout error", error);
  7735. }
  7736. );
  7737. };
  7738. module.exports = Moderator;
  7739. },{"../../service/authentication/AuthenticationEvents":74,"../../service/xmpp/XMPPEvents":76,"../settings/Settings":18}],28:[function(require,module,exports){
  7740. /* jshint -W117 */
  7741. /* a simple MUC connection plugin
  7742. * can only handle a single MUC room
  7743. */
  7744. var ChatRoom = require("./ChatRoom");
  7745. module.exports = function(XMPP) {
  7746. Strophe.addConnectionPlugin('emuc', {
  7747. connection: null,
  7748. rooms: {},//map with the rooms
  7749. init: function (conn) {
  7750. this.connection = conn;
  7751. // add handlers (just once)
  7752. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, null, null);
  7753. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null);
  7754. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null);
  7755. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null);
  7756. },
  7757. createRoom: function (jid, password, options) {
  7758. var roomJid = Strophe.getBareJidFromJid(jid);
  7759. if (this.rooms[roomJid]) {
  7760. console.error("You are already in the room!");
  7761. return;
  7762. }
  7763. this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, options);
  7764. return this.rooms[roomJid];
  7765. },
  7766. doLeave: function (jid) {
  7767. this.rooms[jid].doLeave();
  7768. delete this.rooms[jid];
  7769. },
  7770. onPresence: function (pres) {
  7771. var from = pres.getAttribute('from');
  7772. // What is this for? A workaround for something?
  7773. if (pres.getAttribute('type')) {
  7774. return true;
  7775. }
  7776. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7777. if(!room)
  7778. return;
  7779. // Parse status.
  7780. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  7781. room.createNonAnonymousRoom();
  7782. }
  7783. room.onPresence(pres);
  7784. return true;
  7785. },
  7786. onPresenceUnavailable: function (pres) {
  7787. var from = pres.getAttribute('from');
  7788. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7789. if(!room)
  7790. return;
  7791. room.onPresenceUnavailable(pres, from);
  7792. return true;
  7793. },
  7794. onPresenceError: function (pres) {
  7795. var from = pres.getAttribute('from');
  7796. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7797. if(!room)
  7798. return;
  7799. room.onPresenceError(pres, from);
  7800. return true;
  7801. },
  7802. onMessage: function (msg) {
  7803. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  7804. var from = msg.getAttribute('from');
  7805. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7806. if(!room)
  7807. return;
  7808. room.onMessage(msg, from);
  7809. return true;
  7810. },
  7811. setJingleSession: function (from, session) {
  7812. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7813. if(!room)
  7814. return;
  7815. room.setJingleSession(session);
  7816. }
  7817. });
  7818. };
  7819. },{"./ChatRoom":19}],29:[function(require,module,exports){
  7820. /* jshint -W117 */
  7821. var JingleSession = require("./JingleSessionPC");
  7822. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7823. var RTCBrowserType = require("../RTC/RTCBrowserType");
  7824. module.exports = function(XMPP, eventEmitter) {
  7825. Strophe.addConnectionPlugin('jingle', {
  7826. connection: null,
  7827. sessions: {},
  7828. jid2session: {},
  7829. ice_config: {iceServers: []},
  7830. media_constraints: {
  7831. mandatory: {
  7832. 'OfferToReceiveAudio': true,
  7833. 'OfferToReceiveVideo': true
  7834. }
  7835. // MozDontOfferDataChannel: true when this is firefox
  7836. },
  7837. init: function (conn) {
  7838. this.connection = conn;
  7839. if (this.connection.disco) {
  7840. // http://xmpp.org/extensions/xep-0167.html#support
  7841. // http://xmpp.org/extensions/xep-0176.html#support
  7842. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  7843. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  7844. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  7845. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  7846. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  7847. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  7848. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  7849. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  7850. || RTCBrowserType.isTemasysPluginUsed()) {
  7851. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  7852. }
  7853. // this is dealt with by SDP O/A so we don't need to announce this
  7854. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  7855. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  7856. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  7857. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  7858. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  7859. }
  7860. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  7861. },
  7862. onJingle: function (iq) {
  7863. var sid = $(iq).find('jingle').attr('sid');
  7864. var action = $(iq).find('jingle').attr('action');
  7865. var fromJid = iq.getAttribute('from');
  7866. // send ack first
  7867. var ack = $iq({type: 'result',
  7868. to: fromJid,
  7869. id: iq.getAttribute('id')
  7870. });
  7871. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  7872. var sess = this.sessions[sid];
  7873. if ('session-initiate' != action) {
  7874. if (sess === null) {
  7875. ack.type = 'error';
  7876. ack.c('error', {type: 'cancel'})
  7877. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  7878. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  7879. this.connection.send(ack);
  7880. return true;
  7881. }
  7882. // local jid is not checked
  7883. if (fromJid != sess.peerjid) {
  7884. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  7885. ack.type = 'error';
  7886. ack.c('error', {type: 'cancel'})
  7887. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  7888. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  7889. this.connection.send(ack);
  7890. return true;
  7891. }
  7892. } else if (sess !== undefined) {
  7893. // existing session with same session id
  7894. // this might be out-of-order if the sess.peerjid is the same as from
  7895. ack.type = 'error';
  7896. ack.c('error', {type: 'cancel'})
  7897. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  7898. console.warn('duplicate session id', sid);
  7899. this.connection.send(ack);
  7900. return true;
  7901. }
  7902. // FIXME: check for a defined action
  7903. this.connection.send(ack);
  7904. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  7905. switch (action) {
  7906. case 'session-initiate':
  7907. var startMuted = $(iq).find('jingle>startmuted');
  7908. if (startMuted && startMuted.length > 0) {
  7909. var audioMuted = startMuted.attr("audio");
  7910. var videoMuted = startMuted.attr("video");
  7911. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  7912. audioMuted === "true", videoMuted === "true");
  7913. }
  7914. sess = new JingleSession(
  7915. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  7916. this.connection, XMPP);
  7917. // configure session
  7918. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  7919. this.connection.emuc.setJingleSession(fromBareJid, sess);
  7920. sess.media_constraints = this.media_constraints;
  7921. sess.ice_config = this.ice_config;
  7922. sess.initialize(fromJid, false);
  7923. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  7924. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  7925. sess.setOffer($(iq).find('>jingle'));
  7926. this.sessions[sess.sid] = sess;
  7927. this.jid2session[sess.peerjid] = sess;
  7928. // the callback should either
  7929. // .sendAnswer and .accept
  7930. // or .sendTerminate -- not necessarily synchronous
  7931. sess.sendAnswer();
  7932. sess.accept();
  7933. break;
  7934. case 'session-accept':
  7935. sess.setAnswer($(iq).find('>jingle'));
  7936. sess.accept();
  7937. break;
  7938. case 'session-terminate':
  7939. // If this is not the focus sending the terminate, we have
  7940. // nothing more to do here.
  7941. if (Object.keys(this.sessions).length < 1
  7942. || !(this.sessions[Object.keys(this.sessions)[0]]
  7943. instanceof JingleSession))
  7944. {
  7945. break;
  7946. }
  7947. console.log('terminating...', sess.sid);
  7948. sess.terminate();
  7949. this.terminate(sess.sid);
  7950. if ($(iq).find('>jingle>reason').length) {
  7951. $(document).trigger('callterminated.jingle', [
  7952. sess.sid,
  7953. sess.peerjid,
  7954. $(iq).find('>jingle>reason>:first')[0].tagName,
  7955. $(iq).find('>jingle>reason>text').text()
  7956. ]);
  7957. } else {
  7958. $(document).trigger('callterminated.jingle',
  7959. [sess.sid, sess.peerjid]);
  7960. }
  7961. break;
  7962. case 'transport-info':
  7963. sess.addIceCandidate($(iq).find('>jingle>content'));
  7964. break;
  7965. case 'session-info':
  7966. var affected;
  7967. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  7968. $(document).trigger('ringing.jingle', [sess.sid]);
  7969. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  7970. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  7971. $(document).trigger('mute.jingle', [sess.sid, affected]);
  7972. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  7973. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  7974. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  7975. }
  7976. break;
  7977. case 'addsource': // FIXME: proprietary, un-jingleish
  7978. case 'source-add': // FIXME: proprietary
  7979. sess.addSource($(iq).find('>jingle>content'), fromJid);
  7980. break;
  7981. case 'removesource': // FIXME: proprietary, un-jingleish
  7982. case 'source-remove': // FIXME: proprietary
  7983. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  7984. break;
  7985. default:
  7986. console.warn('jingle action not implemented', action);
  7987. break;
  7988. }
  7989. return true;
  7990. },
  7991. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  7992. if (sid === null || sid === undefined) {
  7993. for (sid in this.sessions) {
  7994. if (this.sessions[sid].state != 'ended') {
  7995. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  7996. this.sessions[sid].terminate();
  7997. }
  7998. delete this.jid2session[this.sessions[sid].peerjid];
  7999. delete this.sessions[sid];
  8000. }
  8001. } else if (this.sessions.hasOwnProperty(sid)) {
  8002. if (this.sessions[sid].state != 'ended') {
  8003. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  8004. this.sessions[sid].terminate();
  8005. }
  8006. delete this.jid2session[this.sessions[sid].peerjid];
  8007. delete this.sessions[sid];
  8008. }
  8009. },
  8010. getStunAndTurnCredentials: function () {
  8011. // get stun and turn configuration from server via xep-0215
  8012. // uses time-limited credentials as described in
  8013. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  8014. //
  8015. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  8016. // for a prosody module which implements this
  8017. //
  8018. // currently, this doesn't work with updateIce and therefore credentials with a long
  8019. // validity have to be fetched before creating the peerconnection
  8020. // TODO: implement refresh via updateIce as described in
  8021. // https://code.google.com/p/webrtc/issues/detail?id=1650
  8022. var self = this;
  8023. this.connection.sendIQ(
  8024. $iq({type: 'get', to: this.connection.domain})
  8025. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  8026. function (res) {
  8027. var iceservers = [];
  8028. $(res).find('>services>service').each(function (idx, el) {
  8029. el = $(el);
  8030. var dict = {};
  8031. var type = el.attr('type');
  8032. switch (type) {
  8033. case 'stun':
  8034. dict.url = 'stun:' + el.attr('host');
  8035. if (el.attr('port')) {
  8036. dict.url += ':' + el.attr('port');
  8037. }
  8038. iceservers.push(dict);
  8039. break;
  8040. case 'turn':
  8041. case 'turns':
  8042. dict.url = type + ':';
  8043. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  8044. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  8045. dict.url += el.attr('username') + '@';
  8046. } else {
  8047. dict.username = el.attr('username'); // only works in M28
  8048. }
  8049. }
  8050. dict.url += el.attr('host');
  8051. if (el.attr('port') && el.attr('port') != '3478') {
  8052. dict.url += ':' + el.attr('port');
  8053. }
  8054. if (el.attr('transport') && el.attr('transport') != 'udp') {
  8055. dict.url += '?transport=' + el.attr('transport');
  8056. }
  8057. if (el.attr('password')) {
  8058. dict.credential = el.attr('password');
  8059. }
  8060. iceservers.push(dict);
  8061. break;
  8062. }
  8063. });
  8064. self.ice_config.iceServers = iceservers;
  8065. },
  8066. function (err) {
  8067. console.warn('getting turn credentials failed', err);
  8068. console.warn('is mod_turncredentials or similar installed?');
  8069. }
  8070. );
  8071. // implement push?
  8072. },
  8073. /**
  8074. * Returns the data saved in 'updateLog' in a format to be logged.
  8075. */
  8076. getLog: function () {
  8077. var data = {};
  8078. var self = this;
  8079. Object.keys(this.sessions).forEach(function (sid) {
  8080. var session = self.sessions[sid];
  8081. if (session.peerconnection && session.peerconnection.updateLog) {
  8082. // FIXME: should probably be a .dump call
  8083. data["jingle_" + session.sid] = {
  8084. updateLog: session.peerconnection.updateLog,
  8085. stats: session.peerconnection.stats,
  8086. url: window.location.href
  8087. };
  8088. }
  8089. });
  8090. return data;
  8091. }
  8092. });
  8093. };
  8094. },{"../../service/xmpp/XMPPEvents":76,"../RTC/RTCBrowserType":14,"./JingleSessionPC":21}],30:[function(require,module,exports){
  8095. /* global Strophe */
  8096. module.exports = function () {
  8097. Strophe.addConnectionPlugin('logger', {
  8098. // logs raw stanzas and makes them available for download as JSON
  8099. connection: null,
  8100. log: [],
  8101. init: function (conn) {
  8102. this.connection = conn;
  8103. this.connection.rawInput = this.log_incoming.bind(this);
  8104. this.connection.rawOutput = this.log_outgoing.bind(this);
  8105. },
  8106. log_incoming: function (stanza) {
  8107. this.log.push([new Date().getTime(), 'incoming', stanza]);
  8108. },
  8109. log_outgoing: function (stanza) {
  8110. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  8111. }
  8112. });
  8113. };
  8114. },{}],31:[function(require,module,exports){
  8115. /* jshint -W117 */
  8116. module.exports = function() {
  8117. Strophe.addConnectionPlugin('rayo',
  8118. {
  8119. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  8120. connection: null,
  8121. init: function (conn) {
  8122. this.connection = conn;
  8123. if (this.connection.disco) {
  8124. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  8125. }
  8126. this.connection.addHandler(
  8127. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  8128. },
  8129. onRayo: function (iq) {
  8130. console.info("Rayo IQ", iq);
  8131. },
  8132. dial: function (to, from, roomName, roomPass) {
  8133. var self = this;
  8134. var req = $iq(
  8135. {
  8136. type: 'set',
  8137. to: this.connection.emuc.focusMucJid
  8138. }
  8139. );
  8140. req.c('dial',
  8141. {
  8142. xmlns: this.RAYO_XMLNS,
  8143. to: to,
  8144. from: from
  8145. });
  8146. req.c('header',
  8147. {
  8148. name: 'JvbRoomName',
  8149. value: roomName
  8150. }).up();
  8151. if (roomPass !== null && roomPass.length) {
  8152. req.c('header',
  8153. {
  8154. name: 'JvbRoomPassword',
  8155. value: roomPass
  8156. }).up();
  8157. }
  8158. this.connection.sendIQ(
  8159. req,
  8160. function (result) {
  8161. console.info('Dial result ', result);
  8162. var resource = $(result).find('ref').attr('uri');
  8163. this.call_resource = resource.substr('xmpp:'.length);
  8164. console.info(
  8165. "Received call resource: " + this.call_resource);
  8166. },
  8167. function (error) {
  8168. console.info('Dial error ', error);
  8169. }
  8170. );
  8171. },
  8172. hang_up: function () {
  8173. if (!this.call_resource) {
  8174. console.warn("No call in progress");
  8175. return;
  8176. }
  8177. var self = this;
  8178. var req = $iq(
  8179. {
  8180. type: 'set',
  8181. to: this.call_resource
  8182. }
  8183. );
  8184. req.c('hangup',
  8185. {
  8186. xmlns: this.RAYO_XMLNS
  8187. });
  8188. this.connection.sendIQ(
  8189. req,
  8190. function (result) {
  8191. console.info('Hangup result ', result);
  8192. self.call_resource = null;
  8193. },
  8194. function (error) {
  8195. console.info('Hangup error ', error);
  8196. self.call_resource = null;
  8197. }
  8198. );
  8199. }
  8200. }
  8201. );
  8202. };
  8203. },{}],32:[function(require,module,exports){
  8204. /**
  8205. * Strophe logger implementation. Logs from level WARN and above.
  8206. */
  8207. module.exports = function () {
  8208. Strophe.log = function (level, msg) {
  8209. switch (level) {
  8210. case Strophe.LogLevel.WARN:
  8211. console.warn("Strophe: " + msg);
  8212. break;
  8213. case Strophe.LogLevel.ERROR:
  8214. case Strophe.LogLevel.FATAL:
  8215. console.error("Strophe: " + msg);
  8216. break;
  8217. }
  8218. };
  8219. Strophe.getStatusString = function (status) {
  8220. switch (status) {
  8221. case Strophe.Status.ERROR:
  8222. return "ERROR";
  8223. case Strophe.Status.CONNECTING:
  8224. return "CONNECTING";
  8225. case Strophe.Status.CONNFAIL:
  8226. return "CONNFAIL";
  8227. case Strophe.Status.AUTHENTICATING:
  8228. return "AUTHENTICATING";
  8229. case Strophe.Status.AUTHFAIL:
  8230. return "AUTHFAIL";
  8231. case Strophe.Status.CONNECTED:
  8232. return "CONNECTED";
  8233. case Strophe.Status.DISCONNECTED:
  8234. return "DISCONNECTED";
  8235. case Strophe.Status.DISCONNECTING:
  8236. return "DISCONNECTING";
  8237. case Strophe.Status.ATTACHED:
  8238. return "ATTACHED";
  8239. default:
  8240. return "unknown";
  8241. }
  8242. };
  8243. };
  8244. },{}],33:[function(require,module,exports){
  8245. /* global $, APP, config, Strophe*/
  8246. var EventEmitter = require("events");
  8247. var Pako = require("pako");
  8248. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  8249. var RTCEvents = require("../../service/RTC/RTCEvents");
  8250. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8251. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  8252. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  8253. var RTC = require("../RTC/RTC");
  8254. var authenticatedUser = false;
  8255. function createConnection(bosh) {
  8256. bosh = bosh || '/http-bind';
  8257. return new Strophe.Connection(bosh);
  8258. };
  8259. //!!!!!!!!!! FIXME: ...
  8260. function initStrophePlugins(XMPP)
  8261. {
  8262. require("./strophe.emuc")(XMPP);
  8263. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  8264. // require("./strophe.moderate")(XMPP, eventEmitter);
  8265. require("./strophe.util")();
  8266. require("./strophe.rayo")();
  8267. require("./strophe.logger")();
  8268. }
  8269. //!!!!!!!!!! FIXME: ...
  8270. ///**
  8271. // * If given <tt>localStream</tt> is video one this method will advertise it's
  8272. // * video type in MUC presence.
  8273. // * @param localStream new or modified <tt>LocalStream</tt>.
  8274. // */
  8275. //function broadcastLocalVideoType(localStream) {
  8276. // if (localStream.videoType)
  8277. // XMPP.addToPresence('videoType', localStream.videoType);
  8278. //}
  8279. //
  8280. //function registerListeners() {
  8281. // RTC.addStreamListener(
  8282. // broadcastLocalVideoType,
  8283. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  8284. // );
  8285. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  8286. // XMPP.addToPresence("devices", devices);
  8287. // });
  8288. //}
  8289. function XMPP(options) {
  8290. this.eventEmitter = new EventEmitter();
  8291. this.connection = null;
  8292. this.disconnectInProgress = false;
  8293. this.forceMuted = false;
  8294. this.options = options;
  8295. initStrophePlugins(this);
  8296. // registerListeners();
  8297. this.connection = createConnection(options.bosh);
  8298. }
  8299. XMPP.prototype.getConnection = function(){ return connection; };
  8300. XMPP.prototype._connect = function (jid, password) {
  8301. var self = this;
  8302. // connection.connect() starts the connection process.
  8303. //
  8304. // As the connection process proceeds, the user supplied callback will
  8305. // be triggered multiple times with status updates. The callback should
  8306. // take two arguments - the status code and the error condition.
  8307. //
  8308. // The status code will be one of the values in the Strophe.Status
  8309. // constants. The error condition will be one of the conditions defined
  8310. // in RFC 3920 or the condition ‘strophe-parsererror’.
  8311. //
  8312. // The Parameters wait, hold and route are optional and only relevant
  8313. // for BOSH connections. Please see XEP 124 for a more detailed
  8314. // explanation of the optional parameters.
  8315. //
  8316. // Connection status constants for use by the connection handler
  8317. // callback.
  8318. //
  8319. // Status.ERROR - An error has occurred (websockets specific)
  8320. // Status.CONNECTING - The connection is currently being made
  8321. // Status.CONNFAIL - The connection attempt failed
  8322. // Status.AUTHENTICATING - The connection is authenticating
  8323. // Status.AUTHFAIL - The authentication attempt failed
  8324. // Status.CONNECTED - The connection has succeeded
  8325. // Status.DISCONNECTED - The connection has been terminated
  8326. // Status.DISCONNECTING - The connection is currently being terminated
  8327. // Status.ATTACHED - The connection has been attached
  8328. var anonymousConnectionFailed = false;
  8329. var connectionFailed = false;
  8330. var lastErrorMsg;
  8331. this.connection.connect(jid, password, function (status, msg) {
  8332. console.log('Strophe status changed to',
  8333. Strophe.getStatusString(status), msg);
  8334. if (status === Strophe.Status.CONNECTED) {
  8335. if (self.options.useStunTurn) {
  8336. self.connection.jingle.getStunAndTurnCredentials();
  8337. }
  8338. console.info("My Jabber ID: " + self.connection.jid);
  8339. if (password)
  8340. authenticatedUser = true;
  8341. if (self.connection && self.connection.connected &&
  8342. Strophe.getResourceFromJid(self.connection.jid)) {
  8343. // .connected is true while connecting?
  8344. // self.connection.send($pres());
  8345. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  8346. Strophe.getResourceFromJid(self.connection.jid));
  8347. }
  8348. } else if (status === Strophe.Status.CONNFAIL) {
  8349. if (msg === 'x-strophe-bad-non-anon-jid') {
  8350. anonymousConnectionFailed = true;
  8351. }
  8352. else
  8353. {
  8354. connectionFailed = true;
  8355. }
  8356. lastErrorMsg = msg;
  8357. } else if (status === Strophe.Status.DISCONNECTED) {
  8358. self.disconnectInProgress = false;
  8359. if (anonymousConnectionFailed) {
  8360. // prompt user for username and password
  8361. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  8362. JitsiConnectionErrors.PASSWORD_REQUIRED);
  8363. } else if(connectionFailed) {
  8364. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  8365. JitsiConnectionErrors.OTHER_ERROR,
  8366. msg ? msg : lastErrorMsg);
  8367. } else {
  8368. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  8369. msg ? msg : lastErrorMsg);
  8370. }
  8371. } else if (status === Strophe.Status.AUTHFAIL) {
  8372. // wrong password or username, prompt user
  8373. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  8374. JitsiConnectionErrors.PASSWORD_REQUIRED);
  8375. }
  8376. });
  8377. }
  8378. XMPP.prototype.connect = function (jid, password) {
  8379. if(!jid) {
  8380. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  8381. // Force authenticated domain if room is appended with '?login=true'
  8382. if (this.options.hosts.anonymousdomain &&
  8383. window.location.search.indexOf("login=true") !== -1) {
  8384. configDomain = this.options.hosts.domain;
  8385. }
  8386. jid = configDomain || window.location.hostname;
  8387. }
  8388. return this._connect(jid, password);
  8389. };
  8390. XMPP.prototype.createRoom = function (roomName, options, useNicks, nick) {
  8391. var roomjid = roomName + '@' + this.options.hosts.muc;
  8392. if (useNicks) {
  8393. if (nick) {
  8394. roomjid += '/' + nick;
  8395. } else {
  8396. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  8397. }
  8398. } else {
  8399. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  8400. if(!authenticatedUser)
  8401. tmpJid = tmpJid.substr(0, 8);
  8402. roomjid += '/' + tmpJid;
  8403. }
  8404. return this.connection.emuc.createRoom(roomjid, null, options);
  8405. }
  8406. XMPP.prototype.addListener = function(type, listener) {
  8407. this.eventEmitter.on(type, listener);
  8408. };
  8409. XMPP.prototype.removeListener = function (type, listener) {
  8410. this.eventEmitter.removeListener(type, listener);
  8411. };
  8412. //FIXME: this should work with the room
  8413. XMPP.prototype.leaveRoom = function (jid) {
  8414. var handler = this.connection.jingle.jid2session[jid];
  8415. if (handler && handler.peerconnection) {
  8416. // FIXME: probably removing streams is not required and close() should
  8417. // be enough
  8418. if (RTC.localAudio) {
  8419. handler.peerconnection.removeStream(
  8420. RTC.localAudio.getOriginalStream(), true);
  8421. }
  8422. if (RTC.localVideo) {
  8423. handler.peerconnection.removeStream(
  8424. RTC.localVideo.getOriginalStream(), true);
  8425. }
  8426. handler.peerconnection.close();
  8427. }
  8428. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  8429. this.connection.emuc.doLeave(jid);
  8430. };
  8431. /**
  8432. * Sends 'data' as a log message to the focus. Returns true iff a message
  8433. * was sent.
  8434. * @param data
  8435. * @returns {boolean} true iff a message was sent.
  8436. */
  8437. XMPP.prototype.sendLogs = function (data) {
  8438. if(!this.connection.emuc.focusMucJid)
  8439. return false;
  8440. var deflate = true;
  8441. var content = JSON.stringify(data);
  8442. if (deflate) {
  8443. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  8444. }
  8445. content = Base64.encode(content);
  8446. // XEP-0337-ish
  8447. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  8448. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  8449. id: 'PeerConnectionStats'});
  8450. message.c('message').t(content).up();
  8451. if (deflate) {
  8452. message.c('tag', {name: "deflated", value: "true"}).up();
  8453. }
  8454. message.up();
  8455. this.connection.send(message);
  8456. return true;
  8457. };
  8458. // Gets the logs from strophe.jingle.
  8459. XMPP.prototype.getJingleLog = function () {
  8460. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  8461. };
  8462. // Gets the logs from strophe.
  8463. XMPP.prototype.getXmppLog = function () {
  8464. return this.connection.logger ? this.connection.logger.log : null;
  8465. };
  8466. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  8467. this.connection.rayo.dial(to, from, roomName,roomPass);
  8468. };
  8469. XMPP.prototype.setMute = function (jid, mute) {
  8470. this.connection.moderate.setMute(jid, mute);
  8471. };
  8472. XMPP.prototype.eject = function (jid) {
  8473. this.connection.moderate.eject(jid);
  8474. };
  8475. XMPP.prototype.getJidFromSSRC = function (ssrc) {
  8476. if (!this.isConferenceInProgress())
  8477. return null;
  8478. return this.connection.jingle.activecall.getSsrcOwner(ssrc);
  8479. };
  8480. XMPP.prototype.getSessions = function () {
  8481. return this.connection.jingle.sessions;
  8482. };
  8483. XMPP.prototype.disconnect = function () {
  8484. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  8485. {
  8486. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  8487. return;
  8488. }
  8489. this.disconnectInProgress = true;
  8490. this.connection.disconnect();
  8491. };
  8492. module.exports = XMPP;
  8493. },{"../../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){
  8494. (function (process){
  8495. /*!
  8496. * async
  8497. * https://github.com/caolan/async
  8498. *
  8499. * Copyright 2010-2014 Caolan McMahon
  8500. * Released under the MIT license
  8501. */
  8502. /*jshint onevar: false, indent:4 */
  8503. /*global setImmediate: false, setTimeout: false, console: false */
  8504. (function () {
  8505. var async = {};
  8506. // global on the server, window in the browser
  8507. var root, previous_async;
  8508. root = this;
  8509. if (root != null) {
  8510. previous_async = root.async;
  8511. }
  8512. async.noConflict = function () {
  8513. root.async = previous_async;
  8514. return async;
  8515. };
  8516. function only_once(fn) {
  8517. var called = false;
  8518. return function() {
  8519. if (called) throw new Error("Callback was already called.");
  8520. called = true;
  8521. fn.apply(root, arguments);
  8522. }
  8523. }
  8524. //// cross-browser compatiblity functions ////
  8525. var _toString = Object.prototype.toString;
  8526. var _isArray = Array.isArray || function (obj) {
  8527. return _toString.call(obj) === '[object Array]';
  8528. };
  8529. var _each = function (arr, iterator) {
  8530. if (arr.forEach) {
  8531. return arr.forEach(iterator);
  8532. }
  8533. for (var i = 0; i < arr.length; i += 1) {
  8534. iterator(arr[i], i, arr);
  8535. }
  8536. };
  8537. var _map = function (arr, iterator) {
  8538. if (arr.map) {
  8539. return arr.map(iterator);
  8540. }
  8541. var results = [];
  8542. _each(arr, function (x, i, a) {
  8543. results.push(iterator(x, i, a));
  8544. });
  8545. return results;
  8546. };
  8547. var _reduce = function (arr, iterator, memo) {
  8548. if (arr.reduce) {
  8549. return arr.reduce(iterator, memo);
  8550. }
  8551. _each(arr, function (x, i, a) {
  8552. memo = iterator(memo, x, i, a);
  8553. });
  8554. return memo;
  8555. };
  8556. var _keys = function (obj) {
  8557. if (Object.keys) {
  8558. return Object.keys(obj);
  8559. }
  8560. var keys = [];
  8561. for (var k in obj) {
  8562. if (obj.hasOwnProperty(k)) {
  8563. keys.push(k);
  8564. }
  8565. }
  8566. return keys;
  8567. };
  8568. //// exported async module functions ////
  8569. //// nextTick implementation with browser-compatible fallback ////
  8570. if (typeof process === 'undefined' || !(process.nextTick)) {
  8571. if (typeof setImmediate === 'function') {
  8572. async.nextTick = function (fn) {
  8573. // not a direct alias for IE10 compatibility
  8574. setImmediate(fn);
  8575. };
  8576. async.setImmediate = async.nextTick;
  8577. }
  8578. else {
  8579. async.nextTick = function (fn) {
  8580. setTimeout(fn, 0);
  8581. };
  8582. async.setImmediate = async.nextTick;
  8583. }
  8584. }
  8585. else {
  8586. async.nextTick = process.nextTick;
  8587. if (typeof setImmediate !== 'undefined') {
  8588. async.setImmediate = function (fn) {
  8589. // not a direct alias for IE10 compatibility
  8590. setImmediate(fn);
  8591. };
  8592. }
  8593. else {
  8594. async.setImmediate = async.nextTick;
  8595. }
  8596. }
  8597. async.each = function (arr, iterator, callback) {
  8598. callback = callback || function () {};
  8599. if (!arr.length) {
  8600. return callback();
  8601. }
  8602. var completed = 0;
  8603. _each(arr, function (x) {
  8604. iterator(x, only_once(done) );
  8605. });
  8606. function done(err) {
  8607. if (err) {
  8608. callback(err);
  8609. callback = function () {};
  8610. }
  8611. else {
  8612. completed += 1;
  8613. if (completed >= arr.length) {
  8614. callback();
  8615. }
  8616. }
  8617. }
  8618. };
  8619. async.forEach = async.each;
  8620. async.eachSeries = function (arr, iterator, callback) {
  8621. callback = callback || function () {};
  8622. if (!arr.length) {
  8623. return callback();
  8624. }
  8625. var completed = 0;
  8626. var iterate = function () {
  8627. iterator(arr[completed], function (err) {
  8628. if (err) {
  8629. callback(err);
  8630. callback = function () {};
  8631. }
  8632. else {
  8633. completed += 1;
  8634. if (completed >= arr.length) {
  8635. callback();
  8636. }
  8637. else {
  8638. iterate();
  8639. }
  8640. }
  8641. });
  8642. };
  8643. iterate();
  8644. };
  8645. async.forEachSeries = async.eachSeries;
  8646. async.eachLimit = function (arr, limit, iterator, callback) {
  8647. var fn = _eachLimit(limit);
  8648. fn.apply(null, [arr, iterator, callback]);
  8649. };
  8650. async.forEachLimit = async.eachLimit;
  8651. var _eachLimit = function (limit) {
  8652. return function (arr, iterator, callback) {
  8653. callback = callback || function () {};
  8654. if (!arr.length || limit <= 0) {
  8655. return callback();
  8656. }
  8657. var completed = 0;
  8658. var started = 0;
  8659. var running = 0;
  8660. (function replenish () {
  8661. if (completed >= arr.length) {
  8662. return callback();
  8663. }
  8664. while (running < limit && started < arr.length) {
  8665. started += 1;
  8666. running += 1;
  8667. iterator(arr[started - 1], function (err) {
  8668. if (err) {
  8669. callback(err);
  8670. callback = function () {};
  8671. }
  8672. else {
  8673. completed += 1;
  8674. running -= 1;
  8675. if (completed >= arr.length) {
  8676. callback();
  8677. }
  8678. else {
  8679. replenish();
  8680. }
  8681. }
  8682. });
  8683. }
  8684. })();
  8685. };
  8686. };
  8687. var doParallel = function (fn) {
  8688. return function () {
  8689. var args = Array.prototype.slice.call(arguments);
  8690. return fn.apply(null, [async.each].concat(args));
  8691. };
  8692. };
  8693. var doParallelLimit = function(limit, fn) {
  8694. return function () {
  8695. var args = Array.prototype.slice.call(arguments);
  8696. return fn.apply(null, [_eachLimit(limit)].concat(args));
  8697. };
  8698. };
  8699. var doSeries = function (fn) {
  8700. return function () {
  8701. var args = Array.prototype.slice.call(arguments);
  8702. return fn.apply(null, [async.eachSeries].concat(args));
  8703. };
  8704. };
  8705. var _asyncMap = function (eachfn, arr, iterator, callback) {
  8706. arr = _map(arr, function (x, i) {
  8707. return {index: i, value: x};
  8708. });
  8709. if (!callback) {
  8710. eachfn(arr, function (x, callback) {
  8711. iterator(x.value, function (err) {
  8712. callback(err);
  8713. });
  8714. });
  8715. } else {
  8716. var results = [];
  8717. eachfn(arr, function (x, callback) {
  8718. iterator(x.value, function (err, v) {
  8719. results[x.index] = v;
  8720. callback(err);
  8721. });
  8722. }, function (err) {
  8723. callback(err, results);
  8724. });
  8725. }
  8726. };
  8727. async.map = doParallel(_asyncMap);
  8728. async.mapSeries = doSeries(_asyncMap);
  8729. async.mapLimit = function (arr, limit, iterator, callback) {
  8730. return _mapLimit(limit)(arr, iterator, callback);
  8731. };
  8732. var _mapLimit = function(limit) {
  8733. return doParallelLimit(limit, _asyncMap);
  8734. };
  8735. // reduce only has a series version, as doing reduce in parallel won't
  8736. // work in many situations.
  8737. async.reduce = function (arr, memo, iterator, callback) {
  8738. async.eachSeries(arr, function (x, callback) {
  8739. iterator(memo, x, function (err, v) {
  8740. memo = v;
  8741. callback(err);
  8742. });
  8743. }, function (err) {
  8744. callback(err, memo);
  8745. });
  8746. };
  8747. // inject alias
  8748. async.inject = async.reduce;
  8749. // foldl alias
  8750. async.foldl = async.reduce;
  8751. async.reduceRight = function (arr, memo, iterator, callback) {
  8752. var reversed = _map(arr, function (x) {
  8753. return x;
  8754. }).reverse();
  8755. async.reduce(reversed, memo, iterator, callback);
  8756. };
  8757. // foldr alias
  8758. async.foldr = async.reduceRight;
  8759. var _filter = function (eachfn, arr, iterator, callback) {
  8760. var results = [];
  8761. arr = _map(arr, function (x, i) {
  8762. return {index: i, value: x};
  8763. });
  8764. eachfn(arr, function (x, callback) {
  8765. iterator(x.value, function (v) {
  8766. if (v) {
  8767. results.push(x);
  8768. }
  8769. callback();
  8770. });
  8771. }, function (err) {
  8772. callback(_map(results.sort(function (a, b) {
  8773. return a.index - b.index;
  8774. }), function (x) {
  8775. return x.value;
  8776. }));
  8777. });
  8778. };
  8779. async.filter = doParallel(_filter);
  8780. async.filterSeries = doSeries(_filter);
  8781. // select alias
  8782. async.select = async.filter;
  8783. async.selectSeries = async.filterSeries;
  8784. var _reject = function (eachfn, arr, iterator, callback) {
  8785. var results = [];
  8786. arr = _map(arr, function (x, i) {
  8787. return {index: i, value: x};
  8788. });
  8789. eachfn(arr, function (x, callback) {
  8790. iterator(x.value, function (v) {
  8791. if (!v) {
  8792. results.push(x);
  8793. }
  8794. callback();
  8795. });
  8796. }, function (err) {
  8797. callback(_map(results.sort(function (a, b) {
  8798. return a.index - b.index;
  8799. }), function (x) {
  8800. return x.value;
  8801. }));
  8802. });
  8803. };
  8804. async.reject = doParallel(_reject);
  8805. async.rejectSeries = doSeries(_reject);
  8806. var _detect = function (eachfn, arr, iterator, main_callback) {
  8807. eachfn(arr, function (x, callback) {
  8808. iterator(x, function (result) {
  8809. if (result) {
  8810. main_callback(x);
  8811. main_callback = function () {};
  8812. }
  8813. else {
  8814. callback();
  8815. }
  8816. });
  8817. }, function (err) {
  8818. main_callback();
  8819. });
  8820. };
  8821. async.detect = doParallel(_detect);
  8822. async.detectSeries = doSeries(_detect);
  8823. async.some = function (arr, iterator, main_callback) {
  8824. async.each(arr, function (x, callback) {
  8825. iterator(x, function (v) {
  8826. if (v) {
  8827. main_callback(true);
  8828. main_callback = function () {};
  8829. }
  8830. callback();
  8831. });
  8832. }, function (err) {
  8833. main_callback(false);
  8834. });
  8835. };
  8836. // any alias
  8837. async.any = async.some;
  8838. async.every = function (arr, iterator, main_callback) {
  8839. async.each(arr, function (x, callback) {
  8840. iterator(x, function (v) {
  8841. if (!v) {
  8842. main_callback(false);
  8843. main_callback = function () {};
  8844. }
  8845. callback();
  8846. });
  8847. }, function (err) {
  8848. main_callback(true);
  8849. });
  8850. };
  8851. // all alias
  8852. async.all = async.every;
  8853. async.sortBy = function (arr, iterator, callback) {
  8854. async.map(arr, function (x, callback) {
  8855. iterator(x, function (err, criteria) {
  8856. if (err) {
  8857. callback(err);
  8858. }
  8859. else {
  8860. callback(null, {value: x, criteria: criteria});
  8861. }
  8862. });
  8863. }, function (err, results) {
  8864. if (err) {
  8865. return callback(err);
  8866. }
  8867. else {
  8868. var fn = function (left, right) {
  8869. var a = left.criteria, b = right.criteria;
  8870. return a < b ? -1 : a > b ? 1 : 0;
  8871. };
  8872. callback(null, _map(results.sort(fn), function (x) {
  8873. return x.value;
  8874. }));
  8875. }
  8876. });
  8877. };
  8878. async.auto = function (tasks, callback) {
  8879. callback = callback || function () {};
  8880. var keys = _keys(tasks);
  8881. var remainingTasks = keys.length
  8882. if (!remainingTasks) {
  8883. return callback();
  8884. }
  8885. var results = {};
  8886. var listeners = [];
  8887. var addListener = function (fn) {
  8888. listeners.unshift(fn);
  8889. };
  8890. var removeListener = function (fn) {
  8891. for (var i = 0; i < listeners.length; i += 1) {
  8892. if (listeners[i] === fn) {
  8893. listeners.splice(i, 1);
  8894. return;
  8895. }
  8896. }
  8897. };
  8898. var taskComplete = function () {
  8899. remainingTasks--
  8900. _each(listeners.slice(0), function (fn) {
  8901. fn();
  8902. });
  8903. };
  8904. addListener(function () {
  8905. if (!remainingTasks) {
  8906. var theCallback = callback;
  8907. // prevent final callback from calling itself if it errors
  8908. callback = function () {};
  8909. theCallback(null, results);
  8910. }
  8911. });
  8912. _each(keys, function (k) {
  8913. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  8914. var taskCallback = function (err) {
  8915. var args = Array.prototype.slice.call(arguments, 1);
  8916. if (args.length <= 1) {
  8917. args = args[0];
  8918. }
  8919. if (err) {
  8920. var safeResults = {};
  8921. _each(_keys(results), function(rkey) {
  8922. safeResults[rkey] = results[rkey];
  8923. });
  8924. safeResults[k] = args;
  8925. callback(err, safeResults);
  8926. // stop subsequent errors hitting callback multiple times
  8927. callback = function () {};
  8928. }
  8929. else {
  8930. results[k] = args;
  8931. async.setImmediate(taskComplete);
  8932. }
  8933. };
  8934. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  8935. var ready = function () {
  8936. return _reduce(requires, function (a, x) {
  8937. return (a && results.hasOwnProperty(x));
  8938. }, true) && !results.hasOwnProperty(k);
  8939. };
  8940. if (ready()) {
  8941. task[task.length - 1](taskCallback, results);
  8942. }
  8943. else {
  8944. var listener = function () {
  8945. if (ready()) {
  8946. removeListener(listener);
  8947. task[task.length - 1](taskCallback, results);
  8948. }
  8949. };
  8950. addListener(listener);
  8951. }
  8952. });
  8953. };
  8954. async.retry = function(times, task, callback) {
  8955. var DEFAULT_TIMES = 5;
  8956. var attempts = [];
  8957. // Use defaults if times not passed
  8958. if (typeof times === 'function') {
  8959. callback = task;
  8960. task = times;
  8961. times = DEFAULT_TIMES;
  8962. }
  8963. // Make sure times is a number
  8964. times = parseInt(times, 10) || DEFAULT_TIMES;
  8965. var wrappedTask = function(wrappedCallback, wrappedResults) {
  8966. var retryAttempt = function(task, finalAttempt) {
  8967. return function(seriesCallback) {
  8968. task(function(err, result){
  8969. seriesCallback(!err || finalAttempt, {err: err, result: result});
  8970. }, wrappedResults);
  8971. };
  8972. };
  8973. while (times) {
  8974. attempts.push(retryAttempt(task, !(times-=1)));
  8975. }
  8976. async.series(attempts, function(done, data){
  8977. data = data[data.length - 1];
  8978. (wrappedCallback || callback)(data.err, data.result);
  8979. });
  8980. }
  8981. // If a callback is passed, run this as a controll flow
  8982. return callback ? wrappedTask() : wrappedTask
  8983. };
  8984. async.waterfall = function (tasks, callback) {
  8985. callback = callback || function () {};
  8986. if (!_isArray(tasks)) {
  8987. var err = new Error('First argument to waterfall must be an array of functions');
  8988. return callback(err);
  8989. }
  8990. if (!tasks.length) {
  8991. return callback();
  8992. }
  8993. var wrapIterator = function (iterator) {
  8994. return function (err) {
  8995. if (err) {
  8996. callback.apply(null, arguments);
  8997. callback = function () {};
  8998. }
  8999. else {
  9000. var args = Array.prototype.slice.call(arguments, 1);
  9001. var next = iterator.next();
  9002. if (next) {
  9003. args.push(wrapIterator(next));
  9004. }
  9005. else {
  9006. args.push(callback);
  9007. }
  9008. async.setImmediate(function () {
  9009. iterator.apply(null, args);
  9010. });
  9011. }
  9012. };
  9013. };
  9014. wrapIterator(async.iterator(tasks))();
  9015. };
  9016. var _parallel = function(eachfn, tasks, callback) {
  9017. callback = callback || function () {};
  9018. if (_isArray(tasks)) {
  9019. eachfn.map(tasks, function (fn, callback) {
  9020. if (fn) {
  9021. fn(function (err) {
  9022. var args = Array.prototype.slice.call(arguments, 1);
  9023. if (args.length <= 1) {
  9024. args = args[0];
  9025. }
  9026. callback.call(null, err, args);
  9027. });
  9028. }
  9029. }, callback);
  9030. }
  9031. else {
  9032. var results = {};
  9033. eachfn.each(_keys(tasks), function (k, callback) {
  9034. tasks[k](function (err) {
  9035. var args = Array.prototype.slice.call(arguments, 1);
  9036. if (args.length <= 1) {
  9037. args = args[0];
  9038. }
  9039. results[k] = args;
  9040. callback(err);
  9041. });
  9042. }, function (err) {
  9043. callback(err, results);
  9044. });
  9045. }
  9046. };
  9047. async.parallel = function (tasks, callback) {
  9048. _parallel({ map: async.map, each: async.each }, tasks, callback);
  9049. };
  9050. async.parallelLimit = function(tasks, limit, callback) {
  9051. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  9052. };
  9053. async.series = function (tasks, callback) {
  9054. callback = callback || function () {};
  9055. if (_isArray(tasks)) {
  9056. async.mapSeries(tasks, function (fn, callback) {
  9057. if (fn) {
  9058. fn(function (err) {
  9059. var args = Array.prototype.slice.call(arguments, 1);
  9060. if (args.length <= 1) {
  9061. args = args[0];
  9062. }
  9063. callback.call(null, err, args);
  9064. });
  9065. }
  9066. }, callback);
  9067. }
  9068. else {
  9069. var results = {};
  9070. async.eachSeries(_keys(tasks), function (k, callback) {
  9071. tasks[k](function (err) {
  9072. var args = Array.prototype.slice.call(arguments, 1);
  9073. if (args.length <= 1) {
  9074. args = args[0];
  9075. }
  9076. results[k] = args;
  9077. callback(err);
  9078. });
  9079. }, function (err) {
  9080. callback(err, results);
  9081. });
  9082. }
  9083. };
  9084. async.iterator = function (tasks) {
  9085. var makeCallback = function (index) {
  9086. var fn = function () {
  9087. if (tasks.length) {
  9088. tasks[index].apply(null, arguments);
  9089. }
  9090. return fn.next();
  9091. };
  9092. fn.next = function () {
  9093. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  9094. };
  9095. return fn;
  9096. };
  9097. return makeCallback(0);
  9098. };
  9099. async.apply = function (fn) {
  9100. var args = Array.prototype.slice.call(arguments, 1);
  9101. return function () {
  9102. return fn.apply(
  9103. null, args.concat(Array.prototype.slice.call(arguments))
  9104. );
  9105. };
  9106. };
  9107. var _concat = function (eachfn, arr, fn, callback) {
  9108. var r = [];
  9109. eachfn(arr, function (x, cb) {
  9110. fn(x, function (err, y) {
  9111. r = r.concat(y || []);
  9112. cb(err);
  9113. });
  9114. }, function (err) {
  9115. callback(err, r);
  9116. });
  9117. };
  9118. async.concat = doParallel(_concat);
  9119. async.concatSeries = doSeries(_concat);
  9120. async.whilst = function (test, iterator, callback) {
  9121. if (test()) {
  9122. iterator(function (err) {
  9123. if (err) {
  9124. return callback(err);
  9125. }
  9126. async.whilst(test, iterator, callback);
  9127. });
  9128. }
  9129. else {
  9130. callback();
  9131. }
  9132. };
  9133. async.doWhilst = function (iterator, test, callback) {
  9134. iterator(function (err) {
  9135. if (err) {
  9136. return callback(err);
  9137. }
  9138. var args = Array.prototype.slice.call(arguments, 1);
  9139. if (test.apply(null, args)) {
  9140. async.doWhilst(iterator, test, callback);
  9141. }
  9142. else {
  9143. callback();
  9144. }
  9145. });
  9146. };
  9147. async.until = function (test, iterator, callback) {
  9148. if (!test()) {
  9149. iterator(function (err) {
  9150. if (err) {
  9151. return callback(err);
  9152. }
  9153. async.until(test, iterator, callback);
  9154. });
  9155. }
  9156. else {
  9157. callback();
  9158. }
  9159. };
  9160. async.doUntil = function (iterator, test, callback) {
  9161. iterator(function (err) {
  9162. if (err) {
  9163. return callback(err);
  9164. }
  9165. var args = Array.prototype.slice.call(arguments, 1);
  9166. if (!test.apply(null, args)) {
  9167. async.doUntil(iterator, test, callback);
  9168. }
  9169. else {
  9170. callback();
  9171. }
  9172. });
  9173. };
  9174. async.queue = function (worker, concurrency) {
  9175. if (concurrency === undefined) {
  9176. concurrency = 1;
  9177. }
  9178. function _insert(q, data, pos, callback) {
  9179. if (!q.started){
  9180. q.started = true;
  9181. }
  9182. if (!_isArray(data)) {
  9183. data = [data];
  9184. }
  9185. if(data.length == 0) {
  9186. // call drain immediately if there are no tasks
  9187. return async.setImmediate(function() {
  9188. if (q.drain) {
  9189. q.drain();
  9190. }
  9191. });
  9192. }
  9193. _each(data, function(task) {
  9194. var item = {
  9195. data: task,
  9196. callback: typeof callback === 'function' ? callback : null
  9197. };
  9198. if (pos) {
  9199. q.tasks.unshift(item);
  9200. } else {
  9201. q.tasks.push(item);
  9202. }
  9203. if (q.saturated && q.tasks.length === q.concurrency) {
  9204. q.saturated();
  9205. }
  9206. async.setImmediate(q.process);
  9207. });
  9208. }
  9209. var workers = 0;
  9210. var q = {
  9211. tasks: [],
  9212. concurrency: concurrency,
  9213. saturated: null,
  9214. empty: null,
  9215. drain: null,
  9216. started: false,
  9217. paused: false,
  9218. push: function (data, callback) {
  9219. _insert(q, data, false, callback);
  9220. },
  9221. kill: function () {
  9222. q.drain = null;
  9223. q.tasks = [];
  9224. },
  9225. unshift: function (data, callback) {
  9226. _insert(q, data, true, callback);
  9227. },
  9228. process: function () {
  9229. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  9230. var task = q.tasks.shift();
  9231. if (q.empty && q.tasks.length === 0) {
  9232. q.empty();
  9233. }
  9234. workers += 1;
  9235. var next = function () {
  9236. workers -= 1;
  9237. if (task.callback) {
  9238. task.callback.apply(task, arguments);
  9239. }
  9240. if (q.drain && q.tasks.length + workers === 0) {
  9241. q.drain();
  9242. }
  9243. q.process();
  9244. };
  9245. var cb = only_once(next);
  9246. worker(task.data, cb);
  9247. }
  9248. },
  9249. length: function () {
  9250. return q.tasks.length;
  9251. },
  9252. running: function () {
  9253. return workers;
  9254. },
  9255. idle: function() {
  9256. return q.tasks.length + workers === 0;
  9257. },
  9258. pause: function () {
  9259. if (q.paused === true) { return; }
  9260. q.paused = true;
  9261. q.process();
  9262. },
  9263. resume: function () {
  9264. if (q.paused === false) { return; }
  9265. q.paused = false;
  9266. q.process();
  9267. }
  9268. };
  9269. return q;
  9270. };
  9271. async.priorityQueue = function (worker, concurrency) {
  9272. function _compareTasks(a, b){
  9273. return a.priority - b.priority;
  9274. };
  9275. function _binarySearch(sequence, item, compare) {
  9276. var beg = -1,
  9277. end = sequence.length - 1;
  9278. while (beg < end) {
  9279. var mid = beg + ((end - beg + 1) >>> 1);
  9280. if (compare(item, sequence[mid]) >= 0) {
  9281. beg = mid;
  9282. } else {
  9283. end = mid - 1;
  9284. }
  9285. }
  9286. return beg;
  9287. }
  9288. function _insert(q, data, priority, callback) {
  9289. if (!q.started){
  9290. q.started = true;
  9291. }
  9292. if (!_isArray(data)) {
  9293. data = [data];
  9294. }
  9295. if(data.length == 0) {
  9296. // call drain immediately if there are no tasks
  9297. return async.setImmediate(function() {
  9298. if (q.drain) {
  9299. q.drain();
  9300. }
  9301. });
  9302. }
  9303. _each(data, function(task) {
  9304. var item = {
  9305. data: task,
  9306. priority: priority,
  9307. callback: typeof callback === 'function' ? callback : null
  9308. };
  9309. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  9310. if (q.saturated && q.tasks.length === q.concurrency) {
  9311. q.saturated();
  9312. }
  9313. async.setImmediate(q.process);
  9314. });
  9315. }
  9316. // Start with a normal queue
  9317. var q = async.queue(worker, concurrency);
  9318. // Override push to accept second parameter representing priority
  9319. q.push = function (data, priority, callback) {
  9320. _insert(q, data, priority, callback);
  9321. };
  9322. // Remove unshift function
  9323. delete q.unshift;
  9324. return q;
  9325. };
  9326. async.cargo = function (worker, payload) {
  9327. var working = false,
  9328. tasks = [];
  9329. var cargo = {
  9330. tasks: tasks,
  9331. payload: payload,
  9332. saturated: null,
  9333. empty: null,
  9334. drain: null,
  9335. drained: true,
  9336. push: function (data, callback) {
  9337. if (!_isArray(data)) {
  9338. data = [data];
  9339. }
  9340. _each(data, function(task) {
  9341. tasks.push({
  9342. data: task,
  9343. callback: typeof callback === 'function' ? callback : null
  9344. });
  9345. cargo.drained = false;
  9346. if (cargo.saturated && tasks.length === payload) {
  9347. cargo.saturated();
  9348. }
  9349. });
  9350. async.setImmediate(cargo.process);
  9351. },
  9352. process: function process() {
  9353. if (working) return;
  9354. if (tasks.length === 0) {
  9355. if(cargo.drain && !cargo.drained) cargo.drain();
  9356. cargo.drained = true;
  9357. return;
  9358. }
  9359. var ts = typeof payload === 'number'
  9360. ? tasks.splice(0, payload)
  9361. : tasks.splice(0, tasks.length);
  9362. var ds = _map(ts, function (task) {
  9363. return task.data;
  9364. });
  9365. if(cargo.empty) cargo.empty();
  9366. working = true;
  9367. worker(ds, function () {
  9368. working = false;
  9369. var args = arguments;
  9370. _each(ts, function (data) {
  9371. if (data.callback) {
  9372. data.callback.apply(null, args);
  9373. }
  9374. });
  9375. process();
  9376. });
  9377. },
  9378. length: function () {
  9379. return tasks.length;
  9380. },
  9381. running: function () {
  9382. return working;
  9383. }
  9384. };
  9385. return cargo;
  9386. };
  9387. var _console_fn = function (name) {
  9388. return function (fn) {
  9389. var args = Array.prototype.slice.call(arguments, 1);
  9390. fn.apply(null, args.concat([function (err) {
  9391. var args = Array.prototype.slice.call(arguments, 1);
  9392. if (typeof console !== 'undefined') {
  9393. if (err) {
  9394. if (console.error) {
  9395. console.error(err);
  9396. }
  9397. }
  9398. else if (console[name]) {
  9399. _each(args, function (x) {
  9400. console[name](x);
  9401. });
  9402. }
  9403. }
  9404. }]));
  9405. };
  9406. };
  9407. async.log = _console_fn('log');
  9408. async.dir = _console_fn('dir');
  9409. /*async.info = _console_fn('info');
  9410. async.warn = _console_fn('warn');
  9411. async.error = _console_fn('error');*/
  9412. async.memoize = function (fn, hasher) {
  9413. var memo = {};
  9414. var queues = {};
  9415. hasher = hasher || function (x) {
  9416. return x;
  9417. };
  9418. var memoized = function () {
  9419. var args = Array.prototype.slice.call(arguments);
  9420. var callback = args.pop();
  9421. var key = hasher.apply(null, args);
  9422. if (key in memo) {
  9423. async.nextTick(function () {
  9424. callback.apply(null, memo[key]);
  9425. });
  9426. }
  9427. else if (key in queues) {
  9428. queues[key].push(callback);
  9429. }
  9430. else {
  9431. queues[key] = [callback];
  9432. fn.apply(null, args.concat([function () {
  9433. memo[key] = arguments;
  9434. var q = queues[key];
  9435. delete queues[key];
  9436. for (var i = 0, l = q.length; i < l; i++) {
  9437. q[i].apply(null, arguments);
  9438. }
  9439. }]));
  9440. }
  9441. };
  9442. memoized.memo = memo;
  9443. memoized.unmemoized = fn;
  9444. return memoized;
  9445. };
  9446. async.unmemoize = function (fn) {
  9447. return function () {
  9448. return (fn.unmemoized || fn).apply(null, arguments);
  9449. };
  9450. };
  9451. async.times = function (count, iterator, callback) {
  9452. var counter = [];
  9453. for (var i = 0; i < count; i++) {
  9454. counter.push(i);
  9455. }
  9456. return async.map(counter, iterator, callback);
  9457. };
  9458. async.timesSeries = function (count, iterator, callback) {
  9459. var counter = [];
  9460. for (var i = 0; i < count; i++) {
  9461. counter.push(i);
  9462. }
  9463. return async.mapSeries(counter, iterator, callback);
  9464. };
  9465. async.seq = function (/* functions... */) {
  9466. var fns = arguments;
  9467. return function () {
  9468. var that = this;
  9469. var args = Array.prototype.slice.call(arguments);
  9470. var callback = args.pop();
  9471. async.reduce(fns, args, function (newargs, fn, cb) {
  9472. fn.apply(that, newargs.concat([function () {
  9473. var err = arguments[0];
  9474. var nextargs = Array.prototype.slice.call(arguments, 1);
  9475. cb(err, nextargs);
  9476. }]))
  9477. },
  9478. function (err, results) {
  9479. callback.apply(that, [err].concat(results));
  9480. });
  9481. };
  9482. };
  9483. async.compose = function (/* functions... */) {
  9484. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  9485. };
  9486. var _applyEach = function (eachfn, fns /*args...*/) {
  9487. var go = function () {
  9488. var that = this;
  9489. var args = Array.prototype.slice.call(arguments);
  9490. var callback = args.pop();
  9491. return eachfn(fns, function (fn, cb) {
  9492. fn.apply(that, args.concat([cb]));
  9493. },
  9494. callback);
  9495. };
  9496. if (arguments.length > 2) {
  9497. var args = Array.prototype.slice.call(arguments, 2);
  9498. return go.apply(this, args);
  9499. }
  9500. else {
  9501. return go;
  9502. }
  9503. };
  9504. async.applyEach = doParallel(_applyEach);
  9505. async.applyEachSeries = doSeries(_applyEach);
  9506. async.forever = function (fn, callback) {
  9507. function next(err) {
  9508. if (err) {
  9509. if (callback) {
  9510. return callback(err);
  9511. }
  9512. throw err;
  9513. }
  9514. fn(next);
  9515. }
  9516. next();
  9517. };
  9518. // Node.js
  9519. if (typeof module !== 'undefined' && module.exports) {
  9520. module.exports = async;
  9521. }
  9522. // AMD / RequireJS
  9523. else if (typeof define !== 'undefined' && define.amd) {
  9524. define([], function () {
  9525. return async;
  9526. });
  9527. }
  9528. // included directly via <script> tag
  9529. else {
  9530. root.async = async;
  9531. }
  9532. }());
  9533. }).call(this,require('_process'))
  9534. },{"_process":78}],35:[function(require,module,exports){
  9535. (function (process,global){
  9536. /*!
  9537. * @overview es6-promise - a tiny implementation of Promises/A+.
  9538. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  9539. * @license Licensed under MIT license
  9540. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  9541. * @version 3.0.2
  9542. */
  9543. (function() {
  9544. "use strict";
  9545. function lib$es6$promise$utils$$objectOrFunction(x) {
  9546. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  9547. }
  9548. function lib$es6$promise$utils$$isFunction(x) {
  9549. return typeof x === 'function';
  9550. }
  9551. function lib$es6$promise$utils$$isMaybeThenable(x) {
  9552. return typeof x === 'object' && x !== null;
  9553. }
  9554. var lib$es6$promise$utils$$_isArray;
  9555. if (!Array.isArray) {
  9556. lib$es6$promise$utils$$_isArray = function (x) {
  9557. return Object.prototype.toString.call(x) === '[object Array]';
  9558. };
  9559. } else {
  9560. lib$es6$promise$utils$$_isArray = Array.isArray;
  9561. }
  9562. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  9563. var lib$es6$promise$asap$$len = 0;
  9564. var lib$es6$promise$asap$$toString = {}.toString;
  9565. var lib$es6$promise$asap$$vertxNext;
  9566. var lib$es6$promise$asap$$customSchedulerFn;
  9567. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  9568. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  9569. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  9570. lib$es6$promise$asap$$len += 2;
  9571. if (lib$es6$promise$asap$$len === 2) {
  9572. // If len is 2, that means that we need to schedule an async flush.
  9573. // If additional callbacks are queued before the queue is flushed, they
  9574. // will be processed by this flush that we are scheduling.
  9575. if (lib$es6$promise$asap$$customSchedulerFn) {
  9576. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  9577. } else {
  9578. lib$es6$promise$asap$$scheduleFlush();
  9579. }
  9580. }
  9581. }
  9582. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  9583. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  9584. }
  9585. function lib$es6$promise$asap$$setAsap(asapFn) {
  9586. lib$es6$promise$asap$$asap = asapFn;
  9587. }
  9588. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  9589. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  9590. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  9591. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  9592. // test for web worker but not in IE10
  9593. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  9594. typeof importScripts !== 'undefined' &&
  9595. typeof MessageChannel !== 'undefined';
  9596. // node
  9597. function lib$es6$promise$asap$$useNextTick() {
  9598. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  9599. // see https://github.com/cujojs/when/issues/410 for details
  9600. return function() {
  9601. process.nextTick(lib$es6$promise$asap$$flush);
  9602. };
  9603. }
  9604. // vertx
  9605. function lib$es6$promise$asap$$useVertxTimer() {
  9606. return function() {
  9607. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  9608. };
  9609. }
  9610. function lib$es6$promise$asap$$useMutationObserver() {
  9611. var iterations = 0;
  9612. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  9613. var node = document.createTextNode('');
  9614. observer.observe(node, { characterData: true });
  9615. return function() {
  9616. node.data = (iterations = ++iterations % 2);
  9617. };
  9618. }
  9619. // web worker
  9620. function lib$es6$promise$asap$$useMessageChannel() {
  9621. var channel = new MessageChannel();
  9622. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  9623. return function () {
  9624. channel.port2.postMessage(0);
  9625. };
  9626. }
  9627. function lib$es6$promise$asap$$useSetTimeout() {
  9628. return function() {
  9629. setTimeout(lib$es6$promise$asap$$flush, 1);
  9630. };
  9631. }
  9632. var lib$es6$promise$asap$$queue = new Array(1000);
  9633. function lib$es6$promise$asap$$flush() {
  9634. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  9635. var callback = lib$es6$promise$asap$$queue[i];
  9636. var arg = lib$es6$promise$asap$$queue[i+1];
  9637. callback(arg);
  9638. lib$es6$promise$asap$$queue[i] = undefined;
  9639. lib$es6$promise$asap$$queue[i+1] = undefined;
  9640. }
  9641. lib$es6$promise$asap$$len = 0;
  9642. }
  9643. function lib$es6$promise$asap$$attemptVertx() {
  9644. try {
  9645. var r = require;
  9646. var vertx = r('vertx');
  9647. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  9648. return lib$es6$promise$asap$$useVertxTimer();
  9649. } catch(e) {
  9650. return lib$es6$promise$asap$$useSetTimeout();
  9651. }
  9652. }
  9653. var lib$es6$promise$asap$$scheduleFlush;
  9654. // Decide what async method to use to triggering processing of queued callbacks:
  9655. if (lib$es6$promise$asap$$isNode) {
  9656. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  9657. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  9658. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  9659. } else if (lib$es6$promise$asap$$isWorker) {
  9660. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  9661. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  9662. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  9663. } else {
  9664. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  9665. }
  9666. function lib$es6$promise$$internal$$noop() {}
  9667. var lib$es6$promise$$internal$$PENDING = void 0;
  9668. var lib$es6$promise$$internal$$FULFILLED = 1;
  9669. var lib$es6$promise$$internal$$REJECTED = 2;
  9670. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  9671. function lib$es6$promise$$internal$$selfFulfillment() {
  9672. return new TypeError("You cannot resolve a promise with itself");
  9673. }
  9674. function lib$es6$promise$$internal$$cannotReturnOwn() {
  9675. return new TypeError('A promises callback cannot return that same promise.');
  9676. }
  9677. function lib$es6$promise$$internal$$getThen(promise) {
  9678. try {
  9679. return promise.then;
  9680. } catch(error) {
  9681. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  9682. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  9683. }
  9684. }
  9685. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  9686. try {
  9687. then.call(value, fulfillmentHandler, rejectionHandler);
  9688. } catch(e) {
  9689. return e;
  9690. }
  9691. }
  9692. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  9693. lib$es6$promise$asap$$asap(function(promise) {
  9694. var sealed = false;
  9695. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  9696. if (sealed) { return; }
  9697. sealed = true;
  9698. if (thenable !== value) {
  9699. lib$es6$promise$$internal$$resolve(promise, value);
  9700. } else {
  9701. lib$es6$promise$$internal$$fulfill(promise, value);
  9702. }
  9703. }, function(reason) {
  9704. if (sealed) { return; }
  9705. sealed = true;
  9706. lib$es6$promise$$internal$$reject(promise, reason);
  9707. }, 'Settle: ' + (promise._label || ' unknown promise'));
  9708. if (!sealed && error) {
  9709. sealed = true;
  9710. lib$es6$promise$$internal$$reject(promise, error);
  9711. }
  9712. }, promise);
  9713. }
  9714. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  9715. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  9716. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  9717. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  9718. lib$es6$promise$$internal$$reject(promise, thenable._result);
  9719. } else {
  9720. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  9721. lib$es6$promise$$internal$$resolve(promise, value);
  9722. }, function(reason) {
  9723. lib$es6$promise$$internal$$reject(promise, reason);
  9724. });
  9725. }
  9726. }
  9727. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  9728. if (maybeThenable.constructor === promise.constructor) {
  9729. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  9730. } else {
  9731. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  9732. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  9733. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  9734. } else if (then === undefined) {
  9735. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  9736. } else if (lib$es6$promise$utils$$isFunction(then)) {
  9737. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  9738. } else {
  9739. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  9740. }
  9741. }
  9742. }
  9743. function lib$es6$promise$$internal$$resolve(promise, value) {
  9744. if (promise === value) {
  9745. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  9746. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  9747. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  9748. } else {
  9749. lib$es6$promise$$internal$$fulfill(promise, value);
  9750. }
  9751. }
  9752. function lib$es6$promise$$internal$$publishRejection(promise) {
  9753. if (promise._onerror) {
  9754. promise._onerror(promise._result);
  9755. }
  9756. lib$es6$promise$$internal$$publish(promise);
  9757. }
  9758. function lib$es6$promise$$internal$$fulfill(promise, value) {
  9759. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  9760. promise._result = value;
  9761. promise._state = lib$es6$promise$$internal$$FULFILLED;
  9762. if (promise._subscribers.length !== 0) {
  9763. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  9764. }
  9765. }
  9766. function lib$es6$promise$$internal$$reject(promise, reason) {
  9767. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  9768. promise._state = lib$es6$promise$$internal$$REJECTED;
  9769. promise._result = reason;
  9770. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  9771. }
  9772. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  9773. var subscribers = parent._subscribers;
  9774. var length = subscribers.length;
  9775. parent._onerror = null;
  9776. subscribers[length] = child;
  9777. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  9778. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  9779. if (length === 0 && parent._state) {
  9780. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  9781. }
  9782. }
  9783. function lib$es6$promise$$internal$$publish(promise) {
  9784. var subscribers = promise._subscribers;
  9785. var settled = promise._state;
  9786. if (subscribers.length === 0) { return; }
  9787. var child, callback, detail = promise._result;
  9788. for (var i = 0; i < subscribers.length; i += 3) {
  9789. child = subscribers[i];
  9790. callback = subscribers[i + settled];
  9791. if (child) {
  9792. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  9793. } else {
  9794. callback(detail);
  9795. }
  9796. }
  9797. promise._subscribers.length = 0;
  9798. }
  9799. function lib$es6$promise$$internal$$ErrorObject() {
  9800. this.error = null;
  9801. }
  9802. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  9803. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  9804. try {
  9805. return callback(detail);
  9806. } catch(e) {
  9807. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  9808. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  9809. }
  9810. }
  9811. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  9812. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  9813. value, error, succeeded, failed;
  9814. if (hasCallback) {
  9815. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  9816. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  9817. failed = true;
  9818. error = value.error;
  9819. value = null;
  9820. } else {
  9821. succeeded = true;
  9822. }
  9823. if (promise === value) {
  9824. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  9825. return;
  9826. }
  9827. } else {
  9828. value = detail;
  9829. succeeded = true;
  9830. }
  9831. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  9832. // noop
  9833. } else if (hasCallback && succeeded) {
  9834. lib$es6$promise$$internal$$resolve(promise, value);
  9835. } else if (failed) {
  9836. lib$es6$promise$$internal$$reject(promise, error);
  9837. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  9838. lib$es6$promise$$internal$$fulfill(promise, value);
  9839. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  9840. lib$es6$promise$$internal$$reject(promise, value);
  9841. }
  9842. }
  9843. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  9844. try {
  9845. resolver(function resolvePromise(value){
  9846. lib$es6$promise$$internal$$resolve(promise, value);
  9847. }, function rejectPromise(reason) {
  9848. lib$es6$promise$$internal$$reject(promise, reason);
  9849. });
  9850. } catch(e) {
  9851. lib$es6$promise$$internal$$reject(promise, e);
  9852. }
  9853. }
  9854. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  9855. var enumerator = this;
  9856. enumerator._instanceConstructor = Constructor;
  9857. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  9858. if (enumerator._validateInput(input)) {
  9859. enumerator._input = input;
  9860. enumerator.length = input.length;
  9861. enumerator._remaining = input.length;
  9862. enumerator._init();
  9863. if (enumerator.length === 0) {
  9864. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  9865. } else {
  9866. enumerator.length = enumerator.length || 0;
  9867. enumerator._enumerate();
  9868. if (enumerator._remaining === 0) {
  9869. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  9870. }
  9871. }
  9872. } else {
  9873. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  9874. }
  9875. }
  9876. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  9877. return lib$es6$promise$utils$$isArray(input);
  9878. };
  9879. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  9880. return new Error('Array Methods must be provided an Array');
  9881. };
  9882. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  9883. this._result = new Array(this.length);
  9884. };
  9885. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  9886. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  9887. var enumerator = this;
  9888. var length = enumerator.length;
  9889. var promise = enumerator.promise;
  9890. var input = enumerator._input;
  9891. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  9892. enumerator._eachEntry(input[i], i);
  9893. }
  9894. };
  9895. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  9896. var enumerator = this;
  9897. var c = enumerator._instanceConstructor;
  9898. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  9899. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  9900. entry._onerror = null;
  9901. enumerator._settledAt(entry._state, i, entry._result);
  9902. } else {
  9903. enumerator._willSettleAt(c.resolve(entry), i);
  9904. }
  9905. } else {
  9906. enumerator._remaining--;
  9907. enumerator._result[i] = entry;
  9908. }
  9909. };
  9910. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  9911. var enumerator = this;
  9912. var promise = enumerator.promise;
  9913. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  9914. enumerator._remaining--;
  9915. if (state === lib$es6$promise$$internal$$REJECTED) {
  9916. lib$es6$promise$$internal$$reject(promise, value);
  9917. } else {
  9918. enumerator._result[i] = value;
  9919. }
  9920. }
  9921. if (enumerator._remaining === 0) {
  9922. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  9923. }
  9924. };
  9925. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  9926. var enumerator = this;
  9927. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  9928. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  9929. }, function(reason) {
  9930. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  9931. });
  9932. };
  9933. function lib$es6$promise$promise$all$$all(entries) {
  9934. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  9935. }
  9936. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  9937. function lib$es6$promise$promise$race$$race(entries) {
  9938. /*jshint validthis:true */
  9939. var Constructor = this;
  9940. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  9941. if (!lib$es6$promise$utils$$isArray(entries)) {
  9942. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  9943. return promise;
  9944. }
  9945. var length = entries.length;
  9946. function onFulfillment(value) {
  9947. lib$es6$promise$$internal$$resolve(promise, value);
  9948. }
  9949. function onRejection(reason) {
  9950. lib$es6$promise$$internal$$reject(promise, reason);
  9951. }
  9952. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  9953. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  9954. }
  9955. return promise;
  9956. }
  9957. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  9958. function lib$es6$promise$promise$resolve$$resolve(object) {
  9959. /*jshint validthis:true */
  9960. var Constructor = this;
  9961. if (object && typeof object === 'object' && object.constructor === Constructor) {
  9962. return object;
  9963. }
  9964. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  9965. lib$es6$promise$$internal$$resolve(promise, object);
  9966. return promise;
  9967. }
  9968. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  9969. function lib$es6$promise$promise$reject$$reject(reason) {
  9970. /*jshint validthis:true */
  9971. var Constructor = this;
  9972. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  9973. lib$es6$promise$$internal$$reject(promise, reason);
  9974. return promise;
  9975. }
  9976. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  9977. var lib$es6$promise$promise$$counter = 0;
  9978. function lib$es6$promise$promise$$needsResolver() {
  9979. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  9980. }
  9981. function lib$es6$promise$promise$$needsNew() {
  9982. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  9983. }
  9984. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  9985. /**
  9986. Promise objects represent the eventual result of an asynchronous operation. The
  9987. primary way of interacting with a promise is through its `then` method, which
  9988. registers callbacks to receive either a promise's eventual value or the reason
  9989. why the promise cannot be fulfilled.
  9990. Terminology
  9991. -----------
  9992. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  9993. - `thenable` is an object or function that defines a `then` method.
  9994. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  9995. - `exception` is a value that is thrown using the throw statement.
  9996. - `reason` is a value that indicates why a promise was rejected.
  9997. - `settled` the final resting state of a promise, fulfilled or rejected.
  9998. A promise can be in one of three states: pending, fulfilled, or rejected.
  9999. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  10000. state. Promises that are rejected have a rejection reason and are in the
  10001. rejected state. A fulfillment value is never a thenable.
  10002. Promises can also be said to *resolve* a value. If this value is also a
  10003. promise, then the original promise's settled state will match the value's
  10004. settled state. So a promise that *resolves* a promise that rejects will
  10005. itself reject, and a promise that *resolves* a promise that fulfills will
  10006. itself fulfill.
  10007. Basic Usage:
  10008. ------------
  10009. ```js
  10010. var promise = new Promise(function(resolve, reject) {
  10011. // on success
  10012. resolve(value);
  10013. // on failure
  10014. reject(reason);
  10015. });
  10016. promise.then(function(value) {
  10017. // on fulfillment
  10018. }, function(reason) {
  10019. // on rejection
  10020. });
  10021. ```
  10022. Advanced Usage:
  10023. ---------------
  10024. Promises shine when abstracting away asynchronous interactions such as
  10025. `XMLHttpRequest`s.
  10026. ```js
  10027. function getJSON(url) {
  10028. return new Promise(function(resolve, reject){
  10029. var xhr = new XMLHttpRequest();
  10030. xhr.open('GET', url);
  10031. xhr.onreadystatechange = handler;
  10032. xhr.responseType = 'json';
  10033. xhr.setRequestHeader('Accept', 'application/json');
  10034. xhr.send();
  10035. function handler() {
  10036. if (this.readyState === this.DONE) {
  10037. if (this.status === 200) {
  10038. resolve(this.response);
  10039. } else {
  10040. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  10041. }
  10042. }
  10043. };
  10044. });
  10045. }
  10046. getJSON('/posts.json').then(function(json) {
  10047. // on fulfillment
  10048. }, function(reason) {
  10049. // on rejection
  10050. });
  10051. ```
  10052. Unlike callbacks, promises are great composable primitives.
  10053. ```js
  10054. Promise.all([
  10055. getJSON('/posts'),
  10056. getJSON('/comments')
  10057. ]).then(function(values){
  10058. values[0] // => postsJSON
  10059. values[1] // => commentsJSON
  10060. return values;
  10061. });
  10062. ```
  10063. @class Promise
  10064. @param {function} resolver
  10065. Useful for tooling.
  10066. @constructor
  10067. */
  10068. function lib$es6$promise$promise$$Promise(resolver) {
  10069. this._id = lib$es6$promise$promise$$counter++;
  10070. this._state = undefined;
  10071. this._result = undefined;
  10072. this._subscribers = [];
  10073. if (lib$es6$promise$$internal$$noop !== resolver) {
  10074. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  10075. lib$es6$promise$promise$$needsResolver();
  10076. }
  10077. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  10078. lib$es6$promise$promise$$needsNew();
  10079. }
  10080. lib$es6$promise$$internal$$initializePromise(this, resolver);
  10081. }
  10082. }
  10083. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  10084. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  10085. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  10086. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  10087. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  10088. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  10089. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  10090. lib$es6$promise$promise$$Promise.prototype = {
  10091. constructor: lib$es6$promise$promise$$Promise,
  10092. /**
  10093. The primary way of interacting with a promise is through its `then` method,
  10094. which registers callbacks to receive either a promise's eventual value or the
  10095. reason why the promise cannot be fulfilled.
  10096. ```js
  10097. findUser().then(function(user){
  10098. // user is available
  10099. }, function(reason){
  10100. // user is unavailable, and you are given the reason why
  10101. });
  10102. ```
  10103. Chaining
  10104. --------
  10105. The return value of `then` is itself a promise. This second, 'downstream'
  10106. promise is resolved with the return value of the first promise's fulfillment
  10107. or rejection handler, or rejected if the handler throws an exception.
  10108. ```js
  10109. findUser().then(function (user) {
  10110. return user.name;
  10111. }, function (reason) {
  10112. return 'default name';
  10113. }).then(function (userName) {
  10114. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  10115. // will be `'default name'`
  10116. });
  10117. findUser().then(function (user) {
  10118. throw new Error('Found user, but still unhappy');
  10119. }, function (reason) {
  10120. throw new Error('`findUser` rejected and we're unhappy');
  10121. }).then(function (value) {
  10122. // never reached
  10123. }, function (reason) {
  10124. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  10125. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  10126. });
  10127. ```
  10128. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  10129. ```js
  10130. findUser().then(function (user) {
  10131. throw new PedagogicalException('Upstream error');
  10132. }).then(function (value) {
  10133. // never reached
  10134. }).then(function (value) {
  10135. // never reached
  10136. }, function (reason) {
  10137. // The `PedgagocialException` is propagated all the way down to here
  10138. });
  10139. ```
  10140. Assimilation
  10141. ------------
  10142. Sometimes the value you want to propagate to a downstream promise can only be
  10143. retrieved asynchronously. This can be achieved by returning a promise in the
  10144. fulfillment or rejection handler. The downstream promise will then be pending
  10145. until the returned promise is settled. This is called *assimilation*.
  10146. ```js
  10147. findUser().then(function (user) {
  10148. return findCommentsByAuthor(user);
  10149. }).then(function (comments) {
  10150. // The user's comments are now available
  10151. });
  10152. ```
  10153. If the assimliated promise rejects, then the downstream promise will also reject.
  10154. ```js
  10155. findUser().then(function (user) {
  10156. return findCommentsByAuthor(user);
  10157. }).then(function (comments) {
  10158. // If `findCommentsByAuthor` fulfills, we'll have the value here
  10159. }, function (reason) {
  10160. // If `findCommentsByAuthor` rejects, we'll have the reason here
  10161. });
  10162. ```
  10163. Simple Example
  10164. --------------
  10165. Synchronous Example
  10166. ```javascript
  10167. var result;
  10168. try {
  10169. result = findResult();
  10170. // success
  10171. } catch(reason) {
  10172. // failure
  10173. }
  10174. ```
  10175. Errback Example
  10176. ```js
  10177. findResult(function(result, err){
  10178. if (err) {
  10179. // failure
  10180. } else {
  10181. // success
  10182. }
  10183. });
  10184. ```
  10185. Promise Example;
  10186. ```javascript
  10187. findResult().then(function(result){
  10188. // success
  10189. }, function(reason){
  10190. // failure
  10191. });
  10192. ```
  10193. Advanced Example
  10194. --------------
  10195. Synchronous Example
  10196. ```javascript
  10197. var author, books;
  10198. try {
  10199. author = findAuthor();
  10200. books = findBooksByAuthor(author);
  10201. // success
  10202. } catch(reason) {
  10203. // failure
  10204. }
  10205. ```
  10206. Errback Example
  10207. ```js
  10208. function foundBooks(books) {
  10209. }
  10210. function failure(reason) {
  10211. }
  10212. findAuthor(function(author, err){
  10213. if (err) {
  10214. failure(err);
  10215. // failure
  10216. } else {
  10217. try {
  10218. findBoooksByAuthor(author, function(books, err) {
  10219. if (err) {
  10220. failure(err);
  10221. } else {
  10222. try {
  10223. foundBooks(books);
  10224. } catch(reason) {
  10225. failure(reason);
  10226. }
  10227. }
  10228. });
  10229. } catch(error) {
  10230. failure(err);
  10231. }
  10232. // success
  10233. }
  10234. });
  10235. ```
  10236. Promise Example;
  10237. ```javascript
  10238. findAuthor().
  10239. then(findBooksByAuthor).
  10240. then(function(books){
  10241. // found books
  10242. }).catch(function(reason){
  10243. // something went wrong
  10244. });
  10245. ```
  10246. @method then
  10247. @param {Function} onFulfilled
  10248. @param {Function} onRejected
  10249. Useful for tooling.
  10250. @return {Promise}
  10251. */
  10252. then: function(onFulfillment, onRejection) {
  10253. var parent = this;
  10254. var state = parent._state;
  10255. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  10256. return this;
  10257. }
  10258. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  10259. var result = parent._result;
  10260. if (state) {
  10261. var callback = arguments[state - 1];
  10262. lib$es6$promise$asap$$asap(function(){
  10263. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  10264. });
  10265. } else {
  10266. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  10267. }
  10268. return child;
  10269. },
  10270. /**
  10271. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  10272. as the catch block of a try/catch statement.
  10273. ```js
  10274. function findAuthor(){
  10275. throw new Error('couldn't find that author');
  10276. }
  10277. // synchronous
  10278. try {
  10279. findAuthor();
  10280. } catch(reason) {
  10281. // something went wrong
  10282. }
  10283. // async with promises
  10284. findAuthor().catch(function(reason){
  10285. // something went wrong
  10286. });
  10287. ```
  10288. @method catch
  10289. @param {Function} onRejection
  10290. Useful for tooling.
  10291. @return {Promise}
  10292. */
  10293. 'catch': function(onRejection) {
  10294. return this.then(null, onRejection);
  10295. }
  10296. };
  10297. function lib$es6$promise$polyfill$$polyfill() {
  10298. var local;
  10299. if (typeof global !== 'undefined') {
  10300. local = global;
  10301. } else if (typeof self !== 'undefined') {
  10302. local = self;
  10303. } else {
  10304. try {
  10305. local = Function('return this')();
  10306. } catch (e) {
  10307. throw new Error('polyfill failed because global object is unavailable in this environment');
  10308. }
  10309. }
  10310. var P = local.Promise;
  10311. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  10312. return;
  10313. }
  10314. local.Promise = lib$es6$promise$promise$$default;
  10315. }
  10316. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  10317. var lib$es6$promise$umd$$ES6Promise = {
  10318. 'Promise': lib$es6$promise$promise$$default,
  10319. 'polyfill': lib$es6$promise$polyfill$$default
  10320. };
  10321. /* global define:true module:true window: true */
  10322. if (typeof define === 'function' && define['amd']) {
  10323. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  10324. } else if (typeof module !== 'undefined' && module['exports']) {
  10325. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  10326. } else if (typeof this !== 'undefined') {
  10327. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  10328. }
  10329. lib$es6$promise$polyfill$$default();
  10330. }).call(this);
  10331. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  10332. },{"_process":78}],36:[function(require,module,exports){
  10333. // Top level file is just a mixin of submodules & constants
  10334. 'use strict';
  10335. var assign = require('./lib/utils/common').assign;
  10336. var deflate = require('./lib/deflate');
  10337. var inflate = require('./lib/inflate');
  10338. var constants = require('./lib/zlib/constants');
  10339. var pako = {};
  10340. assign(pako, deflate, inflate, constants);
  10341. module.exports = pako;
  10342. },{"./lib/deflate":37,"./lib/inflate":38,"./lib/utils/common":39,"./lib/zlib/constants":42}],37:[function(require,module,exports){
  10343. 'use strict';
  10344. var zlib_deflate = require('./zlib/deflate.js');
  10345. var utils = require('./utils/common');
  10346. var strings = require('./utils/strings');
  10347. var msg = require('./zlib/messages');
  10348. var zstream = require('./zlib/zstream');
  10349. var toString = Object.prototype.toString;
  10350. /* Public constants ==========================================================*/
  10351. /* ===========================================================================*/
  10352. var Z_NO_FLUSH = 0;
  10353. var Z_FINISH = 4;
  10354. var Z_OK = 0;
  10355. var Z_STREAM_END = 1;
  10356. var Z_SYNC_FLUSH = 2;
  10357. var Z_DEFAULT_COMPRESSION = -1;
  10358. var Z_DEFAULT_STRATEGY = 0;
  10359. var Z_DEFLATED = 8;
  10360. /* ===========================================================================*/
  10361. /**
  10362. * class Deflate
  10363. *
  10364. * Generic JS-style wrapper for zlib calls. If you don't need
  10365. * streaming behaviour - use more simple functions: [[deflate]],
  10366. * [[deflateRaw]] and [[gzip]].
  10367. **/
  10368. /* internal
  10369. * Deflate.chunks -> Array
  10370. *
  10371. * Chunks of output data, if [[Deflate#onData]] not overriden.
  10372. **/
  10373. /**
  10374. * Deflate.result -> Uint8Array|Array
  10375. *
  10376. * Compressed result, generated by default [[Deflate#onData]]
  10377. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  10378. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  10379. * push a chunk with explicit flush (call [[Deflate#push]] with
  10380. * `Z_SYNC_FLUSH` param).
  10381. **/
  10382. /**
  10383. * Deflate.err -> Number
  10384. *
  10385. * Error code after deflate finished. 0 (Z_OK) on success.
  10386. * You will not need it in real life, because deflate errors
  10387. * are possible only on wrong options or bad `onData` / `onEnd`
  10388. * custom handlers.
  10389. **/
  10390. /**
  10391. * Deflate.msg -> String
  10392. *
  10393. * Error message, if [[Deflate.err]] != 0
  10394. **/
  10395. /**
  10396. * new Deflate(options)
  10397. * - options (Object): zlib deflate options.
  10398. *
  10399. * Creates new deflator instance with specified params. Throws exception
  10400. * on bad params. Supported options:
  10401. *
  10402. * - `level`
  10403. * - `windowBits`
  10404. * - `memLevel`
  10405. * - `strategy`
  10406. *
  10407. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  10408. * for more information on these.
  10409. *
  10410. * Additional options, for internal needs:
  10411. *
  10412. * - `chunkSize` - size of generated data chunks (16K by default)
  10413. * - `raw` (Boolean) - do raw deflate
  10414. * - `gzip` (Boolean) - create gzip wrapper
  10415. * - `to` (String) - if equal to 'string', then result will be "binary string"
  10416. * (each char code [0..255])
  10417. * - `header` (Object) - custom header for gzip
  10418. * - `text` (Boolean) - true if compressed data believed to be text
  10419. * - `time` (Number) - modification time, unix timestamp
  10420. * - `os` (Number) - operation system code
  10421. * - `extra` (Array) - array of bytes with extra data (max 65536)
  10422. * - `name` (String) - file name (binary string)
  10423. * - `comment` (String) - comment (binary string)
  10424. * - `hcrc` (Boolean) - true if header crc should be added
  10425. *
  10426. * ##### Example:
  10427. *
  10428. * ```javascript
  10429. * var pako = require('pako')
  10430. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  10431. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  10432. *
  10433. * var deflate = new pako.Deflate({ level: 3});
  10434. *
  10435. * deflate.push(chunk1, false);
  10436. * deflate.push(chunk2, true); // true -> last chunk
  10437. *
  10438. * if (deflate.err) { throw new Error(deflate.err); }
  10439. *
  10440. * console.log(deflate.result);
  10441. * ```
  10442. **/
  10443. var Deflate = function(options) {
  10444. this.options = utils.assign({
  10445. level: Z_DEFAULT_COMPRESSION,
  10446. method: Z_DEFLATED,
  10447. chunkSize: 16384,
  10448. windowBits: 15,
  10449. memLevel: 8,
  10450. strategy: Z_DEFAULT_STRATEGY,
  10451. to: ''
  10452. }, options || {});
  10453. var opt = this.options;
  10454. if (opt.raw && (opt.windowBits > 0)) {
  10455. opt.windowBits = -opt.windowBits;
  10456. }
  10457. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  10458. opt.windowBits += 16;
  10459. }
  10460. this.err = 0; // error code, if happens (0 = Z_OK)
  10461. this.msg = ''; // error message
  10462. this.ended = false; // used to avoid multiple onEnd() calls
  10463. this.chunks = []; // chunks of compressed data
  10464. this.strm = new zstream();
  10465. this.strm.avail_out = 0;
  10466. var status = zlib_deflate.deflateInit2(
  10467. this.strm,
  10468. opt.level,
  10469. opt.method,
  10470. opt.windowBits,
  10471. opt.memLevel,
  10472. opt.strategy
  10473. );
  10474. if (status !== Z_OK) {
  10475. throw new Error(msg[status]);
  10476. }
  10477. if (opt.header) {
  10478. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  10479. }
  10480. };
  10481. /**
  10482. * Deflate#push(data[, mode]) -> Boolean
  10483. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  10484. * converted to utf8 byte sequence.
  10485. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  10486. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  10487. *
  10488. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  10489. * new compressed chunks. Returns `true` on success. The last data block must have
  10490. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  10491. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  10492. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  10493. *
  10494. * On fail call [[Deflate#onEnd]] with error code and return false.
  10495. *
  10496. * We strongly recommend to use `Uint8Array` on input for best speed (output
  10497. * array format is detected automatically). Also, don't skip last param and always
  10498. * use the same type in your code (boolean or number). That will improve JS speed.
  10499. *
  10500. * For regular `Array`-s make sure all elements are [0..255].
  10501. *
  10502. * ##### Example
  10503. *
  10504. * ```javascript
  10505. * push(chunk, false); // push one of data chunks
  10506. * ...
  10507. * push(chunk, true); // push last chunk
  10508. * ```
  10509. **/
  10510. Deflate.prototype.push = function(data, mode) {
  10511. var strm = this.strm;
  10512. var chunkSize = this.options.chunkSize;
  10513. var status, _mode;
  10514. if (this.ended) { return false; }
  10515. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  10516. // Convert data if needed
  10517. if (typeof data === 'string') {
  10518. // If we need to compress text, change encoding to utf8.
  10519. strm.input = strings.string2buf(data);
  10520. } else if (toString.call(data) === '[object ArrayBuffer]') {
  10521. strm.input = new Uint8Array(data);
  10522. } else {
  10523. strm.input = data;
  10524. }
  10525. strm.next_in = 0;
  10526. strm.avail_in = strm.input.length;
  10527. do {
  10528. if (strm.avail_out === 0) {
  10529. strm.output = new utils.Buf8(chunkSize);
  10530. strm.next_out = 0;
  10531. strm.avail_out = chunkSize;
  10532. }
  10533. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  10534. if (status !== Z_STREAM_END && status !== Z_OK) {
  10535. this.onEnd(status);
  10536. this.ended = true;
  10537. return false;
  10538. }
  10539. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  10540. if (this.options.to === 'string') {
  10541. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  10542. } else {
  10543. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  10544. }
  10545. }
  10546. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  10547. // Finalize on the last chunk.
  10548. if (_mode === Z_FINISH) {
  10549. status = zlib_deflate.deflateEnd(this.strm);
  10550. this.onEnd(status);
  10551. this.ended = true;
  10552. return status === Z_OK;
  10553. }
  10554. // callback interim results if Z_SYNC_FLUSH.
  10555. if (_mode === Z_SYNC_FLUSH) {
  10556. this.onEnd(Z_OK);
  10557. strm.avail_out = 0;
  10558. return true;
  10559. }
  10560. return true;
  10561. };
  10562. /**
  10563. * Deflate#onData(chunk) -> Void
  10564. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  10565. * on js engine support. When string output requested, each chunk
  10566. * will be string.
  10567. *
  10568. * By default, stores data blocks in `chunks[]` property and glue
  10569. * those in `onEnd`. Override this handler, if you need another behaviour.
  10570. **/
  10571. Deflate.prototype.onData = function(chunk) {
  10572. this.chunks.push(chunk);
  10573. };
  10574. /**
  10575. * Deflate#onEnd(status) -> Void
  10576. * - status (Number): deflate status. 0 (Z_OK) on success,
  10577. * other if not.
  10578. *
  10579. * Called once after you tell deflate that the input stream is
  10580. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  10581. * or if an error happened. By default - join collected chunks,
  10582. * free memory and fill `results` / `err` properties.
  10583. **/
  10584. Deflate.prototype.onEnd = function(status) {
  10585. // On success - join
  10586. if (status === Z_OK) {
  10587. if (this.options.to === 'string') {
  10588. this.result = this.chunks.join('');
  10589. } else {
  10590. this.result = utils.flattenChunks(this.chunks);
  10591. }
  10592. }
  10593. this.chunks = [];
  10594. this.err = status;
  10595. this.msg = this.strm.msg;
  10596. };
  10597. /**
  10598. * deflate(data[, options]) -> Uint8Array|Array|String
  10599. * - data (Uint8Array|Array|String): input data to compress.
  10600. * - options (Object): zlib deflate options.
  10601. *
  10602. * Compress `data` with deflate alrorythm and `options`.
  10603. *
  10604. * Supported options are:
  10605. *
  10606. * - level
  10607. * - windowBits
  10608. * - memLevel
  10609. * - strategy
  10610. *
  10611. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  10612. * for more information on these.
  10613. *
  10614. * Sugar (options):
  10615. *
  10616. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  10617. * negative windowBits implicitly.
  10618. * - `to` (String) - if equal to 'string', then result will be "binary string"
  10619. * (each char code [0..255])
  10620. *
  10621. * ##### Example:
  10622. *
  10623. * ```javascript
  10624. * var pako = require('pako')
  10625. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  10626. *
  10627. * console.log(pako.deflate(data));
  10628. * ```
  10629. **/
  10630. function deflate(input, options) {
  10631. var deflator = new Deflate(options);
  10632. deflator.push(input, true);
  10633. // That will never happens, if you don't cheat with options :)
  10634. if (deflator.err) { throw deflator.msg; }
  10635. return deflator.result;
  10636. }
  10637. /**
  10638. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  10639. * - data (Uint8Array|Array|String): input data to compress.
  10640. * - options (Object): zlib deflate options.
  10641. *
  10642. * The same as [[deflate]], but creates raw data, without wrapper
  10643. * (header and adler32 crc).
  10644. **/
  10645. function deflateRaw(input, options) {
  10646. options = options || {};
  10647. options.raw = true;
  10648. return deflate(input, options);
  10649. }
  10650. /**
  10651. * gzip(data[, options]) -> Uint8Array|Array|String
  10652. * - data (Uint8Array|Array|String): input data to compress.
  10653. * - options (Object): zlib deflate options.
  10654. *
  10655. * The same as [[deflate]], but create gzip wrapper instead of
  10656. * deflate one.
  10657. **/
  10658. function gzip(input, options) {
  10659. options = options || {};
  10660. options.gzip = true;
  10661. return deflate(input, options);
  10662. }
  10663. exports.Deflate = Deflate;
  10664. exports.deflate = deflate;
  10665. exports.deflateRaw = deflateRaw;
  10666. exports.gzip = gzip;
  10667. },{"./utils/common":39,"./utils/strings":40,"./zlib/deflate.js":44,"./zlib/messages":49,"./zlib/zstream":51}],38:[function(require,module,exports){
  10668. 'use strict';
  10669. var zlib_inflate = require('./zlib/inflate.js');
  10670. var utils = require('./utils/common');
  10671. var strings = require('./utils/strings');
  10672. var c = require('./zlib/constants');
  10673. var msg = require('./zlib/messages');
  10674. var zstream = require('./zlib/zstream');
  10675. var gzheader = require('./zlib/gzheader');
  10676. var toString = Object.prototype.toString;
  10677. /**
  10678. * class Inflate
  10679. *
  10680. * Generic JS-style wrapper for zlib calls. If you don't need
  10681. * streaming behaviour - use more simple functions: [[inflate]]
  10682. * and [[inflateRaw]].
  10683. **/
  10684. /* internal
  10685. * inflate.chunks -> Array
  10686. *
  10687. * Chunks of output data, if [[Inflate#onData]] not overriden.
  10688. **/
  10689. /**
  10690. * Inflate.result -> Uint8Array|Array|String
  10691. *
  10692. * Uncompressed result, generated by default [[Inflate#onData]]
  10693. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  10694. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  10695. * push a chunk with explicit flush (call [[Inflate#push]] with
  10696. * `Z_SYNC_FLUSH` param).
  10697. **/
  10698. /**
  10699. * Inflate.err -> Number
  10700. *
  10701. * Error code after inflate finished. 0 (Z_OK) on success.
  10702. * Should be checked if broken data possible.
  10703. **/
  10704. /**
  10705. * Inflate.msg -> String
  10706. *
  10707. * Error message, if [[Inflate.err]] != 0
  10708. **/
  10709. /**
  10710. * new Inflate(options)
  10711. * - options (Object): zlib inflate options.
  10712. *
  10713. * Creates new inflator instance with specified params. Throws exception
  10714. * on bad params. Supported options:
  10715. *
  10716. * - `windowBits`
  10717. *
  10718. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  10719. * for more information on these.
  10720. *
  10721. * Additional options, for internal needs:
  10722. *
  10723. * - `chunkSize` - size of generated data chunks (16K by default)
  10724. * - `raw` (Boolean) - do raw inflate
  10725. * - `to` (String) - if equal to 'string', then result will be converted
  10726. * from utf8 to utf16 (javascript) string. When string output requested,
  10727. * chunk length can differ from `chunkSize`, depending on content.
  10728. *
  10729. * By default, when no options set, autodetect deflate/gzip data format via
  10730. * wrapper header.
  10731. *
  10732. * ##### Example:
  10733. *
  10734. * ```javascript
  10735. * var pako = require('pako')
  10736. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  10737. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  10738. *
  10739. * var inflate = new pako.Inflate({ level: 3});
  10740. *
  10741. * inflate.push(chunk1, false);
  10742. * inflate.push(chunk2, true); // true -> last chunk
  10743. *
  10744. * if (inflate.err) { throw new Error(inflate.err); }
  10745. *
  10746. * console.log(inflate.result);
  10747. * ```
  10748. **/
  10749. var Inflate = function(options) {
  10750. this.options = utils.assign({
  10751. chunkSize: 16384,
  10752. windowBits: 0,
  10753. to: ''
  10754. }, options || {});
  10755. var opt = this.options;
  10756. // Force window size for `raw` data, if not set directly,
  10757. // because we have no header for autodetect.
  10758. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  10759. opt.windowBits = -opt.windowBits;
  10760. if (opt.windowBits === 0) { opt.windowBits = -15; }
  10761. }
  10762. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  10763. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  10764. !(options && options.windowBits)) {
  10765. opt.windowBits += 32;
  10766. }
  10767. // Gzip header has no info about windows size, we can do autodetect only
  10768. // for deflate. So, if window size not set, force it to max when gzip possible
  10769. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  10770. // bit 3 (16) -> gzipped data
  10771. // bit 4 (32) -> autodetect gzip/deflate
  10772. if ((opt.windowBits & 15) === 0) {
  10773. opt.windowBits |= 15;
  10774. }
  10775. }
  10776. this.err = 0; // error code, if happens (0 = Z_OK)
  10777. this.msg = ''; // error message
  10778. this.ended = false; // used to avoid multiple onEnd() calls
  10779. this.chunks = []; // chunks of compressed data
  10780. this.strm = new zstream();
  10781. this.strm.avail_out = 0;
  10782. var status = zlib_inflate.inflateInit2(
  10783. this.strm,
  10784. opt.windowBits
  10785. );
  10786. if (status !== c.Z_OK) {
  10787. throw new Error(msg[status]);
  10788. }
  10789. this.header = new gzheader();
  10790. zlib_inflate.inflateGetHeader(this.strm, this.header);
  10791. };
  10792. /**
  10793. * Inflate#push(data[, mode]) -> Boolean
  10794. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  10795. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  10796. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  10797. *
  10798. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  10799. * new output chunks. Returns `true` on success. The last data block must have
  10800. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  10801. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  10802. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  10803. *
  10804. * On fail call [[Inflate#onEnd]] with error code and return false.
  10805. *
  10806. * We strongly recommend to use `Uint8Array` on input for best speed (output
  10807. * format is detected automatically). Also, don't skip last param and always
  10808. * use the same type in your code (boolean or number). That will improve JS speed.
  10809. *
  10810. * For regular `Array`-s make sure all elements are [0..255].
  10811. *
  10812. * ##### Example
  10813. *
  10814. * ```javascript
  10815. * push(chunk, false); // push one of data chunks
  10816. * ...
  10817. * push(chunk, true); // push last chunk
  10818. * ```
  10819. **/
  10820. Inflate.prototype.push = function(data, mode) {
  10821. var strm = this.strm;
  10822. var chunkSize = this.options.chunkSize;
  10823. var status, _mode;
  10824. var next_out_utf8, tail, utf8str;
  10825. if (this.ended) { return false; }
  10826. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  10827. // Convert data if needed
  10828. if (typeof data === 'string') {
  10829. // Only binary strings can be decompressed on practice
  10830. strm.input = strings.binstring2buf(data);
  10831. } else if (toString.call(data) === '[object ArrayBuffer]') {
  10832. strm.input = new Uint8Array(data);
  10833. } else {
  10834. strm.input = data;
  10835. }
  10836. strm.next_in = 0;
  10837. strm.avail_in = strm.input.length;
  10838. do {
  10839. if (strm.avail_out === 0) {
  10840. strm.output = new utils.Buf8(chunkSize);
  10841. strm.next_out = 0;
  10842. strm.avail_out = chunkSize;
  10843. }
  10844. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  10845. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  10846. this.onEnd(status);
  10847. this.ended = true;
  10848. return false;
  10849. }
  10850. if (strm.next_out) {
  10851. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  10852. if (this.options.to === 'string') {
  10853. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  10854. tail = strm.next_out - next_out_utf8;
  10855. utf8str = strings.buf2string(strm.output, next_out_utf8);
  10856. // move tail
  10857. strm.next_out = tail;
  10858. strm.avail_out = chunkSize - tail;
  10859. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  10860. this.onData(utf8str);
  10861. } else {
  10862. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  10863. }
  10864. }
  10865. }
  10866. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  10867. if (status === c.Z_STREAM_END) {
  10868. _mode = c.Z_FINISH;
  10869. }
  10870. // Finalize on the last chunk.
  10871. if (_mode === c.Z_FINISH) {
  10872. status = zlib_inflate.inflateEnd(this.strm);
  10873. this.onEnd(status);
  10874. this.ended = true;
  10875. return status === c.Z_OK;
  10876. }
  10877. // callback interim results if Z_SYNC_FLUSH.
  10878. if (_mode === c.Z_SYNC_FLUSH) {
  10879. this.onEnd(c.Z_OK);
  10880. strm.avail_out = 0;
  10881. return true;
  10882. }
  10883. return true;
  10884. };
  10885. /**
  10886. * Inflate#onData(chunk) -> Void
  10887. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  10888. * on js engine support. When string output requested, each chunk
  10889. * will be string.
  10890. *
  10891. * By default, stores data blocks in `chunks[]` property and glue
  10892. * those in `onEnd`. Override this handler, if you need another behaviour.
  10893. **/
  10894. Inflate.prototype.onData = function(chunk) {
  10895. this.chunks.push(chunk);
  10896. };
  10897. /**
  10898. * Inflate#onEnd(status) -> Void
  10899. * - status (Number): inflate status. 0 (Z_OK) on success,
  10900. * other if not.
  10901. *
  10902. * Called either after you tell inflate that the input stream is
  10903. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  10904. * or if an error happened. By default - join collected chunks,
  10905. * free memory and fill `results` / `err` properties.
  10906. **/
  10907. Inflate.prototype.onEnd = function(status) {
  10908. // On success - join
  10909. if (status === c.Z_OK) {
  10910. if (this.options.to === 'string') {
  10911. // Glue & convert here, until we teach pako to send
  10912. // utf8 alligned strings to onData
  10913. this.result = this.chunks.join('');
  10914. } else {
  10915. this.result = utils.flattenChunks(this.chunks);
  10916. }
  10917. }
  10918. this.chunks = [];
  10919. this.err = status;
  10920. this.msg = this.strm.msg;
  10921. };
  10922. /**
  10923. * inflate(data[, options]) -> Uint8Array|Array|String
  10924. * - data (Uint8Array|Array|String): input data to decompress.
  10925. * - options (Object): zlib inflate options.
  10926. *
  10927. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  10928. * format via wrapper header by default. That's why we don't provide
  10929. * separate `ungzip` method.
  10930. *
  10931. * Supported options are:
  10932. *
  10933. * - windowBits
  10934. *
  10935. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  10936. * for more information.
  10937. *
  10938. * Sugar (options):
  10939. *
  10940. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  10941. * negative windowBits implicitly.
  10942. * - `to` (String) - if equal to 'string', then result will be converted
  10943. * from utf8 to utf16 (javascript) string. When string output requested,
  10944. * chunk length can differ from `chunkSize`, depending on content.
  10945. *
  10946. *
  10947. * ##### Example:
  10948. *
  10949. * ```javascript
  10950. * var pako = require('pako')
  10951. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  10952. * , output;
  10953. *
  10954. * try {
  10955. * output = pako.inflate(input);
  10956. * } catch (err)
  10957. * console.log(err);
  10958. * }
  10959. * ```
  10960. **/
  10961. function inflate(input, options) {
  10962. var inflator = new Inflate(options);
  10963. inflator.push(input, true);
  10964. // That will never happens, if you don't cheat with options :)
  10965. if (inflator.err) { throw inflator.msg; }
  10966. return inflator.result;
  10967. }
  10968. /**
  10969. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  10970. * - data (Uint8Array|Array|String): input data to decompress.
  10971. * - options (Object): zlib inflate options.
  10972. *
  10973. * The same as [[inflate]], but creates raw data, without wrapper
  10974. * (header and adler32 crc).
  10975. **/
  10976. function inflateRaw(input, options) {
  10977. options = options || {};
  10978. options.raw = true;
  10979. return inflate(input, options);
  10980. }
  10981. /**
  10982. * ungzip(data[, options]) -> Uint8Array|Array|String
  10983. * - data (Uint8Array|Array|String): input data to decompress.
  10984. * - options (Object): zlib inflate options.
  10985. *
  10986. * Just shortcut to [[inflate]], because it autodetects format
  10987. * by header.content. Done for convenience.
  10988. **/
  10989. exports.Inflate = Inflate;
  10990. exports.inflate = inflate;
  10991. exports.inflateRaw = inflateRaw;
  10992. exports.ungzip = inflate;
  10993. },{"./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){
  10994. 'use strict';
  10995. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  10996. (typeof Uint16Array !== 'undefined') &&
  10997. (typeof Int32Array !== 'undefined');
  10998. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  10999. var sources = Array.prototype.slice.call(arguments, 1);
  11000. while (sources.length) {
  11001. var source = sources.shift();
  11002. if (!source) { continue; }
  11003. if (typeof source !== 'object') {
  11004. throw new TypeError(source + 'must be non-object');
  11005. }
  11006. for (var p in source) {
  11007. if (source.hasOwnProperty(p)) {
  11008. obj[p] = source[p];
  11009. }
  11010. }
  11011. }
  11012. return obj;
  11013. };
  11014. // reduce buffer size, avoiding mem copy
  11015. exports.shrinkBuf = function (buf, size) {
  11016. if (buf.length === size) { return buf; }
  11017. if (buf.subarray) { return buf.subarray(0, size); }
  11018. buf.length = size;
  11019. return buf;
  11020. };
  11021. var fnTyped = {
  11022. arraySet: function (dest, src, src_offs, len, dest_offs) {
  11023. if (src.subarray && dest.subarray) {
  11024. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  11025. return;
  11026. }
  11027. // Fallback to ordinary array
  11028. for (var i=0; i<len; i++) {
  11029. dest[dest_offs + i] = src[src_offs + i];
  11030. }
  11031. },
  11032. // Join array of chunks to single array.
  11033. flattenChunks: function(chunks) {
  11034. var i, l, len, pos, chunk, result;
  11035. // calculate data length
  11036. len = 0;
  11037. for (i=0, l=chunks.length; i<l; i++) {
  11038. len += chunks[i].length;
  11039. }
  11040. // join chunks
  11041. result = new Uint8Array(len);
  11042. pos = 0;
  11043. for (i=0, l=chunks.length; i<l; i++) {
  11044. chunk = chunks[i];
  11045. result.set(chunk, pos);
  11046. pos += chunk.length;
  11047. }
  11048. return result;
  11049. }
  11050. };
  11051. var fnUntyped = {
  11052. arraySet: function (dest, src, src_offs, len, dest_offs) {
  11053. for (var i=0; i<len; i++) {
  11054. dest[dest_offs + i] = src[src_offs + i];
  11055. }
  11056. },
  11057. // Join array of chunks to single array.
  11058. flattenChunks: function(chunks) {
  11059. return [].concat.apply([], chunks);
  11060. }
  11061. };
  11062. // Enable/Disable typed arrays use, for testing
  11063. //
  11064. exports.setTyped = function (on) {
  11065. if (on) {
  11066. exports.Buf8 = Uint8Array;
  11067. exports.Buf16 = Uint16Array;
  11068. exports.Buf32 = Int32Array;
  11069. exports.assign(exports, fnTyped);
  11070. } else {
  11071. exports.Buf8 = Array;
  11072. exports.Buf16 = Array;
  11073. exports.Buf32 = Array;
  11074. exports.assign(exports, fnUntyped);
  11075. }
  11076. };
  11077. exports.setTyped(TYPED_OK);
  11078. },{}],40:[function(require,module,exports){
  11079. // String encode/decode helpers
  11080. 'use strict';
  11081. var utils = require('./common');
  11082. // Quick check if we can use fast array to bin string conversion
  11083. //
  11084. // - apply(Array) can fail on Android 2.2
  11085. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  11086. //
  11087. var STR_APPLY_OK = true;
  11088. var STR_APPLY_UIA_OK = true;
  11089. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  11090. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  11091. // Table with utf8 lengths (calculated by first byte of sequence)
  11092. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  11093. // because max possible codepoint is 0x10ffff
  11094. var _utf8len = new utils.Buf8(256);
  11095. for (var q=0; q<256; q++) {
  11096. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  11097. }
  11098. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  11099. // convert string to array (typed, when possible)
  11100. exports.string2buf = function (str) {
  11101. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  11102. // count binary size
  11103. for (m_pos = 0; m_pos < str_len; m_pos++) {
  11104. c = str.charCodeAt(m_pos);
  11105. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  11106. c2 = str.charCodeAt(m_pos+1);
  11107. if ((c2 & 0xfc00) === 0xdc00) {
  11108. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  11109. m_pos++;
  11110. }
  11111. }
  11112. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  11113. }
  11114. // allocate buffer
  11115. buf = new utils.Buf8(buf_len);
  11116. // convert
  11117. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  11118. c = str.charCodeAt(m_pos);
  11119. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  11120. c2 = str.charCodeAt(m_pos+1);
  11121. if ((c2 & 0xfc00) === 0xdc00) {
  11122. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  11123. m_pos++;
  11124. }
  11125. }
  11126. if (c < 0x80) {
  11127. /* one byte */
  11128. buf[i++] = c;
  11129. } else if (c < 0x800) {
  11130. /* two bytes */
  11131. buf[i++] = 0xC0 | (c >>> 6);
  11132. buf[i++] = 0x80 | (c & 0x3f);
  11133. } else if (c < 0x10000) {
  11134. /* three bytes */
  11135. buf[i++] = 0xE0 | (c >>> 12);
  11136. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  11137. buf[i++] = 0x80 | (c & 0x3f);
  11138. } else {
  11139. /* four bytes */
  11140. buf[i++] = 0xf0 | (c >>> 18);
  11141. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  11142. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  11143. buf[i++] = 0x80 | (c & 0x3f);
  11144. }
  11145. }
  11146. return buf;
  11147. };
  11148. // Helper (used in 2 places)
  11149. function buf2binstring(buf, len) {
  11150. // use fallback for big arrays to avoid stack overflow
  11151. if (len < 65537) {
  11152. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  11153. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  11154. }
  11155. }
  11156. var result = '';
  11157. for (var i=0; i < len; i++) {
  11158. result += String.fromCharCode(buf[i]);
  11159. }
  11160. return result;
  11161. }
  11162. // Convert byte array to binary string
  11163. exports.buf2binstring = function(buf) {
  11164. return buf2binstring(buf, buf.length);
  11165. };
  11166. // Convert binary string (typed, when possible)
  11167. exports.binstring2buf = function(str) {
  11168. var buf = new utils.Buf8(str.length);
  11169. for (var i=0, len=buf.length; i < len; i++) {
  11170. buf[i] = str.charCodeAt(i);
  11171. }
  11172. return buf;
  11173. };
  11174. // convert array to string
  11175. exports.buf2string = function (buf, max) {
  11176. var i, out, c, c_len;
  11177. var len = max || buf.length;
  11178. // Reserve max possible length (2 words per char)
  11179. // NB: by unknown reasons, Array is significantly faster for
  11180. // String.fromCharCode.apply than Uint16Array.
  11181. var utf16buf = new Array(len*2);
  11182. for (out=0, i=0; i<len;) {
  11183. c = buf[i++];
  11184. // quick process ascii
  11185. if (c < 0x80) { utf16buf[out++] = c; continue; }
  11186. c_len = _utf8len[c];
  11187. // skip 5 & 6 byte codes
  11188. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  11189. // apply mask on first byte
  11190. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  11191. // join the rest
  11192. while (c_len > 1 && i < len) {
  11193. c = (c << 6) | (buf[i++] & 0x3f);
  11194. c_len--;
  11195. }
  11196. // terminated by end of string?
  11197. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  11198. if (c < 0x10000) {
  11199. utf16buf[out++] = c;
  11200. } else {
  11201. c -= 0x10000;
  11202. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  11203. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  11204. }
  11205. }
  11206. return buf2binstring(utf16buf, out);
  11207. };
  11208. // Calculate max possible position in utf8 buffer,
  11209. // that will not break sequence. If that's not possible
  11210. // - (very small limits) return max size as is.
  11211. //
  11212. // buf[] - utf8 bytes array
  11213. // max - length limit (mandatory);
  11214. exports.utf8border = function(buf, max) {
  11215. var pos;
  11216. max = max || buf.length;
  11217. if (max > buf.length) { max = buf.length; }
  11218. // go back from last position, until start of sequence found
  11219. pos = max-1;
  11220. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  11221. // Fuckup - very small and broken sequence,
  11222. // return max, because we should return something anyway.
  11223. if (pos < 0) { return max; }
  11224. // If we came to start of buffer - that means vuffer is too small,
  11225. // return max too.
  11226. if (pos === 0) { return max; }
  11227. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  11228. };
  11229. },{"./common":39}],41:[function(require,module,exports){
  11230. 'use strict';
  11231. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  11232. // It doesn't worth to make additional optimizationa as in original.
  11233. // Small size is preferable.
  11234. function adler32(adler, buf, len, pos) {
  11235. var s1 = (adler & 0xffff) |0,
  11236. s2 = ((adler >>> 16) & 0xffff) |0,
  11237. n = 0;
  11238. while (len !== 0) {
  11239. // Set limit ~ twice less than 5552, to keep
  11240. // s2 in 31-bits, because we force signed ints.
  11241. // in other case %= will fail.
  11242. n = len > 2000 ? 2000 : len;
  11243. len -= n;
  11244. do {
  11245. s1 = (s1 + buf[pos++]) |0;
  11246. s2 = (s2 + s1) |0;
  11247. } while (--n);
  11248. s1 %= 65521;
  11249. s2 %= 65521;
  11250. }
  11251. return (s1 | (s2 << 16)) |0;
  11252. }
  11253. module.exports = adler32;
  11254. },{}],42:[function(require,module,exports){
  11255. module.exports = {
  11256. /* Allowed flush values; see deflate() and inflate() below for details */
  11257. Z_NO_FLUSH: 0,
  11258. Z_PARTIAL_FLUSH: 1,
  11259. Z_SYNC_FLUSH: 2,
  11260. Z_FULL_FLUSH: 3,
  11261. Z_FINISH: 4,
  11262. Z_BLOCK: 5,
  11263. Z_TREES: 6,
  11264. /* Return codes for the compression/decompression functions. Negative values
  11265. * are errors, positive values are used for special but normal events.
  11266. */
  11267. Z_OK: 0,
  11268. Z_STREAM_END: 1,
  11269. Z_NEED_DICT: 2,
  11270. Z_ERRNO: -1,
  11271. Z_STREAM_ERROR: -2,
  11272. Z_DATA_ERROR: -3,
  11273. //Z_MEM_ERROR: -4,
  11274. Z_BUF_ERROR: -5,
  11275. //Z_VERSION_ERROR: -6,
  11276. /* compression levels */
  11277. Z_NO_COMPRESSION: 0,
  11278. Z_BEST_SPEED: 1,
  11279. Z_BEST_COMPRESSION: 9,
  11280. Z_DEFAULT_COMPRESSION: -1,
  11281. Z_FILTERED: 1,
  11282. Z_HUFFMAN_ONLY: 2,
  11283. Z_RLE: 3,
  11284. Z_FIXED: 4,
  11285. Z_DEFAULT_STRATEGY: 0,
  11286. /* Possible values of the data_type field (though see inflate()) */
  11287. Z_BINARY: 0,
  11288. Z_TEXT: 1,
  11289. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  11290. Z_UNKNOWN: 2,
  11291. /* The deflate compression method */
  11292. Z_DEFLATED: 8
  11293. //Z_NULL: null // Use -1 or null inline, depending on var type
  11294. };
  11295. },{}],43:[function(require,module,exports){
  11296. 'use strict';
  11297. // Note: we can't get significant speed boost here.
  11298. // So write code to minimize size - no pregenerated tables
  11299. // and array tools dependencies.
  11300. // Use ordinary array, since untyped makes no boost here
  11301. function makeTable() {
  11302. var c, table = [];
  11303. for (var n =0; n < 256; n++) {
  11304. c = n;
  11305. for (var k =0; k < 8; k++) {
  11306. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  11307. }
  11308. table[n] = c;
  11309. }
  11310. return table;
  11311. }
  11312. // Create table on load. Just 255 signed longs. Not a problem.
  11313. var crcTable = makeTable();
  11314. function crc32(crc, buf, len, pos) {
  11315. var t = crcTable,
  11316. end = pos + len;
  11317. crc = crc ^ (-1);
  11318. for (var i = pos; i < end; i++) {
  11319. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  11320. }
  11321. return (crc ^ (-1)); // >>> 0;
  11322. }
  11323. module.exports = crc32;
  11324. },{}],44:[function(require,module,exports){
  11325. 'use strict';
  11326. var utils = require('../utils/common');
  11327. var trees = require('./trees');
  11328. var adler32 = require('./adler32');
  11329. var crc32 = require('./crc32');
  11330. var msg = require('./messages');
  11331. /* Public constants ==========================================================*/
  11332. /* ===========================================================================*/
  11333. /* Allowed flush values; see deflate() and inflate() below for details */
  11334. var Z_NO_FLUSH = 0;
  11335. var Z_PARTIAL_FLUSH = 1;
  11336. //var Z_SYNC_FLUSH = 2;
  11337. var Z_FULL_FLUSH = 3;
  11338. var Z_FINISH = 4;
  11339. var Z_BLOCK = 5;
  11340. //var Z_TREES = 6;
  11341. /* Return codes for the compression/decompression functions. Negative values
  11342. * are errors, positive values are used for special but normal events.
  11343. */
  11344. var Z_OK = 0;
  11345. var Z_STREAM_END = 1;
  11346. //var Z_NEED_DICT = 2;
  11347. //var Z_ERRNO = -1;
  11348. var Z_STREAM_ERROR = -2;
  11349. var Z_DATA_ERROR = -3;
  11350. //var Z_MEM_ERROR = -4;
  11351. var Z_BUF_ERROR = -5;
  11352. //var Z_VERSION_ERROR = -6;
  11353. /* compression levels */
  11354. //var Z_NO_COMPRESSION = 0;
  11355. //var Z_BEST_SPEED = 1;
  11356. //var Z_BEST_COMPRESSION = 9;
  11357. var Z_DEFAULT_COMPRESSION = -1;
  11358. var Z_FILTERED = 1;
  11359. var Z_HUFFMAN_ONLY = 2;
  11360. var Z_RLE = 3;
  11361. var Z_FIXED = 4;
  11362. var Z_DEFAULT_STRATEGY = 0;
  11363. /* Possible values of the data_type field (though see inflate()) */
  11364. //var Z_BINARY = 0;
  11365. //var Z_TEXT = 1;
  11366. //var Z_ASCII = 1; // = Z_TEXT
  11367. var Z_UNKNOWN = 2;
  11368. /* The deflate compression method */
  11369. var Z_DEFLATED = 8;
  11370. /*============================================================================*/
  11371. var MAX_MEM_LEVEL = 9;
  11372. /* Maximum value for memLevel in deflateInit2 */
  11373. var MAX_WBITS = 15;
  11374. /* 32K LZ77 window */
  11375. var DEF_MEM_LEVEL = 8;
  11376. var LENGTH_CODES = 29;
  11377. /* number of length codes, not counting the special END_BLOCK code */
  11378. var LITERALS = 256;
  11379. /* number of literal bytes 0..255 */
  11380. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  11381. /* number of Literal or Length codes, including the END_BLOCK code */
  11382. var D_CODES = 30;
  11383. /* number of distance codes */
  11384. var BL_CODES = 19;
  11385. /* number of codes used to transfer the bit lengths */
  11386. var HEAP_SIZE = 2*L_CODES + 1;
  11387. /* maximum heap size */
  11388. var MAX_BITS = 15;
  11389. /* All codes must not exceed MAX_BITS bits */
  11390. var MIN_MATCH = 3;
  11391. var MAX_MATCH = 258;
  11392. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  11393. var PRESET_DICT = 0x20;
  11394. var INIT_STATE = 42;
  11395. var EXTRA_STATE = 69;
  11396. var NAME_STATE = 73;
  11397. var COMMENT_STATE = 91;
  11398. var HCRC_STATE = 103;
  11399. var BUSY_STATE = 113;
  11400. var FINISH_STATE = 666;
  11401. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  11402. var BS_BLOCK_DONE = 2; /* block flush performed */
  11403. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  11404. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  11405. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  11406. function err(strm, errorCode) {
  11407. strm.msg = msg[errorCode];
  11408. return errorCode;
  11409. }
  11410. function rank(f) {
  11411. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  11412. }
  11413. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  11414. /* =========================================================================
  11415. * Flush as much pending output as possible. All deflate() output goes
  11416. * through this function so some applications may wish to modify it
  11417. * to avoid allocating a large strm->output buffer and copying into it.
  11418. * (See also read_buf()).
  11419. */
  11420. function flush_pending(strm) {
  11421. var s = strm.state;
  11422. //_tr_flush_bits(s);
  11423. var len = s.pending;
  11424. if (len > strm.avail_out) {
  11425. len = strm.avail_out;
  11426. }
  11427. if (len === 0) { return; }
  11428. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  11429. strm.next_out += len;
  11430. s.pending_out += len;
  11431. strm.total_out += len;
  11432. strm.avail_out -= len;
  11433. s.pending -= len;
  11434. if (s.pending === 0) {
  11435. s.pending_out = 0;
  11436. }
  11437. }
  11438. function flush_block_only (s, last) {
  11439. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  11440. s.block_start = s.strstart;
  11441. flush_pending(s.strm);
  11442. }
  11443. function put_byte(s, b) {
  11444. s.pending_buf[s.pending++] = b;
  11445. }
  11446. /* =========================================================================
  11447. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  11448. * IN assertion: the stream state is correct and there is enough room in
  11449. * pending_buf.
  11450. */
  11451. function putShortMSB(s, b) {
  11452. // put_byte(s, (Byte)(b >> 8));
  11453. // put_byte(s, (Byte)(b & 0xff));
  11454. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  11455. s.pending_buf[s.pending++] = b & 0xff;
  11456. }
  11457. /* ===========================================================================
  11458. * Read a new buffer from the current input stream, update the adler32
  11459. * and total number of bytes read. All deflate() input goes through
  11460. * this function so some applications may wish to modify it to avoid
  11461. * allocating a large strm->input buffer and copying from it.
  11462. * (See also flush_pending()).
  11463. */
  11464. function read_buf(strm, buf, start, size) {
  11465. var len = strm.avail_in;
  11466. if (len > size) { len = size; }
  11467. if (len === 0) { return 0; }
  11468. strm.avail_in -= len;
  11469. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  11470. if (strm.state.wrap === 1) {
  11471. strm.adler = adler32(strm.adler, buf, len, start);
  11472. }
  11473. else if (strm.state.wrap === 2) {
  11474. strm.adler = crc32(strm.adler, buf, len, start);
  11475. }
  11476. strm.next_in += len;
  11477. strm.total_in += len;
  11478. return len;
  11479. }
  11480. /* ===========================================================================
  11481. * Set match_start to the longest match starting at the given string and
  11482. * return its length. Matches shorter or equal to prev_length are discarded,
  11483. * in which case the result is equal to prev_length and match_start is
  11484. * garbage.
  11485. * IN assertions: cur_match is the head of the hash chain for the current
  11486. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  11487. * OUT assertion: the match length is not greater than s->lookahead.
  11488. */
  11489. function longest_match(s, cur_match) {
  11490. var chain_length = s.max_chain_length; /* max hash chain length */
  11491. var scan = s.strstart; /* current string */
  11492. var match; /* matched string */
  11493. var len; /* length of current match */
  11494. var best_len = s.prev_length; /* best match length so far */
  11495. var nice_match = s.nice_match; /* stop if match long enough */
  11496. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  11497. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  11498. var _win = s.window; // shortcut
  11499. var wmask = s.w_mask;
  11500. var prev = s.prev;
  11501. /* Stop when cur_match becomes <= limit. To simplify the code,
  11502. * we prevent matches with the string of window index 0.
  11503. */
  11504. var strend = s.strstart + MAX_MATCH;
  11505. var scan_end1 = _win[scan + best_len - 1];
  11506. var scan_end = _win[scan + best_len];
  11507. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  11508. * It is easy to get rid of this optimization if necessary.
  11509. */
  11510. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  11511. /* Do not waste too much time if we already have a good match: */
  11512. if (s.prev_length >= s.good_match) {
  11513. chain_length >>= 2;
  11514. }
  11515. /* Do not look for matches beyond the end of the input. This is necessary
  11516. * to make deflate deterministic.
  11517. */
  11518. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  11519. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  11520. do {
  11521. // Assert(cur_match < s->strstart, "no future");
  11522. match = cur_match;
  11523. /* Skip to next match if the match length cannot increase
  11524. * or if the match length is less than 2. Note that the checks below
  11525. * for insufficient lookahead only occur occasionally for performance
  11526. * reasons. Therefore uninitialized memory will be accessed, and
  11527. * conditional jumps will be made that depend on those values.
  11528. * However the length of the match is limited to the lookahead, so
  11529. * the output of deflate is not affected by the uninitialized values.
  11530. */
  11531. if (_win[match + best_len] !== scan_end ||
  11532. _win[match + best_len - 1] !== scan_end1 ||
  11533. _win[match] !== _win[scan] ||
  11534. _win[++match] !== _win[scan + 1]) {
  11535. continue;
  11536. }
  11537. /* The check at best_len-1 can be removed because it will be made
  11538. * again later. (This heuristic is not always a win.)
  11539. * It is not necessary to compare scan[2] and match[2] since they
  11540. * are always equal when the other bytes match, given that
  11541. * the hash keys are equal and that HASH_BITS >= 8.
  11542. */
  11543. scan += 2;
  11544. match++;
  11545. // Assert(*scan == *match, "match[2]?");
  11546. /* We check for insufficient lookahead only every 8th comparison;
  11547. * the 256th check will be made at strstart+258.
  11548. */
  11549. do {
  11550. /*jshint noempty:false*/
  11551. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  11552. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  11553. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  11554. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  11555. scan < strend);
  11556. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  11557. len = MAX_MATCH - (strend - scan);
  11558. scan = strend - MAX_MATCH;
  11559. if (len > best_len) {
  11560. s.match_start = cur_match;
  11561. best_len = len;
  11562. if (len >= nice_match) {
  11563. break;
  11564. }
  11565. scan_end1 = _win[scan + best_len - 1];
  11566. scan_end = _win[scan + best_len];
  11567. }
  11568. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  11569. if (best_len <= s.lookahead) {
  11570. return best_len;
  11571. }
  11572. return s.lookahead;
  11573. }
  11574. /* ===========================================================================
  11575. * Fill the window when the lookahead becomes insufficient.
  11576. * Updates strstart and lookahead.
  11577. *
  11578. * IN assertion: lookahead < MIN_LOOKAHEAD
  11579. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  11580. * At least one byte has been read, or avail_in == 0; reads are
  11581. * performed for at least two bytes (required for the zip translate_eol
  11582. * option -- not supported here).
  11583. */
  11584. function fill_window(s) {
  11585. var _w_size = s.w_size;
  11586. var p, n, m, more, str;
  11587. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  11588. do {
  11589. more = s.window_size - s.lookahead - s.strstart;
  11590. // JS ints have 32 bit, block below not needed
  11591. /* Deal with !@#$% 64K limit: */
  11592. //if (sizeof(int) <= 2) {
  11593. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  11594. // more = wsize;
  11595. //
  11596. // } else if (more == (unsigned)(-1)) {
  11597. // /* Very unlikely, but possible on 16 bit machine if
  11598. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  11599. // */
  11600. // more--;
  11601. // }
  11602. //}
  11603. /* If the window is almost full and there is insufficient lookahead,
  11604. * move the upper half to the lower one to make room in the upper half.
  11605. */
  11606. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  11607. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  11608. s.match_start -= _w_size;
  11609. s.strstart -= _w_size;
  11610. /* we now have strstart >= MAX_DIST */
  11611. s.block_start -= _w_size;
  11612. /* Slide the hash table (could be avoided with 32 bit values
  11613. at the expense of memory usage). We slide even when level == 0
  11614. to keep the hash table consistent if we switch back to level > 0
  11615. later. (Using level 0 permanently is not an optimal usage of
  11616. zlib, so we don't care about this pathological case.)
  11617. */
  11618. n = s.hash_size;
  11619. p = n;
  11620. do {
  11621. m = s.head[--p];
  11622. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  11623. } while (--n);
  11624. n = _w_size;
  11625. p = n;
  11626. do {
  11627. m = s.prev[--p];
  11628. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  11629. /* If n is not on any hash chain, prev[n] is garbage but
  11630. * its value will never be used.
  11631. */
  11632. } while (--n);
  11633. more += _w_size;
  11634. }
  11635. if (s.strm.avail_in === 0) {
  11636. break;
  11637. }
  11638. /* If there was no sliding:
  11639. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  11640. * more == window_size - lookahead - strstart
  11641. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  11642. * => more >= window_size - 2*WSIZE + 2
  11643. * In the BIG_MEM or MMAP case (not yet supported),
  11644. * window_size == input_size + MIN_LOOKAHEAD &&
  11645. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  11646. * Otherwise, window_size == 2*WSIZE so more >= 2.
  11647. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  11648. */
  11649. //Assert(more >= 2, "more < 2");
  11650. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  11651. s.lookahead += n;
  11652. /* Initialize the hash value now that we have some input: */
  11653. if (s.lookahead + s.insert >= MIN_MATCH) {
  11654. str = s.strstart - s.insert;
  11655. s.ins_h = s.window[str];
  11656. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  11657. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  11658. //#if MIN_MATCH != 3
  11659. // Call update_hash() MIN_MATCH-3 more times
  11660. //#endif
  11661. while (s.insert) {
  11662. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  11663. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  11664. s.prev[str & s.w_mask] = s.head[s.ins_h];
  11665. s.head[s.ins_h] = str;
  11666. str++;
  11667. s.insert--;
  11668. if (s.lookahead + s.insert < MIN_MATCH) {
  11669. break;
  11670. }
  11671. }
  11672. }
  11673. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  11674. * but this is not important since only literal bytes will be emitted.
  11675. */
  11676. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  11677. /* If the WIN_INIT bytes after the end of the current data have never been
  11678. * written, then zero those bytes in order to avoid memory check reports of
  11679. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  11680. * the longest match routines. Update the high water mark for the next
  11681. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  11682. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  11683. */
  11684. // if (s.high_water < s.window_size) {
  11685. // var curr = s.strstart + s.lookahead;
  11686. // var init = 0;
  11687. //
  11688. // if (s.high_water < curr) {
  11689. // /* Previous high water mark below current data -- zero WIN_INIT
  11690. // * bytes or up to end of window, whichever is less.
  11691. // */
  11692. // init = s.window_size - curr;
  11693. // if (init > WIN_INIT)
  11694. // init = WIN_INIT;
  11695. // zmemzero(s->window + curr, (unsigned)init);
  11696. // s->high_water = curr + init;
  11697. // }
  11698. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  11699. // /* High water mark at or above current data, but below current data
  11700. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  11701. // * to end of window, whichever is less.
  11702. // */
  11703. // init = (ulg)curr + WIN_INIT - s->high_water;
  11704. // if (init > s->window_size - s->high_water)
  11705. // init = s->window_size - s->high_water;
  11706. // zmemzero(s->window + s->high_water, (unsigned)init);
  11707. // s->high_water += init;
  11708. // }
  11709. // }
  11710. //
  11711. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  11712. // "not enough room for search");
  11713. }
  11714. /* ===========================================================================
  11715. * Copy without compression as much as possible from the input stream, return
  11716. * the current block state.
  11717. * This function does not insert new strings in the dictionary since
  11718. * uncompressible data is probably not useful. This function is used
  11719. * only for the level=0 compression option.
  11720. * NOTE: this function should be optimized to avoid extra copying from
  11721. * window to pending_buf.
  11722. */
  11723. function deflate_stored(s, flush) {
  11724. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  11725. * to pending_buf_size, and each stored block has a 5 byte header:
  11726. */
  11727. var max_block_size = 0xffff;
  11728. if (max_block_size > s.pending_buf_size - 5) {
  11729. max_block_size = s.pending_buf_size - 5;
  11730. }
  11731. /* Copy as much as possible from input to output: */
  11732. for (;;) {
  11733. /* Fill the window as much as possible: */
  11734. if (s.lookahead <= 1) {
  11735. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  11736. // s->block_start >= (long)s->w_size, "slide too late");
  11737. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  11738. // s.block_start >= s.w_size)) {
  11739. // throw new Error("slide too late");
  11740. // }
  11741. fill_window(s);
  11742. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  11743. return BS_NEED_MORE;
  11744. }
  11745. if (s.lookahead === 0) {
  11746. break;
  11747. }
  11748. /* flush the current block */
  11749. }
  11750. //Assert(s->block_start >= 0L, "block gone");
  11751. // if (s.block_start < 0) throw new Error("block gone");
  11752. s.strstart += s.lookahead;
  11753. s.lookahead = 0;
  11754. /* Emit a stored block if pending_buf will be full: */
  11755. var max_start = s.block_start + max_block_size;
  11756. if (s.strstart === 0 || s.strstart >= max_start) {
  11757. /* strstart == 0 is possible when wraparound on 16-bit machine */
  11758. s.lookahead = s.strstart - max_start;
  11759. s.strstart = max_start;
  11760. /*** FLUSH_BLOCK(s, 0); ***/
  11761. flush_block_only(s, false);
  11762. if (s.strm.avail_out === 0) {
  11763. return BS_NEED_MORE;
  11764. }
  11765. /***/
  11766. }
  11767. /* Flush if we may have to slide, otherwise block_start may become
  11768. * negative and the data will be gone:
  11769. */
  11770. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  11771. /*** FLUSH_BLOCK(s, 0); ***/
  11772. flush_block_only(s, false);
  11773. if (s.strm.avail_out === 0) {
  11774. return BS_NEED_MORE;
  11775. }
  11776. /***/
  11777. }
  11778. }
  11779. s.insert = 0;
  11780. if (flush === Z_FINISH) {
  11781. /*** FLUSH_BLOCK(s, 1); ***/
  11782. flush_block_only(s, true);
  11783. if (s.strm.avail_out === 0) {
  11784. return BS_FINISH_STARTED;
  11785. }
  11786. /***/
  11787. return BS_FINISH_DONE;
  11788. }
  11789. if (s.strstart > s.block_start) {
  11790. /*** FLUSH_BLOCK(s, 0); ***/
  11791. flush_block_only(s, false);
  11792. if (s.strm.avail_out === 0) {
  11793. return BS_NEED_MORE;
  11794. }
  11795. /***/
  11796. }
  11797. return BS_NEED_MORE;
  11798. }
  11799. /* ===========================================================================
  11800. * Compress as much as possible from the input stream, return the current
  11801. * block state.
  11802. * This function does not perform lazy evaluation of matches and inserts
  11803. * new strings in the dictionary only for unmatched strings or for short
  11804. * matches. It is used only for the fast compression options.
  11805. */
  11806. function deflate_fast(s, flush) {
  11807. var hash_head; /* head of the hash chain */
  11808. var bflush; /* set if current block must be flushed */
  11809. for (;;) {
  11810. /* Make sure that we always have enough lookahead, except
  11811. * at the end of the input file. We need MAX_MATCH bytes
  11812. * for the next match, plus MIN_MATCH bytes to insert the
  11813. * string following the next match.
  11814. */
  11815. if (s.lookahead < MIN_LOOKAHEAD) {
  11816. fill_window(s);
  11817. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  11818. return BS_NEED_MORE;
  11819. }
  11820. if (s.lookahead === 0) {
  11821. break; /* flush the current block */
  11822. }
  11823. }
  11824. /* Insert the string window[strstart .. strstart+2] in the
  11825. * dictionary, and set hash_head to the head of the hash chain:
  11826. */
  11827. hash_head = 0/*NIL*/;
  11828. if (s.lookahead >= MIN_MATCH) {
  11829. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  11830. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  11831. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  11832. s.head[s.ins_h] = s.strstart;
  11833. /***/
  11834. }
  11835. /* Find the longest match, discarding those <= prev_length.
  11836. * At this point we have always match_length < MIN_MATCH
  11837. */
  11838. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  11839. /* To simplify the code, we prevent matches with the string
  11840. * of window index 0 (in particular we have to avoid a match
  11841. * of the string with itself at the start of the input file).
  11842. */
  11843. s.match_length = longest_match(s, hash_head);
  11844. /* longest_match() sets match_start */
  11845. }
  11846. if (s.match_length >= MIN_MATCH) {
  11847. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  11848. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  11849. s.match_length - MIN_MATCH, bflush); ***/
  11850. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  11851. s.lookahead -= s.match_length;
  11852. /* Insert new strings in the hash table only if the match length
  11853. * is not too large. This saves time but degrades compression.
  11854. */
  11855. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  11856. s.match_length--; /* string at strstart already in table */
  11857. do {
  11858. s.strstart++;
  11859. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  11860. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  11861. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  11862. s.head[s.ins_h] = s.strstart;
  11863. /***/
  11864. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  11865. * always MIN_MATCH bytes ahead.
  11866. */
  11867. } while (--s.match_length !== 0);
  11868. s.strstart++;
  11869. } else
  11870. {
  11871. s.strstart += s.match_length;
  11872. s.match_length = 0;
  11873. s.ins_h = s.window[s.strstart];
  11874. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  11875. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  11876. //#if MIN_MATCH != 3
  11877. // Call UPDATE_HASH() MIN_MATCH-3 more times
  11878. //#endif
  11879. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  11880. * matter since it will be recomputed at next deflate call.
  11881. */
  11882. }
  11883. } else {
  11884. /* No match, output a literal byte */
  11885. //Tracevv((stderr,"%c", s.window[s.strstart]));
  11886. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  11887. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  11888. s.lookahead--;
  11889. s.strstart++;
  11890. }
  11891. if (bflush) {
  11892. /*** FLUSH_BLOCK(s, 0); ***/
  11893. flush_block_only(s, false);
  11894. if (s.strm.avail_out === 0) {
  11895. return BS_NEED_MORE;
  11896. }
  11897. /***/
  11898. }
  11899. }
  11900. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  11901. if (flush === Z_FINISH) {
  11902. /*** FLUSH_BLOCK(s, 1); ***/
  11903. flush_block_only(s, true);
  11904. if (s.strm.avail_out === 0) {
  11905. return BS_FINISH_STARTED;
  11906. }
  11907. /***/
  11908. return BS_FINISH_DONE;
  11909. }
  11910. if (s.last_lit) {
  11911. /*** FLUSH_BLOCK(s, 0); ***/
  11912. flush_block_only(s, false);
  11913. if (s.strm.avail_out === 0) {
  11914. return BS_NEED_MORE;
  11915. }
  11916. /***/
  11917. }
  11918. return BS_BLOCK_DONE;
  11919. }
  11920. /* ===========================================================================
  11921. * Same as above, but achieves better compression. We use a lazy
  11922. * evaluation for matches: a match is finally adopted only if there is
  11923. * no better match at the next window position.
  11924. */
  11925. function deflate_slow(s, flush) {
  11926. var hash_head; /* head of hash chain */
  11927. var bflush; /* set if current block must be flushed */
  11928. var max_insert;
  11929. /* Process the input block. */
  11930. for (;;) {
  11931. /* Make sure that we always have enough lookahead, except
  11932. * at the end of the input file. We need MAX_MATCH bytes
  11933. * for the next match, plus MIN_MATCH bytes to insert the
  11934. * string following the next match.
  11935. */
  11936. if (s.lookahead < MIN_LOOKAHEAD) {
  11937. fill_window(s);
  11938. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  11939. return BS_NEED_MORE;
  11940. }
  11941. if (s.lookahead === 0) { break; } /* flush the current block */
  11942. }
  11943. /* Insert the string window[strstart .. strstart+2] in the
  11944. * dictionary, and set hash_head to the head of the hash chain:
  11945. */
  11946. hash_head = 0/*NIL*/;
  11947. if (s.lookahead >= MIN_MATCH) {
  11948. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  11949. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  11950. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  11951. s.head[s.ins_h] = s.strstart;
  11952. /***/
  11953. }
  11954. /* Find the longest match, discarding those <= prev_length.
  11955. */
  11956. s.prev_length = s.match_length;
  11957. s.prev_match = s.match_start;
  11958. s.match_length = MIN_MATCH-1;
  11959. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  11960. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  11961. /* To simplify the code, we prevent matches with the string
  11962. * of window index 0 (in particular we have to avoid a match
  11963. * of the string with itself at the start of the input file).
  11964. */
  11965. s.match_length = longest_match(s, hash_head);
  11966. /* longest_match() sets match_start */
  11967. if (s.match_length <= 5 &&
  11968. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  11969. /* If prev_match is also MIN_MATCH, match_start is garbage
  11970. * but we will ignore the current match anyway.
  11971. */
  11972. s.match_length = MIN_MATCH-1;
  11973. }
  11974. }
  11975. /* If there was a match at the previous step and the current
  11976. * match is not better, output the previous match:
  11977. */
  11978. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  11979. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  11980. /* Do not insert strings in hash table beyond this. */
  11981. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  11982. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  11983. s.prev_length - MIN_MATCH, bflush);***/
  11984. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  11985. /* Insert in hash table all strings up to the end of the match.
  11986. * strstart-1 and strstart are already inserted. If there is not
  11987. * enough lookahead, the last two strings are not inserted in
  11988. * the hash table.
  11989. */
  11990. s.lookahead -= s.prev_length-1;
  11991. s.prev_length -= 2;
  11992. do {
  11993. if (++s.strstart <= max_insert) {
  11994. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  11995. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  11996. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  11997. s.head[s.ins_h] = s.strstart;
  11998. /***/
  11999. }
  12000. } while (--s.prev_length !== 0);
  12001. s.match_available = 0;
  12002. s.match_length = MIN_MATCH-1;
  12003. s.strstart++;
  12004. if (bflush) {
  12005. /*** FLUSH_BLOCK(s, 0); ***/
  12006. flush_block_only(s, false);
  12007. if (s.strm.avail_out === 0) {
  12008. return BS_NEED_MORE;
  12009. }
  12010. /***/
  12011. }
  12012. } else if (s.match_available) {
  12013. /* If there was no match at the previous position, output a
  12014. * single literal. If there was a match but the current match
  12015. * is longer, truncate the previous match to a single literal.
  12016. */
  12017. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  12018. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  12019. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  12020. if (bflush) {
  12021. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  12022. flush_block_only(s, false);
  12023. /***/
  12024. }
  12025. s.strstart++;
  12026. s.lookahead--;
  12027. if (s.strm.avail_out === 0) {
  12028. return BS_NEED_MORE;
  12029. }
  12030. } else {
  12031. /* There is no previous match to compare with, wait for
  12032. * the next step to decide.
  12033. */
  12034. s.match_available = 1;
  12035. s.strstart++;
  12036. s.lookahead--;
  12037. }
  12038. }
  12039. //Assert (flush != Z_NO_FLUSH, "no flush?");
  12040. if (s.match_available) {
  12041. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  12042. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  12043. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  12044. s.match_available = 0;
  12045. }
  12046. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  12047. if (flush === Z_FINISH) {
  12048. /*** FLUSH_BLOCK(s, 1); ***/
  12049. flush_block_only(s, true);
  12050. if (s.strm.avail_out === 0) {
  12051. return BS_FINISH_STARTED;
  12052. }
  12053. /***/
  12054. return BS_FINISH_DONE;
  12055. }
  12056. if (s.last_lit) {
  12057. /*** FLUSH_BLOCK(s, 0); ***/
  12058. flush_block_only(s, false);
  12059. if (s.strm.avail_out === 0) {
  12060. return BS_NEED_MORE;
  12061. }
  12062. /***/
  12063. }
  12064. return BS_BLOCK_DONE;
  12065. }
  12066. /* ===========================================================================
  12067. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  12068. * one. Do not maintain a hash table. (It will be regenerated if this run of
  12069. * deflate switches away from Z_RLE.)
  12070. */
  12071. function deflate_rle(s, flush) {
  12072. var bflush; /* set if current block must be flushed */
  12073. var prev; /* byte at distance one to match */
  12074. var scan, strend; /* scan goes up to strend for length of run */
  12075. var _win = s.window;
  12076. for (;;) {
  12077. /* Make sure that we always have enough lookahead, except
  12078. * at the end of the input file. We need MAX_MATCH bytes
  12079. * for the longest run, plus one for the unrolled loop.
  12080. */
  12081. if (s.lookahead <= MAX_MATCH) {
  12082. fill_window(s);
  12083. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  12084. return BS_NEED_MORE;
  12085. }
  12086. if (s.lookahead === 0) { break; } /* flush the current block */
  12087. }
  12088. /* See how many times the previous byte repeats */
  12089. s.match_length = 0;
  12090. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  12091. scan = s.strstart - 1;
  12092. prev = _win[scan];
  12093. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  12094. strend = s.strstart + MAX_MATCH;
  12095. do {
  12096. /*jshint noempty:false*/
  12097. } while (prev === _win[++scan] && prev === _win[++scan] &&
  12098. prev === _win[++scan] && prev === _win[++scan] &&
  12099. prev === _win[++scan] && prev === _win[++scan] &&
  12100. prev === _win[++scan] && prev === _win[++scan] &&
  12101. scan < strend);
  12102. s.match_length = MAX_MATCH - (strend - scan);
  12103. if (s.match_length > s.lookahead) {
  12104. s.match_length = s.lookahead;
  12105. }
  12106. }
  12107. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  12108. }
  12109. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  12110. if (s.match_length >= MIN_MATCH) {
  12111. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  12112. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  12113. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  12114. s.lookahead -= s.match_length;
  12115. s.strstart += s.match_length;
  12116. s.match_length = 0;
  12117. } else {
  12118. /* No match, output a literal byte */
  12119. //Tracevv((stderr,"%c", s->window[s->strstart]));
  12120. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  12121. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  12122. s.lookahead--;
  12123. s.strstart++;
  12124. }
  12125. if (bflush) {
  12126. /*** FLUSH_BLOCK(s, 0); ***/
  12127. flush_block_only(s, false);
  12128. if (s.strm.avail_out === 0) {
  12129. return BS_NEED_MORE;
  12130. }
  12131. /***/
  12132. }
  12133. }
  12134. s.insert = 0;
  12135. if (flush === Z_FINISH) {
  12136. /*** FLUSH_BLOCK(s, 1); ***/
  12137. flush_block_only(s, true);
  12138. if (s.strm.avail_out === 0) {
  12139. return BS_FINISH_STARTED;
  12140. }
  12141. /***/
  12142. return BS_FINISH_DONE;
  12143. }
  12144. if (s.last_lit) {
  12145. /*** FLUSH_BLOCK(s, 0); ***/
  12146. flush_block_only(s, false);
  12147. if (s.strm.avail_out === 0) {
  12148. return BS_NEED_MORE;
  12149. }
  12150. /***/
  12151. }
  12152. return BS_BLOCK_DONE;
  12153. }
  12154. /* ===========================================================================
  12155. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  12156. * (It will be regenerated if this run of deflate switches away from Huffman.)
  12157. */
  12158. function deflate_huff(s, flush) {
  12159. var bflush; /* set if current block must be flushed */
  12160. for (;;) {
  12161. /* Make sure that we have a literal to write. */
  12162. if (s.lookahead === 0) {
  12163. fill_window(s);
  12164. if (s.lookahead === 0) {
  12165. if (flush === Z_NO_FLUSH) {
  12166. return BS_NEED_MORE;
  12167. }
  12168. break; /* flush the current block */
  12169. }
  12170. }
  12171. /* Output a literal byte */
  12172. s.match_length = 0;
  12173. //Tracevv((stderr,"%c", s->window[s->strstart]));
  12174. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  12175. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  12176. s.lookahead--;
  12177. s.strstart++;
  12178. if (bflush) {
  12179. /*** FLUSH_BLOCK(s, 0); ***/
  12180. flush_block_only(s, false);
  12181. if (s.strm.avail_out === 0) {
  12182. return BS_NEED_MORE;
  12183. }
  12184. /***/
  12185. }
  12186. }
  12187. s.insert = 0;
  12188. if (flush === Z_FINISH) {
  12189. /*** FLUSH_BLOCK(s, 1); ***/
  12190. flush_block_only(s, true);
  12191. if (s.strm.avail_out === 0) {
  12192. return BS_FINISH_STARTED;
  12193. }
  12194. /***/
  12195. return BS_FINISH_DONE;
  12196. }
  12197. if (s.last_lit) {
  12198. /*** FLUSH_BLOCK(s, 0); ***/
  12199. flush_block_only(s, false);
  12200. if (s.strm.avail_out === 0) {
  12201. return BS_NEED_MORE;
  12202. }
  12203. /***/
  12204. }
  12205. return BS_BLOCK_DONE;
  12206. }
  12207. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  12208. * the desired pack level (0..9). The values given below have been tuned to
  12209. * exclude worst case performance for pathological files. Better values may be
  12210. * found for specific files.
  12211. */
  12212. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  12213. this.good_length = good_length;
  12214. this.max_lazy = max_lazy;
  12215. this.nice_length = nice_length;
  12216. this.max_chain = max_chain;
  12217. this.func = func;
  12218. };
  12219. var configuration_table;
  12220. configuration_table = [
  12221. /* good lazy nice chain */
  12222. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  12223. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  12224. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  12225. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  12226. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  12227. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  12228. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  12229. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  12230. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  12231. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  12232. ];
  12233. /* ===========================================================================
  12234. * Initialize the "longest match" routines for a new zlib stream
  12235. */
  12236. function lm_init(s) {
  12237. s.window_size = 2 * s.w_size;
  12238. /*** CLEAR_HASH(s); ***/
  12239. zero(s.head); // Fill with NIL (= 0);
  12240. /* Set the default configuration parameters:
  12241. */
  12242. s.max_lazy_match = configuration_table[s.level].max_lazy;
  12243. s.good_match = configuration_table[s.level].good_length;
  12244. s.nice_match = configuration_table[s.level].nice_length;
  12245. s.max_chain_length = configuration_table[s.level].max_chain;
  12246. s.strstart = 0;
  12247. s.block_start = 0;
  12248. s.lookahead = 0;
  12249. s.insert = 0;
  12250. s.match_length = s.prev_length = MIN_MATCH - 1;
  12251. s.match_available = 0;
  12252. s.ins_h = 0;
  12253. }
  12254. function DeflateState() {
  12255. this.strm = null; /* pointer back to this zlib stream */
  12256. this.status = 0; /* as the name implies */
  12257. this.pending_buf = null; /* output still pending */
  12258. this.pending_buf_size = 0; /* size of pending_buf */
  12259. this.pending_out = 0; /* next pending byte to output to the stream */
  12260. this.pending = 0; /* nb of bytes in the pending buffer */
  12261. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  12262. this.gzhead = null; /* gzip header information to write */
  12263. this.gzindex = 0; /* where in extra, name, or comment */
  12264. this.method = Z_DEFLATED; /* can only be DEFLATED */
  12265. this.last_flush = -1; /* value of flush param for previous deflate call */
  12266. this.w_size = 0; /* LZ77 window size (32K by default) */
  12267. this.w_bits = 0; /* log2(w_size) (8..16) */
  12268. this.w_mask = 0; /* w_size - 1 */
  12269. this.window = null;
  12270. /* Sliding window. Input bytes are read into the second half of the window,
  12271. * and move to the first half later to keep a dictionary of at least wSize
  12272. * bytes. With this organization, matches are limited to a distance of
  12273. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  12274. * performed with a length multiple of the block size.
  12275. */
  12276. this.window_size = 0;
  12277. /* Actual size of window: 2*wSize, except when the user input buffer
  12278. * is directly used as sliding window.
  12279. */
  12280. this.prev = null;
  12281. /* Link to older string with same hash index. To limit the size of this
  12282. * array to 64K, this link is maintained only for the last 32K strings.
  12283. * An index in this array is thus a window index modulo 32K.
  12284. */
  12285. this.head = null; /* Heads of the hash chains or NIL. */
  12286. this.ins_h = 0; /* hash index of string to be inserted */
  12287. this.hash_size = 0; /* number of elements in hash table */
  12288. this.hash_bits = 0; /* log2(hash_size) */
  12289. this.hash_mask = 0; /* hash_size-1 */
  12290. this.hash_shift = 0;
  12291. /* Number of bits by which ins_h must be shifted at each input
  12292. * step. It must be such that after MIN_MATCH steps, the oldest
  12293. * byte no longer takes part in the hash key, that is:
  12294. * hash_shift * MIN_MATCH >= hash_bits
  12295. */
  12296. this.block_start = 0;
  12297. /* Window position at the beginning of the current output block. Gets
  12298. * negative when the window is moved backwards.
  12299. */
  12300. this.match_length = 0; /* length of best match */
  12301. this.prev_match = 0; /* previous match */
  12302. this.match_available = 0; /* set if previous match exists */
  12303. this.strstart = 0; /* start of string to insert */
  12304. this.match_start = 0; /* start of matching string */
  12305. this.lookahead = 0; /* number of valid bytes ahead in window */
  12306. this.prev_length = 0;
  12307. /* Length of the best match at previous step. Matches not greater than this
  12308. * are discarded. This is used in the lazy match evaluation.
  12309. */
  12310. this.max_chain_length = 0;
  12311. /* To speed up deflation, hash chains are never searched beyond this
  12312. * length. A higher limit improves compression ratio but degrades the
  12313. * speed.
  12314. */
  12315. this.max_lazy_match = 0;
  12316. /* Attempt to find a better match only when the current match is strictly
  12317. * smaller than this value. This mechanism is used only for compression
  12318. * levels >= 4.
  12319. */
  12320. // That's alias to max_lazy_match, don't use directly
  12321. //this.max_insert_length = 0;
  12322. /* Insert new strings in the hash table only if the match length is not
  12323. * greater than this length. This saves time but degrades compression.
  12324. * max_insert_length is used only for compression levels <= 3.
  12325. */
  12326. this.level = 0; /* compression level (1..9) */
  12327. this.strategy = 0; /* favor or force Huffman coding*/
  12328. this.good_match = 0;
  12329. /* Use a faster search when the previous match is longer than this */
  12330. this.nice_match = 0; /* Stop searching when current match exceeds this */
  12331. /* used by trees.c: */
  12332. /* Didn't use ct_data typedef below to suppress compiler warning */
  12333. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  12334. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  12335. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  12336. // Use flat array of DOUBLE size, with interleaved fata,
  12337. // because JS does not support effective
  12338. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  12339. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  12340. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  12341. zero(this.dyn_ltree);
  12342. zero(this.dyn_dtree);
  12343. zero(this.bl_tree);
  12344. this.l_desc = null; /* desc. for literal tree */
  12345. this.d_desc = null; /* desc. for distance tree */
  12346. this.bl_desc = null; /* desc. for bit length tree */
  12347. //ush bl_count[MAX_BITS+1];
  12348. this.bl_count = new utils.Buf16(MAX_BITS+1);
  12349. /* number of codes at each bit length for an optimal tree */
  12350. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  12351. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  12352. zero(this.heap);
  12353. this.heap_len = 0; /* number of elements in the heap */
  12354. this.heap_max = 0; /* element of largest frequency */
  12355. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  12356. * The same heap array is used to build all trees.
  12357. */
  12358. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  12359. zero(this.depth);
  12360. /* Depth of each subtree used as tie breaker for trees of equal frequency
  12361. */
  12362. this.l_buf = 0; /* buffer index for literals or lengths */
  12363. this.lit_bufsize = 0;
  12364. /* Size of match buffer for literals/lengths. There are 4 reasons for
  12365. * limiting lit_bufsize to 64K:
  12366. * - frequencies can be kept in 16 bit counters
  12367. * - if compression is not successful for the first block, all input
  12368. * data is still in the window so we can still emit a stored block even
  12369. * when input comes from standard input. (This can also be done for
  12370. * all blocks if lit_bufsize is not greater than 32K.)
  12371. * - if compression is not successful for a file smaller than 64K, we can
  12372. * even emit a stored file instead of a stored block (saving 5 bytes).
  12373. * This is applicable only for zip (not gzip or zlib).
  12374. * - creating new Huffman trees less frequently may not provide fast
  12375. * adaptation to changes in the input data statistics. (Take for
  12376. * example a binary file with poorly compressible code followed by
  12377. * a highly compressible string table.) Smaller buffer sizes give
  12378. * fast adaptation but have of course the overhead of transmitting
  12379. * trees more frequently.
  12380. * - I can't count above 4
  12381. */
  12382. this.last_lit = 0; /* running index in l_buf */
  12383. this.d_buf = 0;
  12384. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  12385. * the same number of elements. To use different lengths, an extra flag
  12386. * array would be necessary.
  12387. */
  12388. this.opt_len = 0; /* bit length of current block with optimal trees */
  12389. this.static_len = 0; /* bit length of current block with static trees */
  12390. this.matches = 0; /* number of string matches in current block */
  12391. this.insert = 0; /* bytes at end of window left to insert */
  12392. this.bi_buf = 0;
  12393. /* Output buffer. bits are inserted starting at the bottom (least
  12394. * significant bits).
  12395. */
  12396. this.bi_valid = 0;
  12397. /* Number of valid bits in bi_buf. All bits above the last valid bit
  12398. * are always zero.
  12399. */
  12400. // Used for window memory init. We safely ignore it for JS. That makes
  12401. // sense only for pointers and memory check tools.
  12402. //this.high_water = 0;
  12403. /* High water mark offset in window for initialized bytes -- bytes above
  12404. * this are set to zero in order to avoid memory check warnings when
  12405. * longest match routines access bytes past the input. This is then
  12406. * updated to the new high water mark.
  12407. */
  12408. }
  12409. function deflateResetKeep(strm) {
  12410. var s;
  12411. if (!strm || !strm.state) {
  12412. return err(strm, Z_STREAM_ERROR);
  12413. }
  12414. strm.total_in = strm.total_out = 0;
  12415. strm.data_type = Z_UNKNOWN;
  12416. s = strm.state;
  12417. s.pending = 0;
  12418. s.pending_out = 0;
  12419. if (s.wrap < 0) {
  12420. s.wrap = -s.wrap;
  12421. /* was made negative by deflate(..., Z_FINISH); */
  12422. }
  12423. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  12424. strm.adler = (s.wrap === 2) ?
  12425. 0 // crc32(0, Z_NULL, 0)
  12426. :
  12427. 1; // adler32(0, Z_NULL, 0)
  12428. s.last_flush = Z_NO_FLUSH;
  12429. trees._tr_init(s);
  12430. return Z_OK;
  12431. }
  12432. function deflateReset(strm) {
  12433. var ret = deflateResetKeep(strm);
  12434. if (ret === Z_OK) {
  12435. lm_init(strm.state);
  12436. }
  12437. return ret;
  12438. }
  12439. function deflateSetHeader(strm, head) {
  12440. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  12441. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  12442. strm.state.gzhead = head;
  12443. return Z_OK;
  12444. }
  12445. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  12446. if (!strm) { // === Z_NULL
  12447. return Z_STREAM_ERROR;
  12448. }
  12449. var wrap = 1;
  12450. if (level === Z_DEFAULT_COMPRESSION) {
  12451. level = 6;
  12452. }
  12453. if (windowBits < 0) { /* suppress zlib wrapper */
  12454. wrap = 0;
  12455. windowBits = -windowBits;
  12456. }
  12457. else if (windowBits > 15) {
  12458. wrap = 2; /* write gzip wrapper instead */
  12459. windowBits -= 16;
  12460. }
  12461. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  12462. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  12463. strategy < 0 || strategy > Z_FIXED) {
  12464. return err(strm, Z_STREAM_ERROR);
  12465. }
  12466. if (windowBits === 8) {
  12467. windowBits = 9;
  12468. }
  12469. /* until 256-byte window bug fixed */
  12470. var s = new DeflateState();
  12471. strm.state = s;
  12472. s.strm = strm;
  12473. s.wrap = wrap;
  12474. s.gzhead = null;
  12475. s.w_bits = windowBits;
  12476. s.w_size = 1 << s.w_bits;
  12477. s.w_mask = s.w_size - 1;
  12478. s.hash_bits = memLevel + 7;
  12479. s.hash_size = 1 << s.hash_bits;
  12480. s.hash_mask = s.hash_size - 1;
  12481. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  12482. s.window = new utils.Buf8(s.w_size * 2);
  12483. s.head = new utils.Buf16(s.hash_size);
  12484. s.prev = new utils.Buf16(s.w_size);
  12485. // Don't need mem init magic for JS.
  12486. //s.high_water = 0; /* nothing written to s->window yet */
  12487. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  12488. s.pending_buf_size = s.lit_bufsize * 4;
  12489. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  12490. s.d_buf = s.lit_bufsize >> 1;
  12491. s.l_buf = (1 + 2) * s.lit_bufsize;
  12492. s.level = level;
  12493. s.strategy = strategy;
  12494. s.method = method;
  12495. return deflateReset(strm);
  12496. }
  12497. function deflateInit(strm, level) {
  12498. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  12499. }
  12500. function deflate(strm, flush) {
  12501. var old_flush, s;
  12502. var beg, val; // for gzip header write only
  12503. if (!strm || !strm.state ||
  12504. flush > Z_BLOCK || flush < 0) {
  12505. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  12506. }
  12507. s = strm.state;
  12508. if (!strm.output ||
  12509. (!strm.input && strm.avail_in !== 0) ||
  12510. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  12511. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  12512. }
  12513. s.strm = strm; /* just in case */
  12514. old_flush = s.last_flush;
  12515. s.last_flush = flush;
  12516. /* Write the header */
  12517. if (s.status === INIT_STATE) {
  12518. if (s.wrap === 2) { // GZIP header
  12519. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  12520. put_byte(s, 31);
  12521. put_byte(s, 139);
  12522. put_byte(s, 8);
  12523. if (!s.gzhead) { // s->gzhead == Z_NULL
  12524. put_byte(s, 0);
  12525. put_byte(s, 0);
  12526. put_byte(s, 0);
  12527. put_byte(s, 0);
  12528. put_byte(s, 0);
  12529. put_byte(s, s.level === 9 ? 2 :
  12530. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  12531. 4 : 0));
  12532. put_byte(s, OS_CODE);
  12533. s.status = BUSY_STATE;
  12534. }
  12535. else {
  12536. put_byte(s, (s.gzhead.text ? 1 : 0) +
  12537. (s.gzhead.hcrc ? 2 : 0) +
  12538. (!s.gzhead.extra ? 0 : 4) +
  12539. (!s.gzhead.name ? 0 : 8) +
  12540. (!s.gzhead.comment ? 0 : 16)
  12541. );
  12542. put_byte(s, s.gzhead.time & 0xff);
  12543. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  12544. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  12545. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  12546. put_byte(s, s.level === 9 ? 2 :
  12547. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  12548. 4 : 0));
  12549. put_byte(s, s.gzhead.os & 0xff);
  12550. if (s.gzhead.extra && s.gzhead.extra.length) {
  12551. put_byte(s, s.gzhead.extra.length & 0xff);
  12552. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  12553. }
  12554. if (s.gzhead.hcrc) {
  12555. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  12556. }
  12557. s.gzindex = 0;
  12558. s.status = EXTRA_STATE;
  12559. }
  12560. }
  12561. else // DEFLATE header
  12562. {
  12563. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  12564. var level_flags = -1;
  12565. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  12566. level_flags = 0;
  12567. } else if (s.level < 6) {
  12568. level_flags = 1;
  12569. } else if (s.level === 6) {
  12570. level_flags = 2;
  12571. } else {
  12572. level_flags = 3;
  12573. }
  12574. header |= (level_flags << 6);
  12575. if (s.strstart !== 0) { header |= PRESET_DICT; }
  12576. header += 31 - (header % 31);
  12577. s.status = BUSY_STATE;
  12578. putShortMSB(s, header);
  12579. /* Save the adler32 of the preset dictionary: */
  12580. if (s.strstart !== 0) {
  12581. putShortMSB(s, strm.adler >>> 16);
  12582. putShortMSB(s, strm.adler & 0xffff);
  12583. }
  12584. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  12585. }
  12586. }
  12587. //#ifdef GZIP
  12588. if (s.status === EXTRA_STATE) {
  12589. if (s.gzhead.extra/* != Z_NULL*/) {
  12590. beg = s.pending; /* start of bytes to update crc */
  12591. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  12592. if (s.pending === s.pending_buf_size) {
  12593. if (s.gzhead.hcrc && s.pending > beg) {
  12594. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12595. }
  12596. flush_pending(strm);
  12597. beg = s.pending;
  12598. if (s.pending === s.pending_buf_size) {
  12599. break;
  12600. }
  12601. }
  12602. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  12603. s.gzindex++;
  12604. }
  12605. if (s.gzhead.hcrc && s.pending > beg) {
  12606. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12607. }
  12608. if (s.gzindex === s.gzhead.extra.length) {
  12609. s.gzindex = 0;
  12610. s.status = NAME_STATE;
  12611. }
  12612. }
  12613. else {
  12614. s.status = NAME_STATE;
  12615. }
  12616. }
  12617. if (s.status === NAME_STATE) {
  12618. if (s.gzhead.name/* != Z_NULL*/) {
  12619. beg = s.pending; /* start of bytes to update crc */
  12620. //int val;
  12621. do {
  12622. if (s.pending === s.pending_buf_size) {
  12623. if (s.gzhead.hcrc && s.pending > beg) {
  12624. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12625. }
  12626. flush_pending(strm);
  12627. beg = s.pending;
  12628. if (s.pending === s.pending_buf_size) {
  12629. val = 1;
  12630. break;
  12631. }
  12632. }
  12633. // JS specific: little magic to add zero terminator to end of string
  12634. if (s.gzindex < s.gzhead.name.length) {
  12635. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  12636. } else {
  12637. val = 0;
  12638. }
  12639. put_byte(s, val);
  12640. } while (val !== 0);
  12641. if (s.gzhead.hcrc && s.pending > beg) {
  12642. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12643. }
  12644. if (val === 0) {
  12645. s.gzindex = 0;
  12646. s.status = COMMENT_STATE;
  12647. }
  12648. }
  12649. else {
  12650. s.status = COMMENT_STATE;
  12651. }
  12652. }
  12653. if (s.status === COMMENT_STATE) {
  12654. if (s.gzhead.comment/* != Z_NULL*/) {
  12655. beg = s.pending; /* start of bytes to update crc */
  12656. //int val;
  12657. do {
  12658. if (s.pending === s.pending_buf_size) {
  12659. if (s.gzhead.hcrc && s.pending > beg) {
  12660. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12661. }
  12662. flush_pending(strm);
  12663. beg = s.pending;
  12664. if (s.pending === s.pending_buf_size) {
  12665. val = 1;
  12666. break;
  12667. }
  12668. }
  12669. // JS specific: little magic to add zero terminator to end of string
  12670. if (s.gzindex < s.gzhead.comment.length) {
  12671. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  12672. } else {
  12673. val = 0;
  12674. }
  12675. put_byte(s, val);
  12676. } while (val !== 0);
  12677. if (s.gzhead.hcrc && s.pending > beg) {
  12678. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12679. }
  12680. if (val === 0) {
  12681. s.status = HCRC_STATE;
  12682. }
  12683. }
  12684. else {
  12685. s.status = HCRC_STATE;
  12686. }
  12687. }
  12688. if (s.status === HCRC_STATE) {
  12689. if (s.gzhead.hcrc) {
  12690. if (s.pending + 2 > s.pending_buf_size) {
  12691. flush_pending(strm);
  12692. }
  12693. if (s.pending + 2 <= s.pending_buf_size) {
  12694. put_byte(s, strm.adler & 0xff);
  12695. put_byte(s, (strm.adler >> 8) & 0xff);
  12696. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  12697. s.status = BUSY_STATE;
  12698. }
  12699. }
  12700. else {
  12701. s.status = BUSY_STATE;
  12702. }
  12703. }
  12704. //#endif
  12705. /* Flush as much pending output as possible */
  12706. if (s.pending !== 0) {
  12707. flush_pending(strm);
  12708. if (strm.avail_out === 0) {
  12709. /* Since avail_out is 0, deflate will be called again with
  12710. * more output space, but possibly with both pending and
  12711. * avail_in equal to zero. There won't be anything to do,
  12712. * but this is not an error situation so make sure we
  12713. * return OK instead of BUF_ERROR at next call of deflate:
  12714. */
  12715. s.last_flush = -1;
  12716. return Z_OK;
  12717. }
  12718. /* Make sure there is something to do and avoid duplicate consecutive
  12719. * flushes. For repeated and useless calls with Z_FINISH, we keep
  12720. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  12721. */
  12722. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  12723. flush !== Z_FINISH) {
  12724. return err(strm, Z_BUF_ERROR);
  12725. }
  12726. /* User must not provide more input after the first FINISH: */
  12727. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  12728. return err(strm, Z_BUF_ERROR);
  12729. }
  12730. /* Start a new block or continue the current one.
  12731. */
  12732. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  12733. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  12734. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  12735. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  12736. configuration_table[s.level].func(s, flush));
  12737. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  12738. s.status = FINISH_STATE;
  12739. }
  12740. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  12741. if (strm.avail_out === 0) {
  12742. s.last_flush = -1;
  12743. /* avoid BUF_ERROR next call, see above */
  12744. }
  12745. return Z_OK;
  12746. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  12747. * of deflate should use the same flush parameter to make sure
  12748. * that the flush is complete. So we don't have to output an
  12749. * empty block here, this will be done at next call. This also
  12750. * ensures that for a very small output buffer, we emit at most
  12751. * one empty block.
  12752. */
  12753. }
  12754. if (bstate === BS_BLOCK_DONE) {
  12755. if (flush === Z_PARTIAL_FLUSH) {
  12756. trees._tr_align(s);
  12757. }
  12758. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  12759. trees._tr_stored_block(s, 0, 0, false);
  12760. /* For a full flush, this empty block will be recognized
  12761. * as a special marker by inflate_sync().
  12762. */
  12763. if (flush === Z_FULL_FLUSH) {
  12764. /*** CLEAR_HASH(s); ***/ /* forget history */
  12765. zero(s.head); // Fill with NIL (= 0);
  12766. if (s.lookahead === 0) {
  12767. s.strstart = 0;
  12768. s.block_start = 0;
  12769. s.insert = 0;
  12770. }
  12771. }
  12772. }
  12773. flush_pending(strm);
  12774. if (strm.avail_out === 0) {
  12775. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  12776. return Z_OK;
  12777. }
  12778. }
  12779. }
  12780. //Assert(strm->avail_out > 0, "bug2");
  12781. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  12782. if (flush !== Z_FINISH) { return Z_OK; }
  12783. if (s.wrap <= 0) { return Z_STREAM_END; }
  12784. /* Write the trailer */
  12785. if (s.wrap === 2) {
  12786. put_byte(s, strm.adler & 0xff);
  12787. put_byte(s, (strm.adler >> 8) & 0xff);
  12788. put_byte(s, (strm.adler >> 16) & 0xff);
  12789. put_byte(s, (strm.adler >> 24) & 0xff);
  12790. put_byte(s, strm.total_in & 0xff);
  12791. put_byte(s, (strm.total_in >> 8) & 0xff);
  12792. put_byte(s, (strm.total_in >> 16) & 0xff);
  12793. put_byte(s, (strm.total_in >> 24) & 0xff);
  12794. }
  12795. else
  12796. {
  12797. putShortMSB(s, strm.adler >>> 16);
  12798. putShortMSB(s, strm.adler & 0xffff);
  12799. }
  12800. flush_pending(strm);
  12801. /* If avail_out is zero, the application will call deflate again
  12802. * to flush the rest.
  12803. */
  12804. if (s.wrap > 0) { s.wrap = -s.wrap; }
  12805. /* write the trailer only once! */
  12806. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  12807. }
  12808. function deflateEnd(strm) {
  12809. var status;
  12810. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  12811. return Z_STREAM_ERROR;
  12812. }
  12813. status = strm.state.status;
  12814. if (status !== INIT_STATE &&
  12815. status !== EXTRA_STATE &&
  12816. status !== NAME_STATE &&
  12817. status !== COMMENT_STATE &&
  12818. status !== HCRC_STATE &&
  12819. status !== BUSY_STATE &&
  12820. status !== FINISH_STATE
  12821. ) {
  12822. return err(strm, Z_STREAM_ERROR);
  12823. }
  12824. strm.state = null;
  12825. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  12826. }
  12827. /* =========================================================================
  12828. * Copy the source state to the destination state
  12829. */
  12830. //function deflateCopy(dest, source) {
  12831. //
  12832. //}
  12833. exports.deflateInit = deflateInit;
  12834. exports.deflateInit2 = deflateInit2;
  12835. exports.deflateReset = deflateReset;
  12836. exports.deflateResetKeep = deflateResetKeep;
  12837. exports.deflateSetHeader = deflateSetHeader;
  12838. exports.deflate = deflate;
  12839. exports.deflateEnd = deflateEnd;
  12840. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  12841. /* Not implemented
  12842. exports.deflateBound = deflateBound;
  12843. exports.deflateCopy = deflateCopy;
  12844. exports.deflateSetDictionary = deflateSetDictionary;
  12845. exports.deflateParams = deflateParams;
  12846. exports.deflatePending = deflatePending;
  12847. exports.deflatePrime = deflatePrime;
  12848. exports.deflateTune = deflateTune;
  12849. */
  12850. },{"../utils/common":39,"./adler32":41,"./crc32":43,"./messages":49,"./trees":50}],45:[function(require,module,exports){
  12851. 'use strict';
  12852. function GZheader() {
  12853. /* true if compressed data believed to be text */
  12854. this.text = 0;
  12855. /* modification time */
  12856. this.time = 0;
  12857. /* extra flags (not used when writing a gzip file) */
  12858. this.xflags = 0;
  12859. /* operating system */
  12860. this.os = 0;
  12861. /* pointer to extra field or Z_NULL if none */
  12862. this.extra = null;
  12863. /* extra field length (valid if extra != Z_NULL) */
  12864. this.extra_len = 0; // Actually, we don't need it in JS,
  12865. // but leave for few code modifications
  12866. //
  12867. // Setup limits is not necessary because in js we should not preallocate memory
  12868. // for inflate use constant limit in 65536 bytes
  12869. //
  12870. /* space at extra (only when reading header) */
  12871. // this.extra_max = 0;
  12872. /* pointer to zero-terminated file name or Z_NULL */
  12873. this.name = '';
  12874. /* space at name (only when reading header) */
  12875. // this.name_max = 0;
  12876. /* pointer to zero-terminated comment or Z_NULL */
  12877. this.comment = '';
  12878. /* space at comment (only when reading header) */
  12879. // this.comm_max = 0;
  12880. /* true if there was or will be a header crc */
  12881. this.hcrc = 0;
  12882. /* true when done reading gzip header (not used when writing a gzip file) */
  12883. this.done = false;
  12884. }
  12885. module.exports = GZheader;
  12886. },{}],46:[function(require,module,exports){
  12887. 'use strict';
  12888. // See state defs from inflate.js
  12889. var BAD = 30; /* got a data error -- remain here until reset */
  12890. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  12891. /*
  12892. Decode literal, length, and distance codes and write out the resulting
  12893. literal and match bytes until either not enough input or output is
  12894. available, an end-of-block is encountered, or a data error is encountered.
  12895. When large enough input and output buffers are supplied to inflate(), for
  12896. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  12897. inflate execution time is spent in this routine.
  12898. Entry assumptions:
  12899. state.mode === LEN
  12900. strm.avail_in >= 6
  12901. strm.avail_out >= 258
  12902. start >= strm.avail_out
  12903. state.bits < 8
  12904. On return, state.mode is one of:
  12905. LEN -- ran out of enough output space or enough available input
  12906. TYPE -- reached end of block code, inflate() to interpret next block
  12907. BAD -- error in block data
  12908. Notes:
  12909. - The maximum input bits used by a length/distance pair is 15 bits for the
  12910. length code, 5 bits for the length extra, 15 bits for the distance code,
  12911. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  12912. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  12913. checking for available input while decoding.
  12914. - The maximum bytes that a single length/distance pair can output is 258
  12915. bytes, which is the maximum length that can be coded. inflate_fast()
  12916. requires strm.avail_out >= 258 for each loop to avoid checking for
  12917. output space.
  12918. */
  12919. module.exports = function inflate_fast(strm, start) {
  12920. var state;
  12921. var _in; /* local strm.input */
  12922. var last; /* have enough input while in < last */
  12923. var _out; /* local strm.output */
  12924. var beg; /* inflate()'s initial strm.output */
  12925. var end; /* while out < end, enough space available */
  12926. //#ifdef INFLATE_STRICT
  12927. var dmax; /* maximum distance from zlib header */
  12928. //#endif
  12929. var wsize; /* window size or zero if not using window */
  12930. var whave; /* valid bytes in the window */
  12931. var wnext; /* window write index */
  12932. var window; /* allocated sliding window, if wsize != 0 */
  12933. var hold; /* local strm.hold */
  12934. var bits; /* local strm.bits */
  12935. var lcode; /* local strm.lencode */
  12936. var dcode; /* local strm.distcode */
  12937. var lmask; /* mask for first level of length codes */
  12938. var dmask; /* mask for first level of distance codes */
  12939. var here; /* retrieved table entry */
  12940. var op; /* code bits, operation, extra bits, or */
  12941. /* window position, window bytes to copy */
  12942. var len; /* match length, unused bytes */
  12943. var dist; /* match distance */
  12944. var from; /* where to copy match from */
  12945. var from_source;
  12946. var input, output; // JS specific, because we have no pointers
  12947. /* copy state to local variables */
  12948. state = strm.state;
  12949. //here = state.here;
  12950. _in = strm.next_in;
  12951. input = strm.input;
  12952. last = _in + (strm.avail_in - 5);
  12953. _out = strm.next_out;
  12954. output = strm.output;
  12955. beg = _out - (start - strm.avail_out);
  12956. end = _out + (strm.avail_out - 257);
  12957. //#ifdef INFLATE_STRICT
  12958. dmax = state.dmax;
  12959. //#endif
  12960. wsize = state.wsize;
  12961. whave = state.whave;
  12962. wnext = state.wnext;
  12963. window = state.window;
  12964. hold = state.hold;
  12965. bits = state.bits;
  12966. lcode = state.lencode;
  12967. dcode = state.distcode;
  12968. lmask = (1 << state.lenbits) - 1;
  12969. dmask = (1 << state.distbits) - 1;
  12970. /* decode literals and length/distances until end-of-block or not enough
  12971. input data or output space */
  12972. top:
  12973. do {
  12974. if (bits < 15) {
  12975. hold += input[_in++] << bits;
  12976. bits += 8;
  12977. hold += input[_in++] << bits;
  12978. bits += 8;
  12979. }
  12980. here = lcode[hold & lmask];
  12981. dolen:
  12982. for (;;) { // Goto emulation
  12983. op = here >>> 24/*here.bits*/;
  12984. hold >>>= op;
  12985. bits -= op;
  12986. op = (here >>> 16) & 0xff/*here.op*/;
  12987. if (op === 0) { /* literal */
  12988. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  12989. // "inflate: literal '%c'\n" :
  12990. // "inflate: literal 0x%02x\n", here.val));
  12991. output[_out++] = here & 0xffff/*here.val*/;
  12992. }
  12993. else if (op & 16) { /* length base */
  12994. len = here & 0xffff/*here.val*/;
  12995. op &= 15; /* number of extra bits */
  12996. if (op) {
  12997. if (bits < op) {
  12998. hold += input[_in++] << bits;
  12999. bits += 8;
  13000. }
  13001. len += hold & ((1 << op) - 1);
  13002. hold >>>= op;
  13003. bits -= op;
  13004. }
  13005. //Tracevv((stderr, "inflate: length %u\n", len));
  13006. if (bits < 15) {
  13007. hold += input[_in++] << bits;
  13008. bits += 8;
  13009. hold += input[_in++] << bits;
  13010. bits += 8;
  13011. }
  13012. here = dcode[hold & dmask];
  13013. dodist:
  13014. for (;;) { // goto emulation
  13015. op = here >>> 24/*here.bits*/;
  13016. hold >>>= op;
  13017. bits -= op;
  13018. op = (here >>> 16) & 0xff/*here.op*/;
  13019. if (op & 16) { /* distance base */
  13020. dist = here & 0xffff/*here.val*/;
  13021. op &= 15; /* number of extra bits */
  13022. if (bits < op) {
  13023. hold += input[_in++] << bits;
  13024. bits += 8;
  13025. if (bits < op) {
  13026. hold += input[_in++] << bits;
  13027. bits += 8;
  13028. }
  13029. }
  13030. dist += hold & ((1 << op) - 1);
  13031. //#ifdef INFLATE_STRICT
  13032. if (dist > dmax) {
  13033. strm.msg = 'invalid distance too far back';
  13034. state.mode = BAD;
  13035. break top;
  13036. }
  13037. //#endif
  13038. hold >>>= op;
  13039. bits -= op;
  13040. //Tracevv((stderr, "inflate: distance %u\n", dist));
  13041. op = _out - beg; /* max distance in output */
  13042. if (dist > op) { /* see if copy from window */
  13043. op = dist - op; /* distance back in window */
  13044. if (op > whave) {
  13045. if (state.sane) {
  13046. strm.msg = 'invalid distance too far back';
  13047. state.mode = BAD;
  13048. break top;
  13049. }
  13050. // (!) This block is disabled in zlib defailts,
  13051. // don't enable it for binary compatibility
  13052. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  13053. // if (len <= op - whave) {
  13054. // do {
  13055. // output[_out++] = 0;
  13056. // } while (--len);
  13057. // continue top;
  13058. // }
  13059. // len -= op - whave;
  13060. // do {
  13061. // output[_out++] = 0;
  13062. // } while (--op > whave);
  13063. // if (op === 0) {
  13064. // from = _out - dist;
  13065. // do {
  13066. // output[_out++] = output[from++];
  13067. // } while (--len);
  13068. // continue top;
  13069. // }
  13070. //#endif
  13071. }
  13072. from = 0; // window index
  13073. from_source = window;
  13074. if (wnext === 0) { /* very common case */
  13075. from += wsize - op;
  13076. if (op < len) { /* some from window */
  13077. len -= op;
  13078. do {
  13079. output[_out++] = window[from++];
  13080. } while (--op);
  13081. from = _out - dist; /* rest from output */
  13082. from_source = output;
  13083. }
  13084. }
  13085. else if (wnext < op) { /* wrap around window */
  13086. from += wsize + wnext - op;
  13087. op -= wnext;
  13088. if (op < len) { /* some from end of window */
  13089. len -= op;
  13090. do {
  13091. output[_out++] = window[from++];
  13092. } while (--op);
  13093. from = 0;
  13094. if (wnext < len) { /* some from start of window */
  13095. op = wnext;
  13096. len -= op;
  13097. do {
  13098. output[_out++] = window[from++];
  13099. } while (--op);
  13100. from = _out - dist; /* rest from output */
  13101. from_source = output;
  13102. }
  13103. }
  13104. }
  13105. else { /* contiguous in window */
  13106. from += wnext - op;
  13107. if (op < len) { /* some from window */
  13108. len -= op;
  13109. do {
  13110. output[_out++] = window[from++];
  13111. } while (--op);
  13112. from = _out - dist; /* rest from output */
  13113. from_source = output;
  13114. }
  13115. }
  13116. while (len > 2) {
  13117. output[_out++] = from_source[from++];
  13118. output[_out++] = from_source[from++];
  13119. output[_out++] = from_source[from++];
  13120. len -= 3;
  13121. }
  13122. if (len) {
  13123. output[_out++] = from_source[from++];
  13124. if (len > 1) {
  13125. output[_out++] = from_source[from++];
  13126. }
  13127. }
  13128. }
  13129. else {
  13130. from = _out - dist; /* copy direct from output */
  13131. do { /* minimum length is three */
  13132. output[_out++] = output[from++];
  13133. output[_out++] = output[from++];
  13134. output[_out++] = output[from++];
  13135. len -= 3;
  13136. } while (len > 2);
  13137. if (len) {
  13138. output[_out++] = output[from++];
  13139. if (len > 1) {
  13140. output[_out++] = output[from++];
  13141. }
  13142. }
  13143. }
  13144. }
  13145. else if ((op & 64) === 0) { /* 2nd level distance code */
  13146. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  13147. continue dodist;
  13148. }
  13149. else {
  13150. strm.msg = 'invalid distance code';
  13151. state.mode = BAD;
  13152. break top;
  13153. }
  13154. break; // need to emulate goto via "continue"
  13155. }
  13156. }
  13157. else if ((op & 64) === 0) { /* 2nd level length code */
  13158. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  13159. continue dolen;
  13160. }
  13161. else if (op & 32) { /* end-of-block */
  13162. //Tracevv((stderr, "inflate: end of block\n"));
  13163. state.mode = TYPE;
  13164. break top;
  13165. }
  13166. else {
  13167. strm.msg = 'invalid literal/length code';
  13168. state.mode = BAD;
  13169. break top;
  13170. }
  13171. break; // need to emulate goto via "continue"
  13172. }
  13173. } while (_in < last && _out < end);
  13174. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  13175. len = bits >> 3;
  13176. _in -= len;
  13177. bits -= len << 3;
  13178. hold &= (1 << bits) - 1;
  13179. /* update state and return */
  13180. strm.next_in = _in;
  13181. strm.next_out = _out;
  13182. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  13183. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  13184. state.hold = hold;
  13185. state.bits = bits;
  13186. return;
  13187. };
  13188. },{}],47:[function(require,module,exports){
  13189. 'use strict';
  13190. var utils = require('../utils/common');
  13191. var adler32 = require('./adler32');
  13192. var crc32 = require('./crc32');
  13193. var inflate_fast = require('./inffast');
  13194. var inflate_table = require('./inftrees');
  13195. var CODES = 0;
  13196. var LENS = 1;
  13197. var DISTS = 2;
  13198. /* Public constants ==========================================================*/
  13199. /* ===========================================================================*/
  13200. /* Allowed flush values; see deflate() and inflate() below for details */
  13201. //var Z_NO_FLUSH = 0;
  13202. //var Z_PARTIAL_FLUSH = 1;
  13203. //var Z_SYNC_FLUSH = 2;
  13204. //var Z_FULL_FLUSH = 3;
  13205. var Z_FINISH = 4;
  13206. var Z_BLOCK = 5;
  13207. var Z_TREES = 6;
  13208. /* Return codes for the compression/decompression functions. Negative values
  13209. * are errors, positive values are used for special but normal events.
  13210. */
  13211. var Z_OK = 0;
  13212. var Z_STREAM_END = 1;
  13213. var Z_NEED_DICT = 2;
  13214. //var Z_ERRNO = -1;
  13215. var Z_STREAM_ERROR = -2;
  13216. var Z_DATA_ERROR = -3;
  13217. var Z_MEM_ERROR = -4;
  13218. var Z_BUF_ERROR = -5;
  13219. //var Z_VERSION_ERROR = -6;
  13220. /* The deflate compression method */
  13221. var Z_DEFLATED = 8;
  13222. /* STATES ====================================================================*/
  13223. /* ===========================================================================*/
  13224. var HEAD = 1; /* i: waiting for magic header */
  13225. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  13226. var TIME = 3; /* i: waiting for modification time (gzip) */
  13227. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  13228. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  13229. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  13230. var NAME = 7; /* i: waiting for end of file name (gzip) */
  13231. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  13232. var HCRC = 9; /* i: waiting for header crc (gzip) */
  13233. var DICTID = 10; /* i: waiting for dictionary check value */
  13234. var DICT = 11; /* waiting for inflateSetDictionary() call */
  13235. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  13236. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  13237. var STORED = 14; /* i: waiting for stored size (length and complement) */
  13238. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  13239. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  13240. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  13241. var LENLENS = 18; /* i: waiting for code length code lengths */
  13242. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  13243. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  13244. var LEN = 21; /* i: waiting for length/lit/eob code */
  13245. var LENEXT = 22; /* i: waiting for length extra bits */
  13246. var DIST = 23; /* i: waiting for distance code */
  13247. var DISTEXT = 24; /* i: waiting for distance extra bits */
  13248. var MATCH = 25; /* o: waiting for output space to copy string */
  13249. var LIT = 26; /* o: waiting for output space to write literal */
  13250. var CHECK = 27; /* i: waiting for 32-bit check value */
  13251. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  13252. var DONE = 29; /* finished check, done -- remain here until reset */
  13253. var BAD = 30; /* got a data error -- remain here until reset */
  13254. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  13255. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  13256. /* ===========================================================================*/
  13257. var ENOUGH_LENS = 852;
  13258. var ENOUGH_DISTS = 592;
  13259. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  13260. var MAX_WBITS = 15;
  13261. /* 32K LZ77 window */
  13262. var DEF_WBITS = MAX_WBITS;
  13263. function ZSWAP32(q) {
  13264. return (((q >>> 24) & 0xff) +
  13265. ((q >>> 8) & 0xff00) +
  13266. ((q & 0xff00) << 8) +
  13267. ((q & 0xff) << 24));
  13268. }
  13269. function InflateState() {
  13270. this.mode = 0; /* current inflate mode */
  13271. this.last = false; /* true if processing last block */
  13272. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  13273. this.havedict = false; /* true if dictionary provided */
  13274. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  13275. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  13276. this.check = 0; /* protected copy of check value */
  13277. this.total = 0; /* protected copy of output count */
  13278. // TODO: may be {}
  13279. this.head = null; /* where to save gzip header information */
  13280. /* sliding window */
  13281. this.wbits = 0; /* log base 2 of requested window size */
  13282. this.wsize = 0; /* window size or zero if not using window */
  13283. this.whave = 0; /* valid bytes in the window */
  13284. this.wnext = 0; /* window write index */
  13285. this.window = null; /* allocated sliding window, if needed */
  13286. /* bit accumulator */
  13287. this.hold = 0; /* input bit accumulator */
  13288. this.bits = 0; /* number of bits in "in" */
  13289. /* for string and stored block copying */
  13290. this.length = 0; /* literal or length of data to copy */
  13291. this.offset = 0; /* distance back to copy string from */
  13292. /* for table and code decoding */
  13293. this.extra = 0; /* extra bits needed */
  13294. /* fixed and dynamic code tables */
  13295. this.lencode = null; /* starting table for length/literal codes */
  13296. this.distcode = null; /* starting table for distance codes */
  13297. this.lenbits = 0; /* index bits for lencode */
  13298. this.distbits = 0; /* index bits for distcode */
  13299. /* dynamic table building */
  13300. this.ncode = 0; /* number of code length code lengths */
  13301. this.nlen = 0; /* number of length code lengths */
  13302. this.ndist = 0; /* number of distance code lengths */
  13303. this.have = 0; /* number of code lengths in lens[] */
  13304. this.next = null; /* next available space in codes[] */
  13305. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  13306. this.work = new utils.Buf16(288); /* work area for code table building */
  13307. /*
  13308. because we don't have pointers in js, we use lencode and distcode directly
  13309. as buffers so we don't need codes
  13310. */
  13311. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  13312. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  13313. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  13314. this.sane = 0; /* if false, allow invalid distance too far */
  13315. this.back = 0; /* bits back of last unprocessed length/lit */
  13316. this.was = 0; /* initial length of match */
  13317. }
  13318. function inflateResetKeep(strm) {
  13319. var state;
  13320. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  13321. state = strm.state;
  13322. strm.total_in = strm.total_out = state.total = 0;
  13323. strm.msg = ''; /*Z_NULL*/
  13324. if (state.wrap) { /* to support ill-conceived Java test suite */
  13325. strm.adler = state.wrap & 1;
  13326. }
  13327. state.mode = HEAD;
  13328. state.last = 0;
  13329. state.havedict = 0;
  13330. state.dmax = 32768;
  13331. state.head = null/*Z_NULL*/;
  13332. state.hold = 0;
  13333. state.bits = 0;
  13334. //state.lencode = state.distcode = state.next = state.codes;
  13335. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  13336. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  13337. state.sane = 1;
  13338. state.back = -1;
  13339. //Tracev((stderr, "inflate: reset\n"));
  13340. return Z_OK;
  13341. }
  13342. function inflateReset(strm) {
  13343. var state;
  13344. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  13345. state = strm.state;
  13346. state.wsize = 0;
  13347. state.whave = 0;
  13348. state.wnext = 0;
  13349. return inflateResetKeep(strm);
  13350. }
  13351. function inflateReset2(strm, windowBits) {
  13352. var wrap;
  13353. var state;
  13354. /* get the state */
  13355. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  13356. state = strm.state;
  13357. /* extract wrap request from windowBits parameter */
  13358. if (windowBits < 0) {
  13359. wrap = 0;
  13360. windowBits = -windowBits;
  13361. }
  13362. else {
  13363. wrap = (windowBits >> 4) + 1;
  13364. if (windowBits < 48) {
  13365. windowBits &= 15;
  13366. }
  13367. }
  13368. /* set number of window bits, free window if different */
  13369. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  13370. return Z_STREAM_ERROR;
  13371. }
  13372. if (state.window !== null && state.wbits !== windowBits) {
  13373. state.window = null;
  13374. }
  13375. /* update state and reset the rest of it */
  13376. state.wrap = wrap;
  13377. state.wbits = windowBits;
  13378. return inflateReset(strm);
  13379. }
  13380. function inflateInit2(strm, windowBits) {
  13381. var ret;
  13382. var state;
  13383. if (!strm) { return Z_STREAM_ERROR; }
  13384. //strm.msg = Z_NULL; /* in case we return an error */
  13385. state = new InflateState();
  13386. //if (state === Z_NULL) return Z_MEM_ERROR;
  13387. //Tracev((stderr, "inflate: allocated\n"));
  13388. strm.state = state;
  13389. state.window = null/*Z_NULL*/;
  13390. ret = inflateReset2(strm, windowBits);
  13391. if (ret !== Z_OK) {
  13392. strm.state = null/*Z_NULL*/;
  13393. }
  13394. return ret;
  13395. }
  13396. function inflateInit(strm) {
  13397. return inflateInit2(strm, DEF_WBITS);
  13398. }
  13399. /*
  13400. Return state with length and distance decoding tables and index sizes set to
  13401. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  13402. If BUILDFIXED is defined, then instead this routine builds the tables the
  13403. first time it's called, and returns those tables the first time and
  13404. thereafter. This reduces the size of the code by about 2K bytes, in
  13405. exchange for a little execution time. However, BUILDFIXED should not be
  13406. used for threaded applications, since the rewriting of the tables and virgin
  13407. may not be thread-safe.
  13408. */
  13409. var virgin = true;
  13410. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  13411. function fixedtables(state) {
  13412. /* build fixed huffman tables if first call (may not be thread safe) */
  13413. if (virgin) {
  13414. var sym;
  13415. lenfix = new utils.Buf32(512);
  13416. distfix = new utils.Buf32(32);
  13417. /* literal/length table */
  13418. sym = 0;
  13419. while (sym < 144) { state.lens[sym++] = 8; }
  13420. while (sym < 256) { state.lens[sym++] = 9; }
  13421. while (sym < 280) { state.lens[sym++] = 7; }
  13422. while (sym < 288) { state.lens[sym++] = 8; }
  13423. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  13424. /* distance table */
  13425. sym = 0;
  13426. while (sym < 32) { state.lens[sym++] = 5; }
  13427. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  13428. /* do this just once */
  13429. virgin = false;
  13430. }
  13431. state.lencode = lenfix;
  13432. state.lenbits = 9;
  13433. state.distcode = distfix;
  13434. state.distbits = 5;
  13435. }
  13436. /*
  13437. Update the window with the last wsize (normally 32K) bytes written before
  13438. returning. If window does not exist yet, create it. This is only called
  13439. when a window is already in use, or when output has been written during this
  13440. inflate call, but the end of the deflate stream has not been reached yet.
  13441. It is also called to create a window for dictionary data when a dictionary
  13442. is loaded.
  13443. Providing output buffers larger than 32K to inflate() should provide a speed
  13444. advantage, since only the last 32K of output is copied to the sliding window
  13445. upon return from inflate(), and since all distances after the first 32K of
  13446. output will fall in the output data, making match copies simpler and faster.
  13447. The advantage may be dependent on the size of the processor's data caches.
  13448. */
  13449. function updatewindow(strm, src, end, copy) {
  13450. var dist;
  13451. var state = strm.state;
  13452. /* if it hasn't been done already, allocate space for the window */
  13453. if (state.window === null) {
  13454. state.wsize = 1 << state.wbits;
  13455. state.wnext = 0;
  13456. state.whave = 0;
  13457. state.window = new utils.Buf8(state.wsize);
  13458. }
  13459. /* copy state->wsize or less output bytes into the circular window */
  13460. if (copy >= state.wsize) {
  13461. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  13462. state.wnext = 0;
  13463. state.whave = state.wsize;
  13464. }
  13465. else {
  13466. dist = state.wsize - state.wnext;
  13467. if (dist > copy) {
  13468. dist = copy;
  13469. }
  13470. //zmemcpy(state->window + state->wnext, end - copy, dist);
  13471. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  13472. copy -= dist;
  13473. if (copy) {
  13474. //zmemcpy(state->window, end - copy, copy);
  13475. utils.arraySet(state.window,src, end - copy, copy, 0);
  13476. state.wnext = copy;
  13477. state.whave = state.wsize;
  13478. }
  13479. else {
  13480. state.wnext += dist;
  13481. if (state.wnext === state.wsize) { state.wnext = 0; }
  13482. if (state.whave < state.wsize) { state.whave += dist; }
  13483. }
  13484. }
  13485. return 0;
  13486. }
  13487. function inflate(strm, flush) {
  13488. var state;
  13489. var input, output; // input/output buffers
  13490. var next; /* next input INDEX */
  13491. var put; /* next output INDEX */
  13492. var have, left; /* available input and output */
  13493. var hold; /* bit buffer */
  13494. var bits; /* bits in bit buffer */
  13495. var _in, _out; /* save starting available input and output */
  13496. var copy; /* number of stored or match bytes to copy */
  13497. var from; /* where to copy match bytes from */
  13498. var from_source;
  13499. var here = 0; /* current decoding table entry */
  13500. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  13501. //var last; /* parent table entry */
  13502. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  13503. var len; /* length to copy for repeats, bits to drop */
  13504. var ret; /* return code */
  13505. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  13506. var opts;
  13507. var n; // temporary var for NEED_BITS
  13508. var order = /* permutation of code lengths */
  13509. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  13510. if (!strm || !strm.state || !strm.output ||
  13511. (!strm.input && strm.avail_in !== 0)) {
  13512. return Z_STREAM_ERROR;
  13513. }
  13514. state = strm.state;
  13515. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  13516. //--- LOAD() ---
  13517. put = strm.next_out;
  13518. output = strm.output;
  13519. left = strm.avail_out;
  13520. next = strm.next_in;
  13521. input = strm.input;
  13522. have = strm.avail_in;
  13523. hold = state.hold;
  13524. bits = state.bits;
  13525. //---
  13526. _in = have;
  13527. _out = left;
  13528. ret = Z_OK;
  13529. inf_leave: // goto emulation
  13530. for (;;) {
  13531. switch (state.mode) {
  13532. case HEAD:
  13533. if (state.wrap === 0) {
  13534. state.mode = TYPEDO;
  13535. break;
  13536. }
  13537. //=== NEEDBITS(16);
  13538. while (bits < 16) {
  13539. if (have === 0) { break inf_leave; }
  13540. have--;
  13541. hold += input[next++] << bits;
  13542. bits += 8;
  13543. }
  13544. //===//
  13545. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  13546. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  13547. //=== CRC2(state.check, hold);
  13548. hbuf[0] = hold & 0xff;
  13549. hbuf[1] = (hold >>> 8) & 0xff;
  13550. state.check = crc32(state.check, hbuf, 2, 0);
  13551. //===//
  13552. //=== INITBITS();
  13553. hold = 0;
  13554. bits = 0;
  13555. //===//
  13556. state.mode = FLAGS;
  13557. break;
  13558. }
  13559. state.flags = 0; /* expect zlib header */
  13560. if (state.head) {
  13561. state.head.done = false;
  13562. }
  13563. if (!(state.wrap & 1) || /* check if zlib header allowed */
  13564. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  13565. strm.msg = 'incorrect header check';
  13566. state.mode = BAD;
  13567. break;
  13568. }
  13569. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  13570. strm.msg = 'unknown compression method';
  13571. state.mode = BAD;
  13572. break;
  13573. }
  13574. //--- DROPBITS(4) ---//
  13575. hold >>>= 4;
  13576. bits -= 4;
  13577. //---//
  13578. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  13579. if (state.wbits === 0) {
  13580. state.wbits = len;
  13581. }
  13582. else if (len > state.wbits) {
  13583. strm.msg = 'invalid window size';
  13584. state.mode = BAD;
  13585. break;
  13586. }
  13587. state.dmax = 1 << len;
  13588. //Tracev((stderr, "inflate: zlib header ok\n"));
  13589. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  13590. state.mode = hold & 0x200 ? DICTID : TYPE;
  13591. //=== INITBITS();
  13592. hold = 0;
  13593. bits = 0;
  13594. //===//
  13595. break;
  13596. case FLAGS:
  13597. //=== NEEDBITS(16); */
  13598. while (bits < 16) {
  13599. if (have === 0) { break inf_leave; }
  13600. have--;
  13601. hold += input[next++] << bits;
  13602. bits += 8;
  13603. }
  13604. //===//
  13605. state.flags = hold;
  13606. if ((state.flags & 0xff) !== Z_DEFLATED) {
  13607. strm.msg = 'unknown compression method';
  13608. state.mode = BAD;
  13609. break;
  13610. }
  13611. if (state.flags & 0xe000) {
  13612. strm.msg = 'unknown header flags set';
  13613. state.mode = BAD;
  13614. break;
  13615. }
  13616. if (state.head) {
  13617. state.head.text = ((hold >> 8) & 1);
  13618. }
  13619. if (state.flags & 0x0200) {
  13620. //=== CRC2(state.check, hold);
  13621. hbuf[0] = hold & 0xff;
  13622. hbuf[1] = (hold >>> 8) & 0xff;
  13623. state.check = crc32(state.check, hbuf, 2, 0);
  13624. //===//
  13625. }
  13626. //=== INITBITS();
  13627. hold = 0;
  13628. bits = 0;
  13629. //===//
  13630. state.mode = TIME;
  13631. /* falls through */
  13632. case TIME:
  13633. //=== NEEDBITS(32); */
  13634. while (bits < 32) {
  13635. if (have === 0) { break inf_leave; }
  13636. have--;
  13637. hold += input[next++] << bits;
  13638. bits += 8;
  13639. }
  13640. //===//
  13641. if (state.head) {
  13642. state.head.time = hold;
  13643. }
  13644. if (state.flags & 0x0200) {
  13645. //=== CRC4(state.check, hold)
  13646. hbuf[0] = hold & 0xff;
  13647. hbuf[1] = (hold >>> 8) & 0xff;
  13648. hbuf[2] = (hold >>> 16) & 0xff;
  13649. hbuf[3] = (hold >>> 24) & 0xff;
  13650. state.check = crc32(state.check, hbuf, 4, 0);
  13651. //===
  13652. }
  13653. //=== INITBITS();
  13654. hold = 0;
  13655. bits = 0;
  13656. //===//
  13657. state.mode = OS;
  13658. /* falls through */
  13659. case OS:
  13660. //=== NEEDBITS(16); */
  13661. while (bits < 16) {
  13662. if (have === 0) { break inf_leave; }
  13663. have--;
  13664. hold += input[next++] << bits;
  13665. bits += 8;
  13666. }
  13667. //===//
  13668. if (state.head) {
  13669. state.head.xflags = (hold & 0xff);
  13670. state.head.os = (hold >> 8);
  13671. }
  13672. if (state.flags & 0x0200) {
  13673. //=== CRC2(state.check, hold);
  13674. hbuf[0] = hold & 0xff;
  13675. hbuf[1] = (hold >>> 8) & 0xff;
  13676. state.check = crc32(state.check, hbuf, 2, 0);
  13677. //===//
  13678. }
  13679. //=== INITBITS();
  13680. hold = 0;
  13681. bits = 0;
  13682. //===//
  13683. state.mode = EXLEN;
  13684. /* falls through */
  13685. case EXLEN:
  13686. if (state.flags & 0x0400) {
  13687. //=== NEEDBITS(16); */
  13688. while (bits < 16) {
  13689. if (have === 0) { break inf_leave; }
  13690. have--;
  13691. hold += input[next++] << bits;
  13692. bits += 8;
  13693. }
  13694. //===//
  13695. state.length = hold;
  13696. if (state.head) {
  13697. state.head.extra_len = hold;
  13698. }
  13699. if (state.flags & 0x0200) {
  13700. //=== CRC2(state.check, hold);
  13701. hbuf[0] = hold & 0xff;
  13702. hbuf[1] = (hold >>> 8) & 0xff;
  13703. state.check = crc32(state.check, hbuf, 2, 0);
  13704. //===//
  13705. }
  13706. //=== INITBITS();
  13707. hold = 0;
  13708. bits = 0;
  13709. //===//
  13710. }
  13711. else if (state.head) {
  13712. state.head.extra = null/*Z_NULL*/;
  13713. }
  13714. state.mode = EXTRA;
  13715. /* falls through */
  13716. case EXTRA:
  13717. if (state.flags & 0x0400) {
  13718. copy = state.length;
  13719. if (copy > have) { copy = have; }
  13720. if (copy) {
  13721. if (state.head) {
  13722. len = state.head.extra_len - state.length;
  13723. if (!state.head.extra) {
  13724. // Use untyped array for more conveniend processing later
  13725. state.head.extra = new Array(state.head.extra_len);
  13726. }
  13727. utils.arraySet(
  13728. state.head.extra,
  13729. input,
  13730. next,
  13731. // extra field is limited to 65536 bytes
  13732. // - no need for additional size check
  13733. copy,
  13734. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  13735. len
  13736. );
  13737. //zmemcpy(state.head.extra + len, next,
  13738. // len + copy > state.head.extra_max ?
  13739. // state.head.extra_max - len : copy);
  13740. }
  13741. if (state.flags & 0x0200) {
  13742. state.check = crc32(state.check, input, copy, next);
  13743. }
  13744. have -= copy;
  13745. next += copy;
  13746. state.length -= copy;
  13747. }
  13748. if (state.length) { break inf_leave; }
  13749. }
  13750. state.length = 0;
  13751. state.mode = NAME;
  13752. /* falls through */
  13753. case NAME:
  13754. if (state.flags & 0x0800) {
  13755. if (have === 0) { break inf_leave; }
  13756. copy = 0;
  13757. do {
  13758. // TODO: 2 or 1 bytes?
  13759. len = input[next + copy++];
  13760. /* use constant limit because in js we should not preallocate memory */
  13761. if (state.head && len &&
  13762. (state.length < 65536 /*state.head.name_max*/)) {
  13763. state.head.name += String.fromCharCode(len);
  13764. }
  13765. } while (len && copy < have);
  13766. if (state.flags & 0x0200) {
  13767. state.check = crc32(state.check, input, copy, next);
  13768. }
  13769. have -= copy;
  13770. next += copy;
  13771. if (len) { break inf_leave; }
  13772. }
  13773. else if (state.head) {
  13774. state.head.name = null;
  13775. }
  13776. state.length = 0;
  13777. state.mode = COMMENT;
  13778. /* falls through */
  13779. case COMMENT:
  13780. if (state.flags & 0x1000) {
  13781. if (have === 0) { break inf_leave; }
  13782. copy = 0;
  13783. do {
  13784. len = input[next + copy++];
  13785. /* use constant limit because in js we should not preallocate memory */
  13786. if (state.head && len &&
  13787. (state.length < 65536 /*state.head.comm_max*/)) {
  13788. state.head.comment += String.fromCharCode(len);
  13789. }
  13790. } while (len && copy < have);
  13791. if (state.flags & 0x0200) {
  13792. state.check = crc32(state.check, input, copy, next);
  13793. }
  13794. have -= copy;
  13795. next += copy;
  13796. if (len) { break inf_leave; }
  13797. }
  13798. else if (state.head) {
  13799. state.head.comment = null;
  13800. }
  13801. state.mode = HCRC;
  13802. /* falls through */
  13803. case HCRC:
  13804. if (state.flags & 0x0200) {
  13805. //=== NEEDBITS(16); */
  13806. while (bits < 16) {
  13807. if (have === 0) { break inf_leave; }
  13808. have--;
  13809. hold += input[next++] << bits;
  13810. bits += 8;
  13811. }
  13812. //===//
  13813. if (hold !== (state.check & 0xffff)) {
  13814. strm.msg = 'header crc mismatch';
  13815. state.mode = BAD;
  13816. break;
  13817. }
  13818. //=== INITBITS();
  13819. hold = 0;
  13820. bits = 0;
  13821. //===//
  13822. }
  13823. if (state.head) {
  13824. state.head.hcrc = ((state.flags >> 9) & 1);
  13825. state.head.done = true;
  13826. }
  13827. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  13828. state.mode = TYPE;
  13829. break;
  13830. case DICTID:
  13831. //=== NEEDBITS(32); */
  13832. while (bits < 32) {
  13833. if (have === 0) { break inf_leave; }
  13834. have--;
  13835. hold += input[next++] << bits;
  13836. bits += 8;
  13837. }
  13838. //===//
  13839. strm.adler = state.check = ZSWAP32(hold);
  13840. //=== INITBITS();
  13841. hold = 0;
  13842. bits = 0;
  13843. //===//
  13844. state.mode = DICT;
  13845. /* falls through */
  13846. case DICT:
  13847. if (state.havedict === 0) {
  13848. //--- RESTORE() ---
  13849. strm.next_out = put;
  13850. strm.avail_out = left;
  13851. strm.next_in = next;
  13852. strm.avail_in = have;
  13853. state.hold = hold;
  13854. state.bits = bits;
  13855. //---
  13856. return Z_NEED_DICT;
  13857. }
  13858. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  13859. state.mode = TYPE;
  13860. /* falls through */
  13861. case TYPE:
  13862. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  13863. /* falls through */
  13864. case TYPEDO:
  13865. if (state.last) {
  13866. //--- BYTEBITS() ---//
  13867. hold >>>= bits & 7;
  13868. bits -= bits & 7;
  13869. //---//
  13870. state.mode = CHECK;
  13871. break;
  13872. }
  13873. //=== NEEDBITS(3); */
  13874. while (bits < 3) {
  13875. if (have === 0) { break inf_leave; }
  13876. have--;
  13877. hold += input[next++] << bits;
  13878. bits += 8;
  13879. }
  13880. //===//
  13881. state.last = (hold & 0x01)/*BITS(1)*/;
  13882. //--- DROPBITS(1) ---//
  13883. hold >>>= 1;
  13884. bits -= 1;
  13885. //---//
  13886. switch ((hold & 0x03)/*BITS(2)*/) {
  13887. case 0: /* stored block */
  13888. //Tracev((stderr, "inflate: stored block%s\n",
  13889. // state.last ? " (last)" : ""));
  13890. state.mode = STORED;
  13891. break;
  13892. case 1: /* fixed block */
  13893. fixedtables(state);
  13894. //Tracev((stderr, "inflate: fixed codes block%s\n",
  13895. // state.last ? " (last)" : ""));
  13896. state.mode = LEN_; /* decode codes */
  13897. if (flush === Z_TREES) {
  13898. //--- DROPBITS(2) ---//
  13899. hold >>>= 2;
  13900. bits -= 2;
  13901. //---//
  13902. break inf_leave;
  13903. }
  13904. break;
  13905. case 2: /* dynamic block */
  13906. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  13907. // state.last ? " (last)" : ""));
  13908. state.mode = TABLE;
  13909. break;
  13910. case 3:
  13911. strm.msg = 'invalid block type';
  13912. state.mode = BAD;
  13913. }
  13914. //--- DROPBITS(2) ---//
  13915. hold >>>= 2;
  13916. bits -= 2;
  13917. //---//
  13918. break;
  13919. case STORED:
  13920. //--- BYTEBITS() ---// /* go to byte boundary */
  13921. hold >>>= bits & 7;
  13922. bits -= bits & 7;
  13923. //---//
  13924. //=== NEEDBITS(32); */
  13925. while (bits < 32) {
  13926. if (have === 0) { break inf_leave; }
  13927. have--;
  13928. hold += input[next++] << bits;
  13929. bits += 8;
  13930. }
  13931. //===//
  13932. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  13933. strm.msg = 'invalid stored block lengths';
  13934. state.mode = BAD;
  13935. break;
  13936. }
  13937. state.length = hold & 0xffff;
  13938. //Tracev((stderr, "inflate: stored length %u\n",
  13939. // state.length));
  13940. //=== INITBITS();
  13941. hold = 0;
  13942. bits = 0;
  13943. //===//
  13944. state.mode = COPY_;
  13945. if (flush === Z_TREES) { break inf_leave; }
  13946. /* falls through */
  13947. case COPY_:
  13948. state.mode = COPY;
  13949. /* falls through */
  13950. case COPY:
  13951. copy = state.length;
  13952. if (copy) {
  13953. if (copy > have) { copy = have; }
  13954. if (copy > left) { copy = left; }
  13955. if (copy === 0) { break inf_leave; }
  13956. //--- zmemcpy(put, next, copy); ---
  13957. utils.arraySet(output, input, next, copy, put);
  13958. //---//
  13959. have -= copy;
  13960. next += copy;
  13961. left -= copy;
  13962. put += copy;
  13963. state.length -= copy;
  13964. break;
  13965. }
  13966. //Tracev((stderr, "inflate: stored end\n"));
  13967. state.mode = TYPE;
  13968. break;
  13969. case TABLE:
  13970. //=== NEEDBITS(14); */
  13971. while (bits < 14) {
  13972. if (have === 0) { break inf_leave; }
  13973. have--;
  13974. hold += input[next++] << bits;
  13975. bits += 8;
  13976. }
  13977. //===//
  13978. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  13979. //--- DROPBITS(5) ---//
  13980. hold >>>= 5;
  13981. bits -= 5;
  13982. //---//
  13983. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  13984. //--- DROPBITS(5) ---//
  13985. hold >>>= 5;
  13986. bits -= 5;
  13987. //---//
  13988. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  13989. //--- DROPBITS(4) ---//
  13990. hold >>>= 4;
  13991. bits -= 4;
  13992. //---//
  13993. //#ifndef PKZIP_BUG_WORKAROUND
  13994. if (state.nlen > 286 || state.ndist > 30) {
  13995. strm.msg = 'too many length or distance symbols';
  13996. state.mode = BAD;
  13997. break;
  13998. }
  13999. //#endif
  14000. //Tracev((stderr, "inflate: table sizes ok\n"));
  14001. state.have = 0;
  14002. state.mode = LENLENS;
  14003. /* falls through */
  14004. case LENLENS:
  14005. while (state.have < state.ncode) {
  14006. //=== NEEDBITS(3);
  14007. while (bits < 3) {
  14008. if (have === 0) { break inf_leave; }
  14009. have--;
  14010. hold += input[next++] << bits;
  14011. bits += 8;
  14012. }
  14013. //===//
  14014. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  14015. //--- DROPBITS(3) ---//
  14016. hold >>>= 3;
  14017. bits -= 3;
  14018. //---//
  14019. }
  14020. while (state.have < 19) {
  14021. state.lens[order[state.have++]] = 0;
  14022. }
  14023. // We have separate tables & no pointers. 2 commented lines below not needed.
  14024. //state.next = state.codes;
  14025. //state.lencode = state.next;
  14026. // Switch to use dynamic table
  14027. state.lencode = state.lendyn;
  14028. state.lenbits = 7;
  14029. opts = {bits: state.lenbits};
  14030. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  14031. state.lenbits = opts.bits;
  14032. if (ret) {
  14033. strm.msg = 'invalid code lengths set';
  14034. state.mode = BAD;
  14035. break;
  14036. }
  14037. //Tracev((stderr, "inflate: code lengths ok\n"));
  14038. state.have = 0;
  14039. state.mode = CODELENS;
  14040. /* falls through */
  14041. case CODELENS:
  14042. while (state.have < state.nlen + state.ndist) {
  14043. for (;;) {
  14044. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  14045. here_bits = here >>> 24;
  14046. here_op = (here >>> 16) & 0xff;
  14047. here_val = here & 0xffff;
  14048. if ((here_bits) <= bits) { break; }
  14049. //--- PULLBYTE() ---//
  14050. if (have === 0) { break inf_leave; }
  14051. have--;
  14052. hold += input[next++] << bits;
  14053. bits += 8;
  14054. //---//
  14055. }
  14056. if (here_val < 16) {
  14057. //--- DROPBITS(here.bits) ---//
  14058. hold >>>= here_bits;
  14059. bits -= here_bits;
  14060. //---//
  14061. state.lens[state.have++] = here_val;
  14062. }
  14063. else {
  14064. if (here_val === 16) {
  14065. //=== NEEDBITS(here.bits + 2);
  14066. n = here_bits + 2;
  14067. while (bits < n) {
  14068. if (have === 0) { break inf_leave; }
  14069. have--;
  14070. hold += input[next++] << bits;
  14071. bits += 8;
  14072. }
  14073. //===//
  14074. //--- DROPBITS(here.bits) ---//
  14075. hold >>>= here_bits;
  14076. bits -= here_bits;
  14077. //---//
  14078. if (state.have === 0) {
  14079. strm.msg = 'invalid bit length repeat';
  14080. state.mode = BAD;
  14081. break;
  14082. }
  14083. len = state.lens[state.have - 1];
  14084. copy = 3 + (hold & 0x03);//BITS(2);
  14085. //--- DROPBITS(2) ---//
  14086. hold >>>= 2;
  14087. bits -= 2;
  14088. //---//
  14089. }
  14090. else if (here_val === 17) {
  14091. //=== NEEDBITS(here.bits + 3);
  14092. n = here_bits + 3;
  14093. while (bits < n) {
  14094. if (have === 0) { break inf_leave; }
  14095. have--;
  14096. hold += input[next++] << bits;
  14097. bits += 8;
  14098. }
  14099. //===//
  14100. //--- DROPBITS(here.bits) ---//
  14101. hold >>>= here_bits;
  14102. bits -= here_bits;
  14103. //---//
  14104. len = 0;
  14105. copy = 3 + (hold & 0x07);//BITS(3);
  14106. //--- DROPBITS(3) ---//
  14107. hold >>>= 3;
  14108. bits -= 3;
  14109. //---//
  14110. }
  14111. else {
  14112. //=== NEEDBITS(here.bits + 7);
  14113. n = here_bits + 7;
  14114. while (bits < n) {
  14115. if (have === 0) { break inf_leave; }
  14116. have--;
  14117. hold += input[next++] << bits;
  14118. bits += 8;
  14119. }
  14120. //===//
  14121. //--- DROPBITS(here.bits) ---//
  14122. hold >>>= here_bits;
  14123. bits -= here_bits;
  14124. //---//
  14125. len = 0;
  14126. copy = 11 + (hold & 0x7f);//BITS(7);
  14127. //--- DROPBITS(7) ---//
  14128. hold >>>= 7;
  14129. bits -= 7;
  14130. //---//
  14131. }
  14132. if (state.have + copy > state.nlen + state.ndist) {
  14133. strm.msg = 'invalid bit length repeat';
  14134. state.mode = BAD;
  14135. break;
  14136. }
  14137. while (copy--) {
  14138. state.lens[state.have++] = len;
  14139. }
  14140. }
  14141. }
  14142. /* handle error breaks in while */
  14143. if (state.mode === BAD) { break; }
  14144. /* check for end-of-block code (better have one) */
  14145. if (state.lens[256] === 0) {
  14146. strm.msg = 'invalid code -- missing end-of-block';
  14147. state.mode = BAD;
  14148. break;
  14149. }
  14150. /* build code tables -- note: do not change the lenbits or distbits
  14151. values here (9 and 6) without reading the comments in inftrees.h
  14152. concerning the ENOUGH constants, which depend on those values */
  14153. state.lenbits = 9;
  14154. opts = {bits: state.lenbits};
  14155. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  14156. // We have separate tables & no pointers. 2 commented lines below not needed.
  14157. // state.next_index = opts.table_index;
  14158. state.lenbits = opts.bits;
  14159. // state.lencode = state.next;
  14160. if (ret) {
  14161. strm.msg = 'invalid literal/lengths set';
  14162. state.mode = BAD;
  14163. break;
  14164. }
  14165. state.distbits = 6;
  14166. //state.distcode.copy(state.codes);
  14167. // Switch to use dynamic table
  14168. state.distcode = state.distdyn;
  14169. opts = {bits: state.distbits};
  14170. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  14171. // We have separate tables & no pointers. 2 commented lines below not needed.
  14172. // state.next_index = opts.table_index;
  14173. state.distbits = opts.bits;
  14174. // state.distcode = state.next;
  14175. if (ret) {
  14176. strm.msg = 'invalid distances set';
  14177. state.mode = BAD;
  14178. break;
  14179. }
  14180. //Tracev((stderr, 'inflate: codes ok\n'));
  14181. state.mode = LEN_;
  14182. if (flush === Z_TREES) { break inf_leave; }
  14183. /* falls through */
  14184. case LEN_:
  14185. state.mode = LEN;
  14186. /* falls through */
  14187. case LEN:
  14188. if (have >= 6 && left >= 258) {
  14189. //--- RESTORE() ---
  14190. strm.next_out = put;
  14191. strm.avail_out = left;
  14192. strm.next_in = next;
  14193. strm.avail_in = have;
  14194. state.hold = hold;
  14195. state.bits = bits;
  14196. //---
  14197. inflate_fast(strm, _out);
  14198. //--- LOAD() ---
  14199. put = strm.next_out;
  14200. output = strm.output;
  14201. left = strm.avail_out;
  14202. next = strm.next_in;
  14203. input = strm.input;
  14204. have = strm.avail_in;
  14205. hold = state.hold;
  14206. bits = state.bits;
  14207. //---
  14208. if (state.mode === TYPE) {
  14209. state.back = -1;
  14210. }
  14211. break;
  14212. }
  14213. state.back = 0;
  14214. for (;;) {
  14215. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  14216. here_bits = here >>> 24;
  14217. here_op = (here >>> 16) & 0xff;
  14218. here_val = here & 0xffff;
  14219. if (here_bits <= bits) { break; }
  14220. //--- PULLBYTE() ---//
  14221. if (have === 0) { break inf_leave; }
  14222. have--;
  14223. hold += input[next++] << bits;
  14224. bits += 8;
  14225. //---//
  14226. }
  14227. if (here_op && (here_op & 0xf0) === 0) {
  14228. last_bits = here_bits;
  14229. last_op = here_op;
  14230. last_val = here_val;
  14231. for (;;) {
  14232. here = state.lencode[last_val +
  14233. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  14234. here_bits = here >>> 24;
  14235. here_op = (here >>> 16) & 0xff;
  14236. here_val = here & 0xffff;
  14237. if ((last_bits + here_bits) <= bits) { break; }
  14238. //--- PULLBYTE() ---//
  14239. if (have === 0) { break inf_leave; }
  14240. have--;
  14241. hold += input[next++] << bits;
  14242. bits += 8;
  14243. //---//
  14244. }
  14245. //--- DROPBITS(last.bits) ---//
  14246. hold >>>= last_bits;
  14247. bits -= last_bits;
  14248. //---//
  14249. state.back += last_bits;
  14250. }
  14251. //--- DROPBITS(here.bits) ---//
  14252. hold >>>= here_bits;
  14253. bits -= here_bits;
  14254. //---//
  14255. state.back += here_bits;
  14256. state.length = here_val;
  14257. if (here_op === 0) {
  14258. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  14259. // "inflate: literal '%c'\n" :
  14260. // "inflate: literal 0x%02x\n", here.val));
  14261. state.mode = LIT;
  14262. break;
  14263. }
  14264. if (here_op & 32) {
  14265. //Tracevv((stderr, "inflate: end of block\n"));
  14266. state.back = -1;
  14267. state.mode = TYPE;
  14268. break;
  14269. }
  14270. if (here_op & 64) {
  14271. strm.msg = 'invalid literal/length code';
  14272. state.mode = BAD;
  14273. break;
  14274. }
  14275. state.extra = here_op & 15;
  14276. state.mode = LENEXT;
  14277. /* falls through */
  14278. case LENEXT:
  14279. if (state.extra) {
  14280. //=== NEEDBITS(state.extra);
  14281. n = state.extra;
  14282. while (bits < n) {
  14283. if (have === 0) { break inf_leave; }
  14284. have--;
  14285. hold += input[next++] << bits;
  14286. bits += 8;
  14287. }
  14288. //===//
  14289. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  14290. //--- DROPBITS(state.extra) ---//
  14291. hold >>>= state.extra;
  14292. bits -= state.extra;
  14293. //---//
  14294. state.back += state.extra;
  14295. }
  14296. //Tracevv((stderr, "inflate: length %u\n", state.length));
  14297. state.was = state.length;
  14298. state.mode = DIST;
  14299. /* falls through */
  14300. case DIST:
  14301. for (;;) {
  14302. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  14303. here_bits = here >>> 24;
  14304. here_op = (here >>> 16) & 0xff;
  14305. here_val = here & 0xffff;
  14306. if ((here_bits) <= bits) { break; }
  14307. //--- PULLBYTE() ---//
  14308. if (have === 0) { break inf_leave; }
  14309. have--;
  14310. hold += input[next++] << bits;
  14311. bits += 8;
  14312. //---//
  14313. }
  14314. if ((here_op & 0xf0) === 0) {
  14315. last_bits = here_bits;
  14316. last_op = here_op;
  14317. last_val = here_val;
  14318. for (;;) {
  14319. here = state.distcode[last_val +
  14320. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  14321. here_bits = here >>> 24;
  14322. here_op = (here >>> 16) & 0xff;
  14323. here_val = here & 0xffff;
  14324. if ((last_bits + here_bits) <= bits) { break; }
  14325. //--- PULLBYTE() ---//
  14326. if (have === 0) { break inf_leave; }
  14327. have--;
  14328. hold += input[next++] << bits;
  14329. bits += 8;
  14330. //---//
  14331. }
  14332. //--- DROPBITS(last.bits) ---//
  14333. hold >>>= last_bits;
  14334. bits -= last_bits;
  14335. //---//
  14336. state.back += last_bits;
  14337. }
  14338. //--- DROPBITS(here.bits) ---//
  14339. hold >>>= here_bits;
  14340. bits -= here_bits;
  14341. //---//
  14342. state.back += here_bits;
  14343. if (here_op & 64) {
  14344. strm.msg = 'invalid distance code';
  14345. state.mode = BAD;
  14346. break;
  14347. }
  14348. state.offset = here_val;
  14349. state.extra = (here_op) & 15;
  14350. state.mode = DISTEXT;
  14351. /* falls through */
  14352. case DISTEXT:
  14353. if (state.extra) {
  14354. //=== NEEDBITS(state.extra);
  14355. n = state.extra;
  14356. while (bits < n) {
  14357. if (have === 0) { break inf_leave; }
  14358. have--;
  14359. hold += input[next++] << bits;
  14360. bits += 8;
  14361. }
  14362. //===//
  14363. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  14364. //--- DROPBITS(state.extra) ---//
  14365. hold >>>= state.extra;
  14366. bits -= state.extra;
  14367. //---//
  14368. state.back += state.extra;
  14369. }
  14370. //#ifdef INFLATE_STRICT
  14371. if (state.offset > state.dmax) {
  14372. strm.msg = 'invalid distance too far back';
  14373. state.mode = BAD;
  14374. break;
  14375. }
  14376. //#endif
  14377. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  14378. state.mode = MATCH;
  14379. /* falls through */
  14380. case MATCH:
  14381. if (left === 0) { break inf_leave; }
  14382. copy = _out - left;
  14383. if (state.offset > copy) { /* copy from window */
  14384. copy = state.offset - copy;
  14385. if (copy > state.whave) {
  14386. if (state.sane) {
  14387. strm.msg = 'invalid distance too far back';
  14388. state.mode = BAD;
  14389. break;
  14390. }
  14391. // (!) This block is disabled in zlib defailts,
  14392. // don't enable it for binary compatibility
  14393. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  14394. // Trace((stderr, "inflate.c too far\n"));
  14395. // copy -= state.whave;
  14396. // if (copy > state.length) { copy = state.length; }
  14397. // if (copy > left) { copy = left; }
  14398. // left -= copy;
  14399. // state.length -= copy;
  14400. // do {
  14401. // output[put++] = 0;
  14402. // } while (--copy);
  14403. // if (state.length === 0) { state.mode = LEN; }
  14404. // break;
  14405. //#endif
  14406. }
  14407. if (copy > state.wnext) {
  14408. copy -= state.wnext;
  14409. from = state.wsize - copy;
  14410. }
  14411. else {
  14412. from = state.wnext - copy;
  14413. }
  14414. if (copy > state.length) { copy = state.length; }
  14415. from_source = state.window;
  14416. }
  14417. else { /* copy from output */
  14418. from_source = output;
  14419. from = put - state.offset;
  14420. copy = state.length;
  14421. }
  14422. if (copy > left) { copy = left; }
  14423. left -= copy;
  14424. state.length -= copy;
  14425. do {
  14426. output[put++] = from_source[from++];
  14427. } while (--copy);
  14428. if (state.length === 0) { state.mode = LEN; }
  14429. break;
  14430. case LIT:
  14431. if (left === 0) { break inf_leave; }
  14432. output[put++] = state.length;
  14433. left--;
  14434. state.mode = LEN;
  14435. break;
  14436. case CHECK:
  14437. if (state.wrap) {
  14438. //=== NEEDBITS(32);
  14439. while (bits < 32) {
  14440. if (have === 0) { break inf_leave; }
  14441. have--;
  14442. // Use '|' insdead of '+' to make sure that result is signed
  14443. hold |= input[next++] << bits;
  14444. bits += 8;
  14445. }
  14446. //===//
  14447. _out -= left;
  14448. strm.total_out += _out;
  14449. state.total += _out;
  14450. if (_out) {
  14451. strm.adler = state.check =
  14452. /*UPDATE(state.check, put - _out, _out);*/
  14453. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  14454. }
  14455. _out = left;
  14456. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  14457. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  14458. strm.msg = 'incorrect data check';
  14459. state.mode = BAD;
  14460. break;
  14461. }
  14462. //=== INITBITS();
  14463. hold = 0;
  14464. bits = 0;
  14465. //===//
  14466. //Tracev((stderr, "inflate: check matches trailer\n"));
  14467. }
  14468. state.mode = LENGTH;
  14469. /* falls through */
  14470. case LENGTH:
  14471. if (state.wrap && state.flags) {
  14472. //=== NEEDBITS(32);
  14473. while (bits < 32) {
  14474. if (have === 0) { break inf_leave; }
  14475. have--;
  14476. hold += input[next++] << bits;
  14477. bits += 8;
  14478. }
  14479. //===//
  14480. if (hold !== (state.total & 0xffffffff)) {
  14481. strm.msg = 'incorrect length check';
  14482. state.mode = BAD;
  14483. break;
  14484. }
  14485. //=== INITBITS();
  14486. hold = 0;
  14487. bits = 0;
  14488. //===//
  14489. //Tracev((stderr, "inflate: length matches trailer\n"));
  14490. }
  14491. state.mode = DONE;
  14492. /* falls through */
  14493. case DONE:
  14494. ret = Z_STREAM_END;
  14495. break inf_leave;
  14496. case BAD:
  14497. ret = Z_DATA_ERROR;
  14498. break inf_leave;
  14499. case MEM:
  14500. return Z_MEM_ERROR;
  14501. case SYNC:
  14502. /* falls through */
  14503. default:
  14504. return Z_STREAM_ERROR;
  14505. }
  14506. }
  14507. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  14508. /*
  14509. Return from inflate(), updating the total counts and the check value.
  14510. If there was no progress during the inflate() call, return a buffer
  14511. error. Call updatewindow() to create and/or update the window state.
  14512. Note: a memory error from inflate() is non-recoverable.
  14513. */
  14514. //--- RESTORE() ---
  14515. strm.next_out = put;
  14516. strm.avail_out = left;
  14517. strm.next_in = next;
  14518. strm.avail_in = have;
  14519. state.hold = hold;
  14520. state.bits = bits;
  14521. //---
  14522. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  14523. (state.mode < CHECK || flush !== Z_FINISH))) {
  14524. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  14525. state.mode = MEM;
  14526. return Z_MEM_ERROR;
  14527. }
  14528. }
  14529. _in -= strm.avail_in;
  14530. _out -= strm.avail_out;
  14531. strm.total_in += _in;
  14532. strm.total_out += _out;
  14533. state.total += _out;
  14534. if (state.wrap && _out) {
  14535. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  14536. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  14537. }
  14538. strm.data_type = state.bits + (state.last ? 64 : 0) +
  14539. (state.mode === TYPE ? 128 : 0) +
  14540. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  14541. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  14542. ret = Z_BUF_ERROR;
  14543. }
  14544. return ret;
  14545. }
  14546. function inflateEnd(strm) {
  14547. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  14548. return Z_STREAM_ERROR;
  14549. }
  14550. var state = strm.state;
  14551. if (state.window) {
  14552. state.window = null;
  14553. }
  14554. strm.state = null;
  14555. return Z_OK;
  14556. }
  14557. function inflateGetHeader(strm, head) {
  14558. var state;
  14559. /* check state */
  14560. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  14561. state = strm.state;
  14562. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  14563. /* save header structure */
  14564. state.head = head;
  14565. head.done = false;
  14566. return Z_OK;
  14567. }
  14568. exports.inflateReset = inflateReset;
  14569. exports.inflateReset2 = inflateReset2;
  14570. exports.inflateResetKeep = inflateResetKeep;
  14571. exports.inflateInit = inflateInit;
  14572. exports.inflateInit2 = inflateInit2;
  14573. exports.inflate = inflate;
  14574. exports.inflateEnd = inflateEnd;
  14575. exports.inflateGetHeader = inflateGetHeader;
  14576. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  14577. /* Not implemented
  14578. exports.inflateCopy = inflateCopy;
  14579. exports.inflateGetDictionary = inflateGetDictionary;
  14580. exports.inflateMark = inflateMark;
  14581. exports.inflatePrime = inflatePrime;
  14582. exports.inflateSetDictionary = inflateSetDictionary;
  14583. exports.inflateSync = inflateSync;
  14584. exports.inflateSyncPoint = inflateSyncPoint;
  14585. exports.inflateUndermine = inflateUndermine;
  14586. */
  14587. },{"../utils/common":39,"./adler32":41,"./crc32":43,"./inffast":46,"./inftrees":48}],48:[function(require,module,exports){
  14588. 'use strict';
  14589. var utils = require('../utils/common');
  14590. var MAXBITS = 15;
  14591. var ENOUGH_LENS = 852;
  14592. var ENOUGH_DISTS = 592;
  14593. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  14594. var CODES = 0;
  14595. var LENS = 1;
  14596. var DISTS = 2;
  14597. var lbase = [ /* Length codes 257..285 base */
  14598. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  14599. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  14600. ];
  14601. var lext = [ /* Length codes 257..285 extra */
  14602. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  14603. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  14604. ];
  14605. var dbase = [ /* Distance codes 0..29 base */
  14606. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  14607. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  14608. 8193, 12289, 16385, 24577, 0, 0
  14609. ];
  14610. var dext = [ /* Distance codes 0..29 extra */
  14611. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  14612. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  14613. 28, 28, 29, 29, 64, 64
  14614. ];
  14615. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  14616. {
  14617. var bits = opts.bits;
  14618. //here = opts.here; /* table entry for duplication */
  14619. var len = 0; /* a code's length in bits */
  14620. var sym = 0; /* index of code symbols */
  14621. var min = 0, max = 0; /* minimum and maximum code lengths */
  14622. var root = 0; /* number of index bits for root table */
  14623. var curr = 0; /* number of index bits for current table */
  14624. var drop = 0; /* code bits to drop for sub-table */
  14625. var left = 0; /* number of prefix codes available */
  14626. var used = 0; /* code entries in table used */
  14627. var huff = 0; /* Huffman code */
  14628. var incr; /* for incrementing code, index */
  14629. var fill; /* index for replicating entries */
  14630. var low; /* low bits for current root entry */
  14631. var mask; /* mask for low root bits */
  14632. var next; /* next available space in table */
  14633. var base = null; /* base value table to use */
  14634. var base_index = 0;
  14635. // var shoextra; /* extra bits table to use */
  14636. var end; /* use base and extra for symbol > end */
  14637. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  14638. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  14639. var extra = null;
  14640. var extra_index = 0;
  14641. var here_bits, here_op, here_val;
  14642. /*
  14643. Process a set of code lengths to create a canonical Huffman code. The
  14644. code lengths are lens[0..codes-1]. Each length corresponds to the
  14645. symbols 0..codes-1. The Huffman code is generated by first sorting the
  14646. symbols by length from short to long, and retaining the symbol order
  14647. for codes with equal lengths. Then the code starts with all zero bits
  14648. for the first code of the shortest length, and the codes are integer
  14649. increments for the same length, and zeros are appended as the length
  14650. increases. For the deflate format, these bits are stored backwards
  14651. from their more natural integer increment ordering, and so when the
  14652. decoding tables are built in the large loop below, the integer codes
  14653. are incremented backwards.
  14654. This routine assumes, but does not check, that all of the entries in
  14655. lens[] are in the range 0..MAXBITS. The caller must assure this.
  14656. 1..MAXBITS is interpreted as that code length. zero means that that
  14657. symbol does not occur in this code.
  14658. The codes are sorted by computing a count of codes for each length,
  14659. creating from that a table of starting indices for each length in the
  14660. sorted table, and then entering the symbols in order in the sorted
  14661. table. The sorted table is work[], with that space being provided by
  14662. the caller.
  14663. The length counts are used for other purposes as well, i.e. finding
  14664. the minimum and maximum length codes, determining if there are any
  14665. codes at all, checking for a valid set of lengths, and looking ahead
  14666. at length counts to determine sub-table sizes when building the
  14667. decoding tables.
  14668. */
  14669. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  14670. for (len = 0; len <= MAXBITS; len++) {
  14671. count[len] = 0;
  14672. }
  14673. for (sym = 0; sym < codes; sym++) {
  14674. count[lens[lens_index + sym]]++;
  14675. }
  14676. /* bound code lengths, force root to be within code lengths */
  14677. root = bits;
  14678. for (max = MAXBITS; max >= 1; max--) {
  14679. if (count[max] !== 0) { break; }
  14680. }
  14681. if (root > max) {
  14682. root = max;
  14683. }
  14684. if (max === 0) { /* no symbols to code at all */
  14685. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  14686. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  14687. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  14688. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  14689. //table.op[opts.table_index] = 64;
  14690. //table.bits[opts.table_index] = 1;
  14691. //table.val[opts.table_index++] = 0;
  14692. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  14693. opts.bits = 1;
  14694. return 0; /* no symbols, but wait for decoding to report error */
  14695. }
  14696. for (min = 1; min < max; min++) {
  14697. if (count[min] !== 0) { break; }
  14698. }
  14699. if (root < min) {
  14700. root = min;
  14701. }
  14702. /* check for an over-subscribed or incomplete set of lengths */
  14703. left = 1;
  14704. for (len = 1; len <= MAXBITS; len++) {
  14705. left <<= 1;
  14706. left -= count[len];
  14707. if (left < 0) {
  14708. return -1;
  14709. } /* over-subscribed */
  14710. }
  14711. if (left > 0 && (type === CODES || max !== 1)) {
  14712. return -1; /* incomplete set */
  14713. }
  14714. /* generate offsets into symbol table for each length for sorting */
  14715. offs[1] = 0;
  14716. for (len = 1; len < MAXBITS; len++) {
  14717. offs[len + 1] = offs[len] + count[len];
  14718. }
  14719. /* sort symbols by length, by symbol order within each length */
  14720. for (sym = 0; sym < codes; sym++) {
  14721. if (lens[lens_index + sym] !== 0) {
  14722. work[offs[lens[lens_index + sym]]++] = sym;
  14723. }
  14724. }
  14725. /*
  14726. Create and fill in decoding tables. In this loop, the table being
  14727. filled is at next and has curr index bits. The code being used is huff
  14728. with length len. That code is converted to an index by dropping drop
  14729. bits off of the bottom. For codes where len is less than drop + curr,
  14730. those top drop + curr - len bits are incremented through all values to
  14731. fill the table with replicated entries.
  14732. root is the number of index bits for the root table. When len exceeds
  14733. root, sub-tables are created pointed to by the root entry with an index
  14734. of the low root bits of huff. This is saved in low to check for when a
  14735. new sub-table should be started. drop is zero when the root table is
  14736. being filled, and drop is root when sub-tables are being filled.
  14737. When a new sub-table is needed, it is necessary to look ahead in the
  14738. code lengths to determine what size sub-table is needed. The length
  14739. counts are used for this, and so count[] is decremented as codes are
  14740. entered in the tables.
  14741. used keeps track of how many table entries have been allocated from the
  14742. provided *table space. It is checked for LENS and DIST tables against
  14743. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  14744. the initial root table size constants. See the comments in inftrees.h
  14745. for more information.
  14746. sym increments through all symbols, and the loop terminates when
  14747. all codes of length max, i.e. all codes, have been processed. This
  14748. routine permits incomplete codes, so another loop after this one fills
  14749. in the rest of the decoding tables with invalid code markers.
  14750. */
  14751. /* set up for code type */
  14752. // poor man optimization - use if-else instead of switch,
  14753. // to avoid deopts in old v8
  14754. if (type === CODES) {
  14755. base = extra = work; /* dummy value--not used */
  14756. end = 19;
  14757. } else if (type === LENS) {
  14758. base = lbase;
  14759. base_index -= 257;
  14760. extra = lext;
  14761. extra_index -= 257;
  14762. end = 256;
  14763. } else { /* DISTS */
  14764. base = dbase;
  14765. extra = dext;
  14766. end = -1;
  14767. }
  14768. /* initialize opts for loop */
  14769. huff = 0; /* starting code */
  14770. sym = 0; /* starting code symbol */
  14771. len = min; /* starting code length */
  14772. next = table_index; /* current table to fill in */
  14773. curr = root; /* current table index bits */
  14774. drop = 0; /* current bits to drop from code for index */
  14775. low = -1; /* trigger new sub-table when len > root */
  14776. used = 1 << root; /* use root table entries */
  14777. mask = used - 1; /* mask for comparing low */
  14778. /* check available table space */
  14779. if ((type === LENS && used > ENOUGH_LENS) ||
  14780. (type === DISTS && used > ENOUGH_DISTS)) {
  14781. return 1;
  14782. }
  14783. var i=0;
  14784. /* process all codes and make table entries */
  14785. for (;;) {
  14786. i++;
  14787. /* create table entry */
  14788. here_bits = len - drop;
  14789. if (work[sym] < end) {
  14790. here_op = 0;
  14791. here_val = work[sym];
  14792. }
  14793. else if (work[sym] > end) {
  14794. here_op = extra[extra_index + work[sym]];
  14795. here_val = base[base_index + work[sym]];
  14796. }
  14797. else {
  14798. here_op = 32 + 64; /* end of block */
  14799. here_val = 0;
  14800. }
  14801. /* replicate for those indices with low len bits equal to huff */
  14802. incr = 1 << (len - drop);
  14803. fill = 1 << curr;
  14804. min = fill; /* save offset to next table */
  14805. do {
  14806. fill -= incr;
  14807. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  14808. } while (fill !== 0);
  14809. /* backwards increment the len-bit code huff */
  14810. incr = 1 << (len - 1);
  14811. while (huff & incr) {
  14812. incr >>= 1;
  14813. }
  14814. if (incr !== 0) {
  14815. huff &= incr - 1;
  14816. huff += incr;
  14817. } else {
  14818. huff = 0;
  14819. }
  14820. /* go to next symbol, update count, len */
  14821. sym++;
  14822. if (--count[len] === 0) {
  14823. if (len === max) { break; }
  14824. len = lens[lens_index + work[sym]];
  14825. }
  14826. /* create new sub-table if needed */
  14827. if (len > root && (huff & mask) !== low) {
  14828. /* if first time, transition to sub-tables */
  14829. if (drop === 0) {
  14830. drop = root;
  14831. }
  14832. /* increment past last table */
  14833. next += min; /* here min is 1 << curr */
  14834. /* determine length of next table */
  14835. curr = len - drop;
  14836. left = 1 << curr;
  14837. while (curr + drop < max) {
  14838. left -= count[curr + drop];
  14839. if (left <= 0) { break; }
  14840. curr++;
  14841. left <<= 1;
  14842. }
  14843. /* check for enough space */
  14844. used += 1 << curr;
  14845. if ((type === LENS && used > ENOUGH_LENS) ||
  14846. (type === DISTS && used > ENOUGH_DISTS)) {
  14847. return 1;
  14848. }
  14849. /* point entry in root table to sub-table */
  14850. low = huff & mask;
  14851. /*table.op[low] = curr;
  14852. table.bits[low] = root;
  14853. table.val[low] = next - opts.table_index;*/
  14854. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  14855. }
  14856. }
  14857. /* fill in remaining table entry if code is incomplete (guaranteed to have
  14858. at most one remaining entry, since if the code is incomplete, the
  14859. maximum code length that was allowed to get this far is one bit) */
  14860. if (huff !== 0) {
  14861. //table.op[next + huff] = 64; /* invalid code marker */
  14862. //table.bits[next + huff] = len - drop;
  14863. //table.val[next + huff] = 0;
  14864. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  14865. }
  14866. /* set return parameters */
  14867. //opts.table_index += used;
  14868. opts.bits = root;
  14869. return 0;
  14870. };
  14871. },{"../utils/common":39}],49:[function(require,module,exports){
  14872. 'use strict';
  14873. module.exports = {
  14874. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  14875. '1': 'stream end', /* Z_STREAM_END 1 */
  14876. '0': '', /* Z_OK 0 */
  14877. '-1': 'file error', /* Z_ERRNO (-1) */
  14878. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  14879. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  14880. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  14881. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  14882. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  14883. };
  14884. },{}],50:[function(require,module,exports){
  14885. 'use strict';
  14886. var utils = require('../utils/common');
  14887. /* Public constants ==========================================================*/
  14888. /* ===========================================================================*/
  14889. //var Z_FILTERED = 1;
  14890. //var Z_HUFFMAN_ONLY = 2;
  14891. //var Z_RLE = 3;
  14892. var Z_FIXED = 4;
  14893. //var Z_DEFAULT_STRATEGY = 0;
  14894. /* Possible values of the data_type field (though see inflate()) */
  14895. var Z_BINARY = 0;
  14896. var Z_TEXT = 1;
  14897. //var Z_ASCII = 1; // = Z_TEXT
  14898. var Z_UNKNOWN = 2;
  14899. /*============================================================================*/
  14900. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  14901. // From zutil.h
  14902. var STORED_BLOCK = 0;
  14903. var STATIC_TREES = 1;
  14904. var DYN_TREES = 2;
  14905. /* The three kinds of block type */
  14906. var MIN_MATCH = 3;
  14907. var MAX_MATCH = 258;
  14908. /* The minimum and maximum match lengths */
  14909. // From deflate.h
  14910. /* ===========================================================================
  14911. * Internal compression state.
  14912. */
  14913. var LENGTH_CODES = 29;
  14914. /* number of length codes, not counting the special END_BLOCK code */
  14915. var LITERALS = 256;
  14916. /* number of literal bytes 0..255 */
  14917. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  14918. /* number of Literal or Length codes, including the END_BLOCK code */
  14919. var D_CODES = 30;
  14920. /* number of distance codes */
  14921. var BL_CODES = 19;
  14922. /* number of codes used to transfer the bit lengths */
  14923. var HEAP_SIZE = 2*L_CODES + 1;
  14924. /* maximum heap size */
  14925. var MAX_BITS = 15;
  14926. /* All codes must not exceed MAX_BITS bits */
  14927. var Buf_size = 16;
  14928. /* size of bit buffer in bi_buf */
  14929. /* ===========================================================================
  14930. * Constants
  14931. */
  14932. var MAX_BL_BITS = 7;
  14933. /* Bit length codes must not exceed MAX_BL_BITS bits */
  14934. var END_BLOCK = 256;
  14935. /* end of block literal code */
  14936. var REP_3_6 = 16;
  14937. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  14938. var REPZ_3_10 = 17;
  14939. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  14940. var REPZ_11_138 = 18;
  14941. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  14942. var extra_lbits = /* extra bits for each length code */
  14943. [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];
  14944. var extra_dbits = /* extra bits for each distance code */
  14945. [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];
  14946. var extra_blbits = /* extra bits for each bit length code */
  14947. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  14948. var bl_order =
  14949. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  14950. /* The lengths of the bit length codes are sent in order of decreasing
  14951. * probability, to avoid transmitting the lengths for unused bit length codes.
  14952. */
  14953. /* ===========================================================================
  14954. * Local data. These are initialized only once.
  14955. */
  14956. // We pre-fill arrays with 0 to avoid uninitialized gaps
  14957. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  14958. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  14959. var static_ltree = new Array((L_CODES+2) * 2);
  14960. zero(static_ltree);
  14961. /* The static literal tree. Since the bit lengths are imposed, there is no
  14962. * need for the L_CODES extra codes used during heap construction. However
  14963. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  14964. * below).
  14965. */
  14966. var static_dtree = new Array(D_CODES * 2);
  14967. zero(static_dtree);
  14968. /* The static distance tree. (Actually a trivial tree since all codes use
  14969. * 5 bits.)
  14970. */
  14971. var _dist_code = new Array(DIST_CODE_LEN);
  14972. zero(_dist_code);
  14973. /* Distance codes. The first 256 values correspond to the distances
  14974. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  14975. * the 15 bit distances.
  14976. */
  14977. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  14978. zero(_length_code);
  14979. /* length code for each normalized match length (0 == MIN_MATCH) */
  14980. var base_length = new Array(LENGTH_CODES);
  14981. zero(base_length);
  14982. /* First normalized length for each code (0 = MIN_MATCH) */
  14983. var base_dist = new Array(D_CODES);
  14984. zero(base_dist);
  14985. /* First normalized distance for each code (0 = distance of 1) */
  14986. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  14987. this.static_tree = static_tree; /* static tree or NULL */
  14988. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  14989. this.extra_base = extra_base; /* base index for extra_bits */
  14990. this.elems = elems; /* max number of elements in the tree */
  14991. this.max_length = max_length; /* max bit length for the codes */
  14992. // show if `static_tree` has data or dummy - needed for monomorphic objects
  14993. this.has_stree = static_tree && static_tree.length;
  14994. };
  14995. var static_l_desc;
  14996. var static_d_desc;
  14997. var static_bl_desc;
  14998. var TreeDesc = function(dyn_tree, stat_desc) {
  14999. this.dyn_tree = dyn_tree; /* the dynamic tree */
  15000. this.max_code = 0; /* largest code with non zero frequency */
  15001. this.stat_desc = stat_desc; /* the corresponding static tree */
  15002. };
  15003. function d_code(dist) {
  15004. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  15005. }
  15006. /* ===========================================================================
  15007. * Output a short LSB first on the stream.
  15008. * IN assertion: there is enough room in pendingBuf.
  15009. */
  15010. function put_short (s, w) {
  15011. // put_byte(s, (uch)((w) & 0xff));
  15012. // put_byte(s, (uch)((ush)(w) >> 8));
  15013. s.pending_buf[s.pending++] = (w) & 0xff;
  15014. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  15015. }
  15016. /* ===========================================================================
  15017. * Send a value on a given number of bits.
  15018. * IN assertion: length <= 16 and value fits in length bits.
  15019. */
  15020. function send_bits(s, value, length) {
  15021. if (s.bi_valid > (Buf_size - length)) {
  15022. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  15023. put_short(s, s.bi_buf);
  15024. s.bi_buf = value >> (Buf_size - s.bi_valid);
  15025. s.bi_valid += length - Buf_size;
  15026. } else {
  15027. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  15028. s.bi_valid += length;
  15029. }
  15030. }
  15031. function send_code(s, c, tree) {
  15032. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  15033. }
  15034. /* ===========================================================================
  15035. * Reverse the first len bits of a code, using straightforward code (a faster
  15036. * method would use a table)
  15037. * IN assertion: 1 <= len <= 15
  15038. */
  15039. function bi_reverse(code, len) {
  15040. var res = 0;
  15041. do {
  15042. res |= code & 1;
  15043. code >>>= 1;
  15044. res <<= 1;
  15045. } while (--len > 0);
  15046. return res >>> 1;
  15047. }
  15048. /* ===========================================================================
  15049. * Flush the bit buffer, keeping at most 7 bits in it.
  15050. */
  15051. function bi_flush(s) {
  15052. if (s.bi_valid === 16) {
  15053. put_short(s, s.bi_buf);
  15054. s.bi_buf = 0;
  15055. s.bi_valid = 0;
  15056. } else if (s.bi_valid >= 8) {
  15057. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  15058. s.bi_buf >>= 8;
  15059. s.bi_valid -= 8;
  15060. }
  15061. }
  15062. /* ===========================================================================
  15063. * Compute the optimal bit lengths for a tree and update the total bit length
  15064. * for the current block.
  15065. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  15066. * above are the tree nodes sorted by increasing frequency.
  15067. * OUT assertions: the field len is set to the optimal bit length, the
  15068. * array bl_count contains the frequencies for each bit length.
  15069. * The length opt_len is updated; static_len is also updated if stree is
  15070. * not null.
  15071. */
  15072. function gen_bitlen(s, desc)
  15073. // deflate_state *s;
  15074. // tree_desc *desc; /* the tree descriptor */
  15075. {
  15076. var tree = desc.dyn_tree;
  15077. var max_code = desc.max_code;
  15078. var stree = desc.stat_desc.static_tree;
  15079. var has_stree = desc.stat_desc.has_stree;
  15080. var extra = desc.stat_desc.extra_bits;
  15081. var base = desc.stat_desc.extra_base;
  15082. var max_length = desc.stat_desc.max_length;
  15083. var h; /* heap index */
  15084. var n, m; /* iterate over the tree elements */
  15085. var bits; /* bit length */
  15086. var xbits; /* extra bits */
  15087. var f; /* frequency */
  15088. var overflow = 0; /* number of elements with bit length too large */
  15089. for (bits = 0; bits <= MAX_BITS; bits++) {
  15090. s.bl_count[bits] = 0;
  15091. }
  15092. /* In a first pass, compute the optimal bit lengths (which may
  15093. * overflow in the case of the bit length tree).
  15094. */
  15095. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  15096. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  15097. n = s.heap[h];
  15098. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  15099. if (bits > max_length) {
  15100. bits = max_length;
  15101. overflow++;
  15102. }
  15103. tree[n*2 + 1]/*.Len*/ = bits;
  15104. /* We overwrite tree[n].Dad which is no longer needed */
  15105. if (n > max_code) { continue; } /* not a leaf node */
  15106. s.bl_count[bits]++;
  15107. xbits = 0;
  15108. if (n >= base) {
  15109. xbits = extra[n-base];
  15110. }
  15111. f = tree[n * 2]/*.Freq*/;
  15112. s.opt_len += f * (bits + xbits);
  15113. if (has_stree) {
  15114. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  15115. }
  15116. }
  15117. if (overflow === 0) { return; }
  15118. // Trace((stderr,"\nbit length overflow\n"));
  15119. /* This happens for example on obj2 and pic of the Calgary corpus */
  15120. /* Find the first bit length which could increase: */
  15121. do {
  15122. bits = max_length-1;
  15123. while (s.bl_count[bits] === 0) { bits--; }
  15124. s.bl_count[bits]--; /* move one leaf down the tree */
  15125. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  15126. s.bl_count[max_length]--;
  15127. /* The brother of the overflow item also moves one step up,
  15128. * but this does not affect bl_count[max_length]
  15129. */
  15130. overflow -= 2;
  15131. } while (overflow > 0);
  15132. /* Now recompute all bit lengths, scanning in increasing frequency.
  15133. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  15134. * lengths instead of fixing only the wrong ones. This idea is taken
  15135. * from 'ar' written by Haruhiko Okumura.)
  15136. */
  15137. for (bits = max_length; bits !== 0; bits--) {
  15138. n = s.bl_count[bits];
  15139. while (n !== 0) {
  15140. m = s.heap[--h];
  15141. if (m > max_code) { continue; }
  15142. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  15143. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  15144. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  15145. tree[m*2 + 1]/*.Len*/ = bits;
  15146. }
  15147. n--;
  15148. }
  15149. }
  15150. }
  15151. /* ===========================================================================
  15152. * Generate the codes for a given tree and bit counts (which need not be
  15153. * optimal).
  15154. * IN assertion: the array bl_count contains the bit length statistics for
  15155. * the given tree and the field len is set for all tree elements.
  15156. * OUT assertion: the field code is set for all tree elements of non
  15157. * zero code length.
  15158. */
  15159. function gen_codes(tree, max_code, bl_count)
  15160. // ct_data *tree; /* the tree to decorate */
  15161. // int max_code; /* largest code with non zero frequency */
  15162. // ushf *bl_count; /* number of codes at each bit length */
  15163. {
  15164. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  15165. var code = 0; /* running code value */
  15166. var bits; /* bit index */
  15167. var n; /* code index */
  15168. /* The distribution counts are first used to generate the code values
  15169. * without bit reversal.
  15170. */
  15171. for (bits = 1; bits <= MAX_BITS; bits++) {
  15172. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  15173. }
  15174. /* Check that the bit counts in bl_count are consistent. The last code
  15175. * must be all ones.
  15176. */
  15177. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  15178. // "inconsistent bit counts");
  15179. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  15180. for (n = 0; n <= max_code; n++) {
  15181. var len = tree[n*2 + 1]/*.Len*/;
  15182. if (len === 0) { continue; }
  15183. /* Now reverse the bits */
  15184. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  15185. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  15186. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  15187. }
  15188. }
  15189. /* ===========================================================================
  15190. * Initialize the various 'constant' tables.
  15191. */
  15192. function tr_static_init() {
  15193. var n; /* iterates over tree elements */
  15194. var bits; /* bit counter */
  15195. var length; /* length value */
  15196. var code; /* code value */
  15197. var dist; /* distance index */
  15198. var bl_count = new Array(MAX_BITS+1);
  15199. /* number of codes at each bit length for an optimal tree */
  15200. // do check in _tr_init()
  15201. //if (static_init_done) return;
  15202. /* For some embedded targets, global variables are not initialized: */
  15203. /*#ifdef NO_INIT_GLOBAL_POINTERS
  15204. static_l_desc.static_tree = static_ltree;
  15205. static_l_desc.extra_bits = extra_lbits;
  15206. static_d_desc.static_tree = static_dtree;
  15207. static_d_desc.extra_bits = extra_dbits;
  15208. static_bl_desc.extra_bits = extra_blbits;
  15209. #endif*/
  15210. /* Initialize the mapping length (0..255) -> length code (0..28) */
  15211. length = 0;
  15212. for (code = 0; code < LENGTH_CODES-1; code++) {
  15213. base_length[code] = length;
  15214. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  15215. _length_code[length++] = code;
  15216. }
  15217. }
  15218. //Assert (length == 256, "tr_static_init: length != 256");
  15219. /* Note that the length 255 (match length 258) can be represented
  15220. * in two different ways: code 284 + 5 bits or code 285, so we
  15221. * overwrite length_code[255] to use the best encoding:
  15222. */
  15223. _length_code[length-1] = code;
  15224. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  15225. dist = 0;
  15226. for (code = 0 ; code < 16; code++) {
  15227. base_dist[code] = dist;
  15228. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  15229. _dist_code[dist++] = code;
  15230. }
  15231. }
  15232. //Assert (dist == 256, "tr_static_init: dist != 256");
  15233. dist >>= 7; /* from now on, all distances are divided by 128 */
  15234. for (; code < D_CODES; code++) {
  15235. base_dist[code] = dist << 7;
  15236. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  15237. _dist_code[256 + dist++] = code;
  15238. }
  15239. }
  15240. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  15241. /* Construct the codes of the static literal tree */
  15242. for (bits = 0; bits <= MAX_BITS; bits++) {
  15243. bl_count[bits] = 0;
  15244. }
  15245. n = 0;
  15246. while (n <= 143) {
  15247. static_ltree[n*2 + 1]/*.Len*/ = 8;
  15248. n++;
  15249. bl_count[8]++;
  15250. }
  15251. while (n <= 255) {
  15252. static_ltree[n*2 + 1]/*.Len*/ = 9;
  15253. n++;
  15254. bl_count[9]++;
  15255. }
  15256. while (n <= 279) {
  15257. static_ltree[n*2 + 1]/*.Len*/ = 7;
  15258. n++;
  15259. bl_count[7]++;
  15260. }
  15261. while (n <= 287) {
  15262. static_ltree[n*2 + 1]/*.Len*/ = 8;
  15263. n++;
  15264. bl_count[8]++;
  15265. }
  15266. /* Codes 286 and 287 do not exist, but we must include them in the
  15267. * tree construction to get a canonical Huffman tree (longest code
  15268. * all ones)
  15269. */
  15270. gen_codes(static_ltree, L_CODES+1, bl_count);
  15271. /* The static distance tree is trivial: */
  15272. for (n = 0; n < D_CODES; n++) {
  15273. static_dtree[n*2 + 1]/*.Len*/ = 5;
  15274. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  15275. }
  15276. // Now data ready and we can init static trees
  15277. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  15278. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  15279. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  15280. //static_init_done = true;
  15281. }
  15282. /* ===========================================================================
  15283. * Initialize a new block.
  15284. */
  15285. function init_block(s) {
  15286. var n; /* iterates over tree elements */
  15287. /* Initialize the trees. */
  15288. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  15289. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  15290. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  15291. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  15292. s.opt_len = s.static_len = 0;
  15293. s.last_lit = s.matches = 0;
  15294. }
  15295. /* ===========================================================================
  15296. * Flush the bit buffer and align the output on a byte boundary
  15297. */
  15298. function bi_windup(s)
  15299. {
  15300. if (s.bi_valid > 8) {
  15301. put_short(s, s.bi_buf);
  15302. } else if (s.bi_valid > 0) {
  15303. //put_byte(s, (Byte)s->bi_buf);
  15304. s.pending_buf[s.pending++] = s.bi_buf;
  15305. }
  15306. s.bi_buf = 0;
  15307. s.bi_valid = 0;
  15308. }
  15309. /* ===========================================================================
  15310. * Copy a stored block, storing first the length and its
  15311. * one's complement if requested.
  15312. */
  15313. function copy_block(s, buf, len, header)
  15314. //DeflateState *s;
  15315. //charf *buf; /* the input data */
  15316. //unsigned len; /* its length */
  15317. //int header; /* true if block header must be written */
  15318. {
  15319. bi_windup(s); /* align on byte boundary */
  15320. if (header) {
  15321. put_short(s, len);
  15322. put_short(s, ~len);
  15323. }
  15324. // while (len--) {
  15325. // put_byte(s, *buf++);
  15326. // }
  15327. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  15328. s.pending += len;
  15329. }
  15330. /* ===========================================================================
  15331. * Compares to subtrees, using the tree depth as tie breaker when
  15332. * the subtrees have equal frequency. This minimizes the worst case length.
  15333. */
  15334. function smaller(tree, n, m, depth) {
  15335. var _n2 = n*2;
  15336. var _m2 = m*2;
  15337. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  15338. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  15339. }
  15340. /* ===========================================================================
  15341. * Restore the heap property by moving down the tree starting at node k,
  15342. * exchanging a node with the smallest of its two sons if necessary, stopping
  15343. * when the heap property is re-established (each father smaller than its
  15344. * two sons).
  15345. */
  15346. function pqdownheap(s, tree, k)
  15347. // deflate_state *s;
  15348. // ct_data *tree; /* the tree to restore */
  15349. // int k; /* node to move down */
  15350. {
  15351. var v = s.heap[k];
  15352. var j = k << 1; /* left son of k */
  15353. while (j <= s.heap_len) {
  15354. /* Set j to the smallest of the two sons: */
  15355. if (j < s.heap_len &&
  15356. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  15357. j++;
  15358. }
  15359. /* Exit if v is smaller than both sons */
  15360. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  15361. /* Exchange v with the smallest son */
  15362. s.heap[k] = s.heap[j];
  15363. k = j;
  15364. /* And continue down the tree, setting j to the left son of k */
  15365. j <<= 1;
  15366. }
  15367. s.heap[k] = v;
  15368. }
  15369. // inlined manually
  15370. // var SMALLEST = 1;
  15371. /* ===========================================================================
  15372. * Send the block data compressed using the given Huffman trees
  15373. */
  15374. function compress_block(s, ltree, dtree)
  15375. // deflate_state *s;
  15376. // const ct_data *ltree; /* literal tree */
  15377. // const ct_data *dtree; /* distance tree */
  15378. {
  15379. var dist; /* distance of matched string */
  15380. var lc; /* match length or unmatched char (if dist == 0) */
  15381. var lx = 0; /* running index in l_buf */
  15382. var code; /* the code to send */
  15383. var extra; /* number of extra bits to send */
  15384. if (s.last_lit !== 0) {
  15385. do {
  15386. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  15387. lc = s.pending_buf[s.l_buf + lx];
  15388. lx++;
  15389. if (dist === 0) {
  15390. send_code(s, lc, ltree); /* send a literal byte */
  15391. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  15392. } else {
  15393. /* Here, lc is the match length - MIN_MATCH */
  15394. code = _length_code[lc];
  15395. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  15396. extra = extra_lbits[code];
  15397. if (extra !== 0) {
  15398. lc -= base_length[code];
  15399. send_bits(s, lc, extra); /* send the extra length bits */
  15400. }
  15401. dist--; /* dist is now the match distance - 1 */
  15402. code = d_code(dist);
  15403. //Assert (code < D_CODES, "bad d_code");
  15404. send_code(s, code, dtree); /* send the distance code */
  15405. extra = extra_dbits[code];
  15406. if (extra !== 0) {
  15407. dist -= base_dist[code];
  15408. send_bits(s, dist, extra); /* send the extra distance bits */
  15409. }
  15410. } /* literal or match pair ? */
  15411. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  15412. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  15413. // "pendingBuf overflow");
  15414. } while (lx < s.last_lit);
  15415. }
  15416. send_code(s, END_BLOCK, ltree);
  15417. }
  15418. /* ===========================================================================
  15419. * Construct one Huffman tree and assigns the code bit strings and lengths.
  15420. * Update the total bit length for the current block.
  15421. * IN assertion: the field freq is set for all tree elements.
  15422. * OUT assertions: the fields len and code are set to the optimal bit length
  15423. * and corresponding code. The length opt_len is updated; static_len is
  15424. * also updated if stree is not null. The field max_code is set.
  15425. */
  15426. function build_tree(s, desc)
  15427. // deflate_state *s;
  15428. // tree_desc *desc; /* the tree descriptor */
  15429. {
  15430. var tree = desc.dyn_tree;
  15431. var stree = desc.stat_desc.static_tree;
  15432. var has_stree = desc.stat_desc.has_stree;
  15433. var elems = desc.stat_desc.elems;
  15434. var n, m; /* iterate over heap elements */
  15435. var max_code = -1; /* largest code with non zero frequency */
  15436. var node; /* new node being created */
  15437. /* Construct the initial heap, with least frequent element in
  15438. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  15439. * heap[0] is not used.
  15440. */
  15441. s.heap_len = 0;
  15442. s.heap_max = HEAP_SIZE;
  15443. for (n = 0; n < elems; n++) {
  15444. if (tree[n * 2]/*.Freq*/ !== 0) {
  15445. s.heap[++s.heap_len] = max_code = n;
  15446. s.depth[n] = 0;
  15447. } else {
  15448. tree[n*2 + 1]/*.Len*/ = 0;
  15449. }
  15450. }
  15451. /* The pkzip format requires that at least one distance code exists,
  15452. * and that at least one bit should be sent even if there is only one
  15453. * possible code. So to avoid special checks later on we force at least
  15454. * two codes of non zero frequency.
  15455. */
  15456. while (s.heap_len < 2) {
  15457. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  15458. tree[node * 2]/*.Freq*/ = 1;
  15459. s.depth[node] = 0;
  15460. s.opt_len--;
  15461. if (has_stree) {
  15462. s.static_len -= stree[node*2 + 1]/*.Len*/;
  15463. }
  15464. /* node is 0 or 1 so it does not have extra bits */
  15465. }
  15466. desc.max_code = max_code;
  15467. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  15468. * establish sub-heaps of increasing lengths:
  15469. */
  15470. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  15471. /* Construct the Huffman tree by repeatedly combining the least two
  15472. * frequent nodes.
  15473. */
  15474. node = elems; /* next internal node of the tree */
  15475. do {
  15476. //pqremove(s, tree, n); /* n = node of least frequency */
  15477. /*** pqremove ***/
  15478. n = s.heap[1/*SMALLEST*/];
  15479. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  15480. pqdownheap(s, tree, 1/*SMALLEST*/);
  15481. /***/
  15482. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  15483. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  15484. s.heap[--s.heap_max] = m;
  15485. /* Create a new node father of n and m */
  15486. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  15487. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  15488. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  15489. /* and insert the new node in the heap */
  15490. s.heap[1/*SMALLEST*/] = node++;
  15491. pqdownheap(s, tree, 1/*SMALLEST*/);
  15492. } while (s.heap_len >= 2);
  15493. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  15494. /* At this point, the fields freq and dad are set. We can now
  15495. * generate the bit lengths.
  15496. */
  15497. gen_bitlen(s, desc);
  15498. /* The field len is now set, we can generate the bit codes */
  15499. gen_codes(tree, max_code, s.bl_count);
  15500. }
  15501. /* ===========================================================================
  15502. * Scan a literal or distance tree to determine the frequencies of the codes
  15503. * in the bit length tree.
  15504. */
  15505. function scan_tree(s, tree, max_code)
  15506. // deflate_state *s;
  15507. // ct_data *tree; /* the tree to be scanned */
  15508. // int max_code; /* and its largest code of non zero frequency */
  15509. {
  15510. var n; /* iterates over all tree elements */
  15511. var prevlen = -1; /* last emitted length */
  15512. var curlen; /* length of current code */
  15513. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  15514. var count = 0; /* repeat count of the current code */
  15515. var max_count = 7; /* max repeat count */
  15516. var min_count = 4; /* min repeat count */
  15517. if (nextlen === 0) {
  15518. max_count = 138;
  15519. min_count = 3;
  15520. }
  15521. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  15522. for (n = 0; n <= max_code; n++) {
  15523. curlen = nextlen;
  15524. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  15525. if (++count < max_count && curlen === nextlen) {
  15526. continue;
  15527. } else if (count < min_count) {
  15528. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  15529. } else if (curlen !== 0) {
  15530. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  15531. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  15532. } else if (count <= 10) {
  15533. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  15534. } else {
  15535. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  15536. }
  15537. count = 0;
  15538. prevlen = curlen;
  15539. if (nextlen === 0) {
  15540. max_count = 138;
  15541. min_count = 3;
  15542. } else if (curlen === nextlen) {
  15543. max_count = 6;
  15544. min_count = 3;
  15545. } else {
  15546. max_count = 7;
  15547. min_count = 4;
  15548. }
  15549. }
  15550. }
  15551. /* ===========================================================================
  15552. * Send a literal or distance tree in compressed form, using the codes in
  15553. * bl_tree.
  15554. */
  15555. function send_tree(s, tree, max_code)
  15556. // deflate_state *s;
  15557. // ct_data *tree; /* the tree to be scanned */
  15558. // int max_code; /* and its largest code of non zero frequency */
  15559. {
  15560. var n; /* iterates over all tree elements */
  15561. var prevlen = -1; /* last emitted length */
  15562. var curlen; /* length of current code */
  15563. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  15564. var count = 0; /* repeat count of the current code */
  15565. var max_count = 7; /* max repeat count */
  15566. var min_count = 4; /* min repeat count */
  15567. /* tree[max_code+1].Len = -1; */ /* guard already set */
  15568. if (nextlen === 0) {
  15569. max_count = 138;
  15570. min_count = 3;
  15571. }
  15572. for (n = 0; n <= max_code; n++) {
  15573. curlen = nextlen;
  15574. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  15575. if (++count < max_count && curlen === nextlen) {
  15576. continue;
  15577. } else if (count < min_count) {
  15578. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  15579. } else if (curlen !== 0) {
  15580. if (curlen !== prevlen) {
  15581. send_code(s, curlen, s.bl_tree);
  15582. count--;
  15583. }
  15584. //Assert(count >= 3 && count <= 6, " 3_6?");
  15585. send_code(s, REP_3_6, s.bl_tree);
  15586. send_bits(s, count-3, 2);
  15587. } else if (count <= 10) {
  15588. send_code(s, REPZ_3_10, s.bl_tree);
  15589. send_bits(s, count-3, 3);
  15590. } else {
  15591. send_code(s, REPZ_11_138, s.bl_tree);
  15592. send_bits(s, count-11, 7);
  15593. }
  15594. count = 0;
  15595. prevlen = curlen;
  15596. if (nextlen === 0) {
  15597. max_count = 138;
  15598. min_count = 3;
  15599. } else if (curlen === nextlen) {
  15600. max_count = 6;
  15601. min_count = 3;
  15602. } else {
  15603. max_count = 7;
  15604. min_count = 4;
  15605. }
  15606. }
  15607. }
  15608. /* ===========================================================================
  15609. * Construct the Huffman tree for the bit lengths and return the index in
  15610. * bl_order of the last bit length code to send.
  15611. */
  15612. function build_bl_tree(s) {
  15613. var max_blindex; /* index of last bit length code of non zero freq */
  15614. /* Determine the bit length frequencies for literal and distance trees */
  15615. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  15616. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  15617. /* Build the bit length tree: */
  15618. build_tree(s, s.bl_desc);
  15619. /* opt_len now includes the length of the tree representations, except
  15620. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  15621. */
  15622. /* Determine the number of bit length codes to send. The pkzip format
  15623. * requires that at least 4 bit length codes be sent. (appnote.txt says
  15624. * 3 but the actual value used is 4.)
  15625. */
  15626. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  15627. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  15628. break;
  15629. }
  15630. }
  15631. /* Update opt_len to include the bit length tree and counts */
  15632. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  15633. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  15634. // s->opt_len, s->static_len));
  15635. return max_blindex;
  15636. }
  15637. /* ===========================================================================
  15638. * Send the header for a block using dynamic Huffman trees: the counts, the
  15639. * lengths of the bit length codes, the literal tree and the distance tree.
  15640. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  15641. */
  15642. function send_all_trees(s, lcodes, dcodes, blcodes)
  15643. // deflate_state *s;
  15644. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  15645. {
  15646. var rank; /* index in bl_order */
  15647. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  15648. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  15649. // "too many codes");
  15650. //Tracev((stderr, "\nbl counts: "));
  15651. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  15652. send_bits(s, dcodes-1, 5);
  15653. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  15654. for (rank = 0; rank < blcodes; rank++) {
  15655. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  15656. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  15657. }
  15658. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  15659. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  15660. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  15661. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  15662. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  15663. }
  15664. /* ===========================================================================
  15665. * Check if the data type is TEXT or BINARY, using the following algorithm:
  15666. * - TEXT if the two conditions below are satisfied:
  15667. * a) There are no non-portable control characters belonging to the
  15668. * "black list" (0..6, 14..25, 28..31).
  15669. * b) There is at least one printable character belonging to the
  15670. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  15671. * - BINARY otherwise.
  15672. * - The following partially-portable control characters form a
  15673. * "gray list" that is ignored in this detection algorithm:
  15674. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  15675. * IN assertion: the fields Freq of dyn_ltree are set.
  15676. */
  15677. function detect_data_type(s) {
  15678. /* black_mask is the bit mask of black-listed bytes
  15679. * set bits 0..6, 14..25, and 28..31
  15680. * 0xf3ffc07f = binary 11110011111111111100000001111111
  15681. */
  15682. var black_mask = 0xf3ffc07f;
  15683. var n;
  15684. /* Check for non-textual ("black-listed") bytes. */
  15685. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  15686. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  15687. return Z_BINARY;
  15688. }
  15689. }
  15690. /* Check for textual ("white-listed") bytes. */
  15691. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  15692. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  15693. return Z_TEXT;
  15694. }
  15695. for (n = 32; n < LITERALS; n++) {
  15696. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  15697. return Z_TEXT;
  15698. }
  15699. }
  15700. /* There are no "black-listed" or "white-listed" bytes:
  15701. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  15702. */
  15703. return Z_BINARY;
  15704. }
  15705. var static_init_done = false;
  15706. /* ===========================================================================
  15707. * Initialize the tree data structures for a new zlib stream.
  15708. */
  15709. function _tr_init(s)
  15710. {
  15711. if (!static_init_done) {
  15712. tr_static_init();
  15713. static_init_done = true;
  15714. }
  15715. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  15716. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  15717. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  15718. s.bi_buf = 0;
  15719. s.bi_valid = 0;
  15720. /* Initialize the first block of the first file: */
  15721. init_block(s);
  15722. }
  15723. /* ===========================================================================
  15724. * Send a stored block
  15725. */
  15726. function _tr_stored_block(s, buf, stored_len, last)
  15727. //DeflateState *s;
  15728. //charf *buf; /* input block */
  15729. //ulg stored_len; /* length of input block */
  15730. //int last; /* one if this is the last block for a file */
  15731. {
  15732. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  15733. copy_block(s, buf, stored_len, true); /* with header */
  15734. }
  15735. /* ===========================================================================
  15736. * Send one empty static block to give enough lookahead for inflate.
  15737. * This takes 10 bits, of which 7 may remain in the bit buffer.
  15738. */
  15739. function _tr_align(s) {
  15740. send_bits(s, STATIC_TREES<<1, 3);
  15741. send_code(s, END_BLOCK, static_ltree);
  15742. bi_flush(s);
  15743. }
  15744. /* ===========================================================================
  15745. * Determine the best encoding for the current block: dynamic trees, static
  15746. * trees or store, and output the encoded block to the zip file.
  15747. */
  15748. function _tr_flush_block(s, buf, stored_len, last)
  15749. //DeflateState *s;
  15750. //charf *buf; /* input block, or NULL if too old */
  15751. //ulg stored_len; /* length of input block */
  15752. //int last; /* one if this is the last block for a file */
  15753. {
  15754. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  15755. var max_blindex = 0; /* index of last bit length code of non zero freq */
  15756. /* Build the Huffman trees unless a stored block is forced */
  15757. if (s.level > 0) {
  15758. /* Check if the file is binary or text */
  15759. if (s.strm.data_type === Z_UNKNOWN) {
  15760. s.strm.data_type = detect_data_type(s);
  15761. }
  15762. /* Construct the literal and distance trees */
  15763. build_tree(s, s.l_desc);
  15764. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  15765. // s->static_len));
  15766. build_tree(s, s.d_desc);
  15767. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  15768. // s->static_len));
  15769. /* At this point, opt_len and static_len are the total bit lengths of
  15770. * the compressed block data, excluding the tree representations.
  15771. */
  15772. /* Build the bit length tree for the above two trees, and get the index
  15773. * in bl_order of the last bit length code to send.
  15774. */
  15775. max_blindex = build_bl_tree(s);
  15776. /* Determine the best encoding. Compute the block lengths in bytes. */
  15777. opt_lenb = (s.opt_len+3+7) >>> 3;
  15778. static_lenb = (s.static_len+3+7) >>> 3;
  15779. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  15780. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  15781. // s->last_lit));
  15782. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  15783. } else {
  15784. // Assert(buf != (char*)0, "lost buf");
  15785. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  15786. }
  15787. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  15788. /* 4: two words for the lengths */
  15789. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  15790. * Otherwise we can't have processed more than WSIZE input bytes since
  15791. * the last block flush, because compression would have been
  15792. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  15793. * transform a block into a stored block.
  15794. */
  15795. _tr_stored_block(s, buf, stored_len, last);
  15796. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  15797. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  15798. compress_block(s, static_ltree, static_dtree);
  15799. } else {
  15800. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  15801. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  15802. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  15803. }
  15804. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  15805. /* The above check is made mod 2^32, for files larger than 512 MB
  15806. * and uLong implemented on 32 bits.
  15807. */
  15808. init_block(s);
  15809. if (last) {
  15810. bi_windup(s);
  15811. }
  15812. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  15813. // s->compressed_len-7*last));
  15814. }
  15815. /* ===========================================================================
  15816. * Save the match info and tally the frequency counts. Return true if
  15817. * the current block must be flushed.
  15818. */
  15819. function _tr_tally(s, dist, lc)
  15820. // deflate_state *s;
  15821. // unsigned dist; /* distance of matched string */
  15822. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  15823. {
  15824. //var out_length, in_length, dcode;
  15825. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  15826. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  15827. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  15828. s.last_lit++;
  15829. if (dist === 0) {
  15830. /* lc is the unmatched char */
  15831. s.dyn_ltree[lc*2]/*.Freq*/++;
  15832. } else {
  15833. s.matches++;
  15834. /* Here, lc is the match length - MIN_MATCH */
  15835. dist--; /* dist = match distance - 1 */
  15836. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  15837. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  15838. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  15839. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  15840. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  15841. }
  15842. // (!) This block is disabled in zlib defailts,
  15843. // don't enable it for binary compatibility
  15844. //#ifdef TRUNCATE_BLOCK
  15845. // /* Try to guess if it is profitable to stop the current block here */
  15846. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  15847. // /* Compute an upper bound for the compressed length */
  15848. // out_length = s.last_lit*8;
  15849. // in_length = s.strstart - s.block_start;
  15850. //
  15851. // for (dcode = 0; dcode < D_CODES; dcode++) {
  15852. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  15853. // }
  15854. // out_length >>>= 3;
  15855. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  15856. // // s->last_lit, in_length, out_length,
  15857. // // 100L - out_length*100L/in_length));
  15858. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  15859. // return true;
  15860. // }
  15861. // }
  15862. //#endif
  15863. return (s.last_lit === s.lit_bufsize-1);
  15864. /* We avoid equality with lit_bufsize because of wraparound at 64K
  15865. * on 16 bit machines and because stored blocks are restricted to
  15866. * 64K-1 bytes.
  15867. */
  15868. }
  15869. exports._tr_init = _tr_init;
  15870. exports._tr_stored_block = _tr_stored_block;
  15871. exports._tr_flush_block = _tr_flush_block;
  15872. exports._tr_tally = _tr_tally;
  15873. exports._tr_align = _tr_align;
  15874. },{"../utils/common":39}],51:[function(require,module,exports){
  15875. 'use strict';
  15876. function ZStream() {
  15877. /* next input byte */
  15878. this.input = null; // JS specific, because we have no pointers
  15879. this.next_in = 0;
  15880. /* number of bytes available at input */
  15881. this.avail_in = 0;
  15882. /* total number of input bytes read so far */
  15883. this.total_in = 0;
  15884. /* next output byte should be put there */
  15885. this.output = null; // JS specific, because we have no pointers
  15886. this.next_out = 0;
  15887. /* remaining free space at output */
  15888. this.avail_out = 0;
  15889. /* total number of bytes output so far */
  15890. this.total_out = 0;
  15891. /* last error message, NULL if no error */
  15892. this.msg = ''/*Z_NULL*/;
  15893. /* not visible by applications */
  15894. this.state = null;
  15895. /* best guess about the data type: binary or text */
  15896. this.data_type = 2/*Z_UNKNOWN*/;
  15897. /* adler32 value of the uncompressed data */
  15898. this.adler = 0;
  15899. }
  15900. module.exports = ZStream;
  15901. },{}],52:[function(require,module,exports){
  15902. module.exports = function arrayEquals(array) {
  15903. // if the other array is a falsy value, return
  15904. if (!array)
  15905. return false;
  15906. // compare lengths - can save a lot of time
  15907. if (this.length != array.length)
  15908. return false;
  15909. for (var i = 0, l = this.length; i < l; i++) {
  15910. // Check if we have nested arrays
  15911. if (this[i] instanceof Array && array[i] instanceof Array) {
  15912. // recurse into the nested arrays
  15913. if (!arrayEquals.apply(this[i], [array[i]]))
  15914. return false;
  15915. } else if (this[i] != array[i]) {
  15916. // Warning - two different object instances will never be equal:
  15917. // {x:20} != {x:20}
  15918. return false;
  15919. }
  15920. }
  15921. return true;
  15922. }
  15923. },{}],53:[function(require,module,exports){
  15924. exports.Interop = require('./interop');
  15925. },{"./interop":54}],54:[function(require,module,exports){
  15926. "use strict";
  15927. var transform = require('./transform');
  15928. var arrayEquals = require('./array-equals');
  15929. function Interop() {
  15930. /**
  15931. * This map holds the most recent Unified Plan offer/answer SDP that was
  15932. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  15933. * the SDP string as values.
  15934. *
  15935. * @type {{}}
  15936. */
  15937. this.cache = {};
  15938. }
  15939. module.exports = Interop;
  15940. /**
  15941. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  15942. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  15943. * application.
  15944. *
  15945. * @param desc
  15946. * @returns {*}
  15947. */
  15948. Interop.prototype.toPlanB = function(desc) {
  15949. //#region Preliminary input validation.
  15950. if (typeof desc !== 'object' || desc === null ||
  15951. typeof desc.sdp !== 'string') {
  15952. console.warn('An empty description was passed as an argument.');
  15953. return desc;
  15954. }
  15955. // Objectify the SDP for easier manipulation.
  15956. var session = transform.parse(desc.sdp);
  15957. // If the SDP contains no media, there's nothing to transform.
  15958. if (typeof session.media === 'undefined' ||
  15959. !Array.isArray(session.media) || session.media.length === 0) {
  15960. console.warn('The description has no media.');
  15961. return desc;
  15962. }
  15963. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  15964. // SDP has a video, an audio and a data "channel" at most.
  15965. if (session.media.length <= 3 && session.media.every(function(m) {
  15966. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  15967. })) {
  15968. console.warn('This description does not look like Unified Plan.');
  15969. return desc;
  15970. }
  15971. //#endregion
  15972. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  15973. // -> Unified Plan transformation.
  15974. this.cache[desc.type] = desc.sdp;
  15975. //#region Convert from Unified Plan to Plan B.
  15976. // We rebuild the session.media array.
  15977. var media = session.media;
  15978. session.media = [];
  15979. // Associative array that maps channel types to channel objects for fast
  15980. // access to channel objects by their type, e.g. type2bl['audio']->channel
  15981. // obj.
  15982. var type2bl = {};
  15983. // Used to build the group:BUNDLE value after the channels construction
  15984. // loop.
  15985. var types = [];
  15986. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  15987. media.forEach(function(unifiedLine) {
  15988. // rtcp-mux is required in the Plan B SDP.
  15989. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  15990. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  15991. unifiedLine.direction !== 'inactive') {
  15992. throw new Error('Cannot convert to Plan B because m-lines ' +
  15993. 'without the rtcp-mux attribute were found.');
  15994. }
  15995. if (unifiedLine.type === 'application') {
  15996. session.media.push(unifiedLine);
  15997. types.push(unifiedLine.mid);
  15998. return;
  15999. }
  16000. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  16001. // as the channel basis.
  16002. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  16003. type2bl[unifiedLine.type] = unifiedLine;
  16004. }
  16005. // Add sources to the channel and handle a=msid.
  16006. if (typeof unifiedLine.sources === 'object') {
  16007. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  16008. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  16009. type2bl[unifiedLine.type].sources = {};
  16010. // Assign the sources to the channel.
  16011. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  16012. if (typeof unifiedLine.msid !== 'undefined') {
  16013. // In Plan B the msid is an SSRC attribute. Also, we don't
  16014. // care about the obsolete label and mslabel attributes.
  16015. //
  16016. // Note that it is not guaranteed that the unifiedLine will have
  16017. // an msid. recvonly channels in particular don't have one.
  16018. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  16019. }
  16020. // NOTE ssrcs in ssrc groups will share msids, as
  16021. // draft-uberti-rtcweb-plan-00 mandates.
  16022. });
  16023. }
  16024. // Add ssrc groups to the channel.
  16025. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  16026. Array.isArray(unifiedLine.ssrcGroups)) {
  16027. // Create the ssrcGroups array, if it's not defined.
  16028. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  16029. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  16030. type2bl[unifiedLine.type].ssrcGroups = [];
  16031. }
  16032. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  16033. }
  16034. if (type2bl[unifiedLine.type] === unifiedLine) {
  16035. // Copy ICE related stuff from the principal media line.
  16036. unifiedLine.candidates = media[0].candidates;
  16037. unifiedLine.iceUfrag = media[0].iceUfrag;
  16038. unifiedLine.icePwd = media[0].icePwd;
  16039. unifiedLine.fingerprint = media[0].fingerprint;
  16040. // Plan B mids are in ['audio', 'video', 'data']
  16041. unifiedLine.mid = unifiedLine.type;
  16042. // Plan B doesn't support/need the bundle-only attribute.
  16043. delete unifiedLine.bundleOnly;
  16044. // In Plan B the msid is an SSRC attribute.
  16045. delete unifiedLine.msid;
  16046. // Used to build the group:BUNDLE value after this loop.
  16047. types.push(unifiedLine.type);
  16048. // Add the channel to the new media array.
  16049. session.media.push(unifiedLine);
  16050. }
  16051. });
  16052. // We regenerate the BUNDLE group with the new mids.
  16053. session.groups.some(function(group) {
  16054. if (group.type === 'BUNDLE') {
  16055. group.mids = types.join(' ');
  16056. return true;
  16057. }
  16058. });
  16059. // msid semantic
  16060. session.msidSemantic = {
  16061. semantic: 'WMS',
  16062. token: '*'
  16063. };
  16064. var resStr = transform.write(session);
  16065. return new RTCSessionDescription({
  16066. type: desc.type,
  16067. sdp: resStr
  16068. });
  16069. //#endregion
  16070. };
  16071. /**
  16072. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  16073. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  16074. * to FF.
  16075. *
  16076. * @param desc
  16077. * @returns {*}
  16078. */
  16079. Interop.prototype.toUnifiedPlan = function(desc) {
  16080. //#region Preliminary input validation.
  16081. if (typeof desc !== 'object' || desc === null ||
  16082. typeof desc.sdp !== 'string') {
  16083. console.warn('An empty description was passed as an argument.');
  16084. return desc;
  16085. }
  16086. var session = transform.parse(desc.sdp);
  16087. // If the SDP contains no media, there's nothing to transform.
  16088. if (typeof session.media === 'undefined' ||
  16089. !Array.isArray(session.media) || session.media.length === 0) {
  16090. console.warn('The description has no media.');
  16091. return desc;
  16092. }
  16093. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  16094. // a video, an audio and a data "channel" at most.
  16095. if (session.media.length > 3 || !session.media.every(function(m) {
  16096. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  16097. })) {
  16098. console.warn('This description does not look like Plan B.');
  16099. return desc;
  16100. }
  16101. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  16102. var mids = [];
  16103. session.media.forEach(function(m) {
  16104. mids.push(m.mid);
  16105. });
  16106. var hasBundle = false;
  16107. if (typeof session.groups !== 'undefined' &&
  16108. Array.isArray(session.groups)) {
  16109. hasBundle = session.groups.every(function(g) {
  16110. return g.type !== 'BUNDLE' ||
  16111. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  16112. });
  16113. }
  16114. if (!hasBundle) {
  16115. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  16116. " are not bundled were found.");
  16117. }
  16118. //#endregion
  16119. //#region Convert from Plan B to Unified Plan.
  16120. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  16121. // rebuild an equivalent Unified Plan offer/answer.
  16122. //
  16123. // For example, if this is a local answer (in Unified Plan style) that we
  16124. // convert to Plan B prior to handing it over to the application (the
  16125. // PeerConnection wrapper called us, for instance, after a successful
  16126. // createAnswer), we want to remember the m-line at which we've seen the
  16127. // (local) SSRC. That's because when the application wants to do call the
  16128. // SLD method, forcing us to do the inverse transformation (from Plan B to
  16129. // Unified Plan), we need to know to which m-line to assign the (local)
  16130. // SSRC. We also need to know all the other m-lines that the original
  16131. // answer had and include them in the transformed answer as well.
  16132. //
  16133. // Another example is if this is a remote offer that we convert to Plan B
  16134. // prior to giving it to the application, we want to remember the mid at
  16135. // which we've seen the (remote) SSRC.
  16136. //
  16137. // In the iteration that follows, we use the cached Unified Plan (if it
  16138. // exists) to assign mids to ssrcs.
  16139. var cached;
  16140. if (typeof this.cache[desc.type] !== 'undefined') {
  16141. cached = transform.parse(this.cache[desc.type]);
  16142. }
  16143. // A helper map that sends mids to m-line objects. We use it later to
  16144. // rebuild the Unified Plan style session.media array.
  16145. var mid2ul = {};
  16146. session.media.forEach(function(bLine) {
  16147. if ((typeof bLine.rtcpMux !== 'string' ||
  16148. bLine.rtcpMux !== 'rtcp-mux') &&
  16149. bLine.direction !== 'inactive') {
  16150. throw new Error("Cannot convert to Unified Plan because m-lines " +
  16151. "without the rtcp-mux attribute were found.");
  16152. }
  16153. if (bLine.type === 'application') {
  16154. mid2ul[bLine.mid] = bLine;
  16155. return;
  16156. }
  16157. // With rtcp-mux and bundle all the channels should have the same ICE
  16158. // stuff.
  16159. var sources = bLine.sources;
  16160. var ssrcGroups = bLine.ssrcGroups;
  16161. var candidates = bLine.candidates;
  16162. var iceUfrag = bLine.iceUfrag;
  16163. var icePwd = bLine.icePwd;
  16164. var fingerprint = bLine.fingerprint;
  16165. var port = bLine.port;
  16166. // We'll use the "bLine" object as a prototype for each new "mLine"
  16167. // that we create, but first we need to clean it up a bit.
  16168. delete bLine.sources;
  16169. delete bLine.ssrcGroups;
  16170. delete bLine.candidates;
  16171. delete bLine.iceUfrag;
  16172. delete bLine.icePwd;
  16173. delete bLine.fingerprint;
  16174. delete bLine.port;
  16175. delete bLine.mid;
  16176. // inverted ssrc group map
  16177. var ssrc2group = {};
  16178. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  16179. ssrcGroups.forEach(function (ssrcGroup) {
  16180. // TODO(gp) find out how to receive simulcast with FF. For the
  16181. // time being, hide it.
  16182. if (ssrcGroup.semantics === 'SIM') {
  16183. return;
  16184. }
  16185. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  16186. Array.isArray(ssrcGroup.ssrcs)) {
  16187. ssrcGroup.ssrcs.forEach(function (ssrc) {
  16188. if (typeof ssrc2group[ssrc] === 'undefined') {
  16189. ssrc2group[ssrc] = [];
  16190. }
  16191. ssrc2group[ssrc].push(ssrcGroup);
  16192. });
  16193. }
  16194. });
  16195. }
  16196. // ssrc to m-line index.
  16197. var ssrc2ml = {};
  16198. if (typeof sources === 'object') {
  16199. // Explode the Plan B channel sources with one m-line per source.
  16200. Object.keys(sources).forEach(function(ssrc) {
  16201. // The (unified) m-line for this SSRC. We either create it from
  16202. // scratch or, if it's a grouped SSRC, we re-use a related
  16203. // mline. In other words, if the source is grouped with another
  16204. // source, put the two together in the same m-line.
  16205. var unifiedLine;
  16206. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  16207. Array.isArray(ssrc2group[ssrc])) {
  16208. ssrc2group[ssrc].some(function (ssrcGroup) {
  16209. // ssrcGroup.ssrcs *is* an Array, no need to check
  16210. // again here.
  16211. return ssrcGroup.ssrcs.some(function (related) {
  16212. if (typeof ssrc2ml[related] === 'object') {
  16213. unifiedLine = ssrc2ml[related];
  16214. return true;
  16215. }
  16216. });
  16217. });
  16218. }
  16219. if (typeof unifiedLine === 'object') {
  16220. // the m-line already exists. Just add the source.
  16221. unifiedLine.sources[ssrc] = sources[ssrc];
  16222. delete sources[ssrc].msid;
  16223. } else {
  16224. // Use the "bLine" as a prototype for the "unifiedLine".
  16225. unifiedLine = Object.create(bLine);
  16226. ssrc2ml[ssrc] = unifiedLine;
  16227. if (typeof sources[ssrc].msid !== 'undefined') {
  16228. // Assign the msid of the source to the m-line. Note
  16229. // that it is not guaranteed that the source will have
  16230. // msid. In particular "recvonly" sources don't have an
  16231. // msid. Note that "recvonly" is a term only defined
  16232. // for m-lines.
  16233. unifiedLine.msid = sources[ssrc].msid;
  16234. delete sources[ssrc].msid;
  16235. }
  16236. // We assign one SSRC per media line.
  16237. unifiedLine.sources = {};
  16238. unifiedLine.sources[ssrc] = sources[ssrc];
  16239. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  16240. // Use the cached Unified Plan SDP (if it exists) to assign
  16241. // SSRCs to mids.
  16242. if (typeof cached !== 'undefined' &&
  16243. typeof cached.media !== 'undefined' &&
  16244. Array.isArray(cached.media)) {
  16245. cached.media.forEach(function (m) {
  16246. if (typeof m.sources === 'object') {
  16247. Object.keys(m.sources).forEach(function (s) {
  16248. if (s === ssrc) {
  16249. unifiedLine.mid = m.mid;
  16250. }
  16251. });
  16252. }
  16253. });
  16254. }
  16255. if (typeof unifiedLine.mid === 'undefined') {
  16256. // If this is an SSRC that we see for the first time
  16257. // assign it a new mid. This is typically the case when
  16258. // this method is called to transform a remote
  16259. // description for the first time or when there is a
  16260. // new SSRC in the remote description because a new
  16261. // peer has joined the conference. Local SSRCs should
  16262. // have already been added to the map in the toPlanB
  16263. // method.
  16264. //
  16265. // Because FF generates answers in Unified Plan style,
  16266. // we MUST already have a cached answer with all the
  16267. // local SSRCs mapped to some m-line/mid.
  16268. if (desc.type === 'answer') {
  16269. throw new Error("An unmapped SSRC was found.");
  16270. }
  16271. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  16272. }
  16273. // Include the candidates in the 1st media line.
  16274. unifiedLine.candidates = candidates;
  16275. unifiedLine.iceUfrag = iceUfrag;
  16276. unifiedLine.icePwd = icePwd;
  16277. unifiedLine.fingerprint = fingerprint;
  16278. unifiedLine.port = port;
  16279. mid2ul[unifiedLine.mid] = unifiedLine;
  16280. }
  16281. });
  16282. }
  16283. });
  16284. // Rebuild the media array in the right order and add the missing mLines
  16285. // (missing from the Plan B SDP).
  16286. session.media = [];
  16287. mids = []; // reuse
  16288. if (desc.type === 'answer') {
  16289. // The media lines in the answer must match the media lines in the
  16290. // offer. The order is important too. Here we assume that Firefox is the
  16291. // answerer, so we merely have to use the reconstructed (unified) answer
  16292. // to update the cached (unified) answer accordingly.
  16293. //
  16294. // In the general case, one would have to use the cached (unified) offer
  16295. // to find the m-lines that are missing from the reconstructed answer,
  16296. // potentially grabbing them from the cached (unified) answer. One has
  16297. // to be carefull with this approach because inactive m-lines do not
  16298. // always have an mid, making it tricky (impossible?) to find where
  16299. // exactly and which m-lines are missing from the reconstructed answer.
  16300. for (var i = 0; i < cached.media.length; i++) {
  16301. var unifiedLine = cached.media[i];
  16302. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  16303. // The mid isn't in the reconstructed (unified) answer.
  16304. // This is either a (unified) m-line containing a remote
  16305. // track only, or a (unified) m-line containing a remote
  16306. // track and a local track that has been removed.
  16307. // In either case, it MUST exist in the cached
  16308. // (unified) answer.
  16309. //
  16310. // In case this is a removed local track, clean-up
  16311. // the (unified) m-line and make sure it's 'recvonly' or
  16312. // 'inactive'.
  16313. delete unifiedLine.msid;
  16314. delete unifiedLine.sources;
  16315. delete unifiedLine.ssrcGroups;
  16316. if (!unifiedLine.direction
  16317. || unifiedLine.direction === 'sendrecv')
  16318. unifiedLine.direction = 'recvonly';
  16319. if (!unifiedLine.direction
  16320. || unifiedLine.direction === 'sendonly')
  16321. unifiedLine.direction = 'inactive';
  16322. } else {
  16323. // This is an (unified) m-line/channel that contains a local
  16324. // track (sendrecv or sendonly channel) or it's a unified
  16325. // recvonly m-line/channel. In either case, since we're
  16326. // going from PlanB -> Unified Plan this m-line MUST
  16327. // exist in the cached answer.
  16328. }
  16329. session.media.push(unifiedLine);
  16330. if (typeof unifiedLine.mid === 'string') {
  16331. // inactive lines don't/may not have an mid.
  16332. mids.push(unifiedLine.mid);
  16333. }
  16334. }
  16335. } else {
  16336. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  16337. // under any circumstances. If we are no longer interested in sending a
  16338. // track, we just remove the msid and ssrc attributes and set it to
  16339. // either a=recvonly (as the reofferer, we must use recvonly if the
  16340. // other side was previously sending on the m-section, but we can also
  16341. // leave the possibility open if it wasn't previously in use), or
  16342. // a=inacive.
  16343. if (typeof cached !== 'undefined' &&
  16344. typeof cached.media !== 'undefined' &&
  16345. Array.isArray(cached.media)) {
  16346. cached.media.forEach(function(unifiedLine) {
  16347. mids.push(unifiedLine.mid);
  16348. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  16349. session.media.push(mid2ul[unifiedLine.mid]);
  16350. } else {
  16351. delete unifiedLine.msid;
  16352. delete unifiedLine.sources;
  16353. delete unifiedLine.ssrcGroups;
  16354. if (!unifiedLine.direction
  16355. || unifiedLine.direction === 'sendrecv')
  16356. unifiedLine.direction = 'recvonly';
  16357. if (!unifiedLine.direction
  16358. || unifiedLine.direction === 'sendonly')
  16359. unifiedLine.direction = 'inactive';
  16360. session.media.push(unifiedLine);
  16361. }
  16362. });
  16363. }
  16364. // Add all the remaining (new) m-lines of the transformed SDP.
  16365. Object.keys(mid2ul).forEach(function(mid) {
  16366. if (mids.indexOf(mid) === -1) {
  16367. mids.push(mid);
  16368. if (typeof mid2ul[mid].direction === 'recvonly') {
  16369. // This is a remote recvonly channel. Add its SSRC to the
  16370. // appropriate sendrecv or sendonly channel.
  16371. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  16372. session.media.some(function (unifiedLine) {
  16373. if ((unifiedLine.direction === 'sendrecv' ||
  16374. unifiedLine.direction === 'sendonly') &&
  16375. unifiedLine.type === mid2ul[mid].type) {
  16376. // mid2ul[mid] shouldn't have any ssrc-groups
  16377. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  16378. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  16379. });
  16380. return true;
  16381. }
  16382. });
  16383. } else {
  16384. session.media.push(mid2ul[mid]);
  16385. }
  16386. }
  16387. });
  16388. }
  16389. // We regenerate the BUNDLE group (since we regenerated the mids)
  16390. session.groups.some(function(group) {
  16391. if (group.type === 'BUNDLE') {
  16392. group.mids = mids.join(' ');
  16393. return true;
  16394. }
  16395. });
  16396. // msid semantic
  16397. session.msidSemantic = {
  16398. semantic: 'WMS',
  16399. token: '*'
  16400. };
  16401. var resStr = transform.write(session);
  16402. // Cache the transformed SDP (Unified Plan) for later re-use in this
  16403. // function.
  16404. this.cache[desc.type] = resStr;
  16405. return new RTCSessionDescription({
  16406. type: desc.type,
  16407. sdp: resStr
  16408. });
  16409. //#endregion
  16410. };
  16411. },{"./array-equals":52,"./transform":55}],55:[function(require,module,exports){
  16412. var transform = require('sdp-transform');
  16413. exports.write = function(session, opts) {
  16414. if (typeof session !== 'undefined' &&
  16415. typeof session.media !== 'undefined' &&
  16416. Array.isArray(session.media)) {
  16417. session.media.forEach(function (mLine) {
  16418. // expand sources to ssrcs
  16419. if (typeof mLine.sources !== 'undefined' &&
  16420. Object.keys(mLine.sources).length !== 0) {
  16421. mLine.ssrcs = [];
  16422. Object.keys(mLine.sources).forEach(function (ssrc) {
  16423. var source = mLine.sources[ssrc];
  16424. Object.keys(source).forEach(function (attribute) {
  16425. mLine.ssrcs.push({
  16426. id: ssrc,
  16427. attribute: attribute,
  16428. value: source[attribute]
  16429. });
  16430. });
  16431. });
  16432. delete mLine.sources;
  16433. }
  16434. // join ssrcs in ssrc groups
  16435. if (typeof mLine.ssrcGroups !== 'undefined' &&
  16436. Array.isArray(mLine.ssrcGroups)) {
  16437. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  16438. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  16439. Array.isArray(ssrcGroup.ssrcs)) {
  16440. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  16441. }
  16442. });
  16443. }
  16444. });
  16445. }
  16446. // join group mids
  16447. if (typeof session !== 'undefined' &&
  16448. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  16449. session.groups.forEach(function (g) {
  16450. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  16451. g.mids = g.mids.join(' ');
  16452. }
  16453. });
  16454. }
  16455. return transform.write(session, opts);
  16456. };
  16457. exports.parse = function(sdp) {
  16458. var session = transform.parse(sdp);
  16459. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  16460. Array.isArray(session.media)) {
  16461. session.media.forEach(function (mLine) {
  16462. // group sources attributes by ssrc
  16463. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  16464. mLine.sources = {};
  16465. mLine.ssrcs.forEach(function (ssrc) {
  16466. if (!mLine.sources[ssrc.id])
  16467. mLine.sources[ssrc.id] = {};
  16468. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  16469. });
  16470. delete mLine.ssrcs;
  16471. }
  16472. // split ssrcs in ssrc groups
  16473. if (typeof mLine.ssrcGroups !== 'undefined' &&
  16474. Array.isArray(mLine.ssrcGroups)) {
  16475. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  16476. if (typeof ssrcGroup.ssrcs === 'string') {
  16477. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  16478. }
  16479. });
  16480. }
  16481. });
  16482. }
  16483. // split group mids
  16484. if (typeof session !== 'undefined' &&
  16485. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  16486. session.groups.forEach(function (g) {
  16487. if (typeof g.mids === 'string') {
  16488. g.mids = g.mids.split(' ');
  16489. }
  16490. });
  16491. }
  16492. return session;
  16493. };
  16494. },{"sdp-transform":57}],56:[function(require,module,exports){
  16495. var grammar = module.exports = {
  16496. v: [{
  16497. name: 'version',
  16498. reg: /^(\d*)$/
  16499. }],
  16500. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  16501. // NB: sessionId will be a String in most cases because it is huge
  16502. name: 'origin',
  16503. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  16504. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  16505. format: "%s %s %d %s IP%d %s"
  16506. }],
  16507. // default parsing of these only (though some of these feel outdated)
  16508. s: [{ name: 'name' }],
  16509. i: [{ name: 'description' }],
  16510. u: [{ name: 'uri' }],
  16511. e: [{ name: 'email' }],
  16512. p: [{ name: 'phone' }],
  16513. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  16514. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  16515. //k: [{}], // outdated thing ignored
  16516. t: [{ //t=0 0
  16517. name: 'timing',
  16518. reg: /^(\d*) (\d*)/,
  16519. names: ['start', 'stop'],
  16520. format: "%d %d"
  16521. }],
  16522. c: [{ //c=IN IP4 10.47.197.26
  16523. name: 'connection',
  16524. reg: /^IN IP(\d) (\S*)/,
  16525. names: ['version', 'ip'],
  16526. format: "IN IP%d %s"
  16527. }],
  16528. b: [{ //b=AS:4000
  16529. push: 'bandwidth',
  16530. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  16531. names: ['type', 'limit'],
  16532. format: "%s:%s"
  16533. }],
  16534. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  16535. // NB: special - pushes to session
  16536. // TODO: rtp/fmtp should be filtered by the payloads found here?
  16537. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  16538. names: ['type', 'port', 'protocol', 'payloads'],
  16539. format: "%s %d %s %s"
  16540. }],
  16541. a: [
  16542. { //a=rtpmap:110 opus/48000/2
  16543. push: 'rtp',
  16544. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  16545. names: ['payload', 'codec', 'rate', 'encoding'],
  16546. format: function (o) {
  16547. return (o.encoding) ?
  16548. "rtpmap:%d %s/%s/%s":
  16549. "rtpmap:%d %s/%s";
  16550. }
  16551. },
  16552. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  16553. push: 'fmtp',
  16554. reg: /^fmtp:(\d*) (\S*)/,
  16555. names: ['payload', 'config'],
  16556. format: "fmtp:%d %s"
  16557. },
  16558. { //a=control:streamid=0
  16559. name: 'control',
  16560. reg: /^control:(.*)/,
  16561. format: "control:%s"
  16562. },
  16563. { //a=rtcp:65179 IN IP4 193.84.77.194
  16564. name: 'rtcp',
  16565. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  16566. names: ['port', 'netType', 'ipVer', 'address'],
  16567. format: function (o) {
  16568. return (o.address != null) ?
  16569. "rtcp:%d %s IP%d %s":
  16570. "rtcp:%d";
  16571. }
  16572. },
  16573. { //a=rtcp-fb:98 trr-int 100
  16574. push: 'rtcpFbTrrInt',
  16575. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  16576. names: ['payload', 'value'],
  16577. format: "rtcp-fb:%d trr-int %d"
  16578. },
  16579. { //a=rtcp-fb:98 nack rpsi
  16580. push: 'rtcpFb',
  16581. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  16582. names: ['payload', 'type', 'subtype'],
  16583. format: function (o) {
  16584. return (o.subtype != null) ?
  16585. "rtcp-fb:%s %s %s":
  16586. "rtcp-fb:%s %s";
  16587. }
  16588. },
  16589. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  16590. //a=extmap:1/recvonly URI-gps-string
  16591. push: 'ext',
  16592. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  16593. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  16594. format: function (o) {
  16595. return (o.config != null) ?
  16596. "extmap:%s %s %s":
  16597. "extmap:%s %s";
  16598. }
  16599. },
  16600. {
  16601. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  16602. push: 'crypto',
  16603. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  16604. names: ['id', 'suite', 'config', 'sessionConfig'],
  16605. format: function (o) {
  16606. return (o.sessionConfig != null) ?
  16607. "crypto:%d %s %s %s":
  16608. "crypto:%d %s %s";
  16609. }
  16610. },
  16611. { //a=setup:actpass
  16612. name: 'setup',
  16613. reg: /^setup:(\w*)/,
  16614. format: "setup:%s"
  16615. },
  16616. { //a=mid:1
  16617. name: 'mid',
  16618. reg: /^mid:([^\s]*)/,
  16619. format: "mid:%s"
  16620. },
  16621. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  16622. name: 'msid',
  16623. reg: /^msid:(.*)/,
  16624. format: "msid:%s"
  16625. },
  16626. { //a=ptime:20
  16627. name: 'ptime',
  16628. reg: /^ptime:(\d*)/,
  16629. format: "ptime:%d"
  16630. },
  16631. { //a=maxptime:60
  16632. name: 'maxptime',
  16633. reg: /^maxptime:(\d*)/,
  16634. format: "maxptime:%d"
  16635. },
  16636. { //a=sendrecv
  16637. name: 'direction',
  16638. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  16639. },
  16640. { //a=ice-lite
  16641. name: 'icelite',
  16642. reg: /^(ice-lite)/
  16643. },
  16644. { //a=ice-ufrag:F7gI
  16645. name: 'iceUfrag',
  16646. reg: /^ice-ufrag:(\S*)/,
  16647. format: "ice-ufrag:%s"
  16648. },
  16649. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  16650. name: 'icePwd',
  16651. reg: /^ice-pwd:(\S*)/,
  16652. format: "ice-pwd:%s"
  16653. },
  16654. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  16655. name: 'fingerprint',
  16656. reg: /^fingerprint:(\S*) (\S*)/,
  16657. names: ['type', 'hash'],
  16658. format: "fingerprint:%s %s"
  16659. },
  16660. {
  16661. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  16662. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  16663. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  16664. push:'candidates',
  16665. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  16666. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  16667. format: function (o) {
  16668. var str = "candidate:%s %d %s %d %s %d typ %s";
  16669. // NB: candidate has two optional chunks, so %void middle one if it's missing
  16670. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  16671. if (o.generation != null) {
  16672. str += " generation %d";
  16673. }
  16674. return str;
  16675. }
  16676. },
  16677. { //a=end-of-candidates (keep after the candidates line for readability)
  16678. name: 'endOfCandidates',
  16679. reg: /^(end-of-candidates)/
  16680. },
  16681. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  16682. name: 'remoteCandidates',
  16683. reg: /^remote-candidates:(.*)/,
  16684. format: "remote-candidates:%s"
  16685. },
  16686. { //a=ice-options:google-ice
  16687. name: 'iceOptions',
  16688. reg: /^ice-options:(\S*)/,
  16689. format: "ice-options:%s"
  16690. },
  16691. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  16692. push: "ssrcs",
  16693. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  16694. names: ['id', 'attribute', 'value'],
  16695. format: "ssrc:%d %s:%s"
  16696. },
  16697. { //a=ssrc-group:FEC 1 2
  16698. push: "ssrcGroups",
  16699. reg: /^ssrc-group:(\w*) (.*)/,
  16700. names: ['semantics', 'ssrcs'],
  16701. format: "ssrc-group:%s %s"
  16702. },
  16703. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  16704. name: "msidSemantic",
  16705. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  16706. names: ['semantic', 'token'],
  16707. format: "msid-semantic: %s %s" // space after ":" is not accidental
  16708. },
  16709. { //a=group:BUNDLE audio video
  16710. push: 'groups',
  16711. reg: /^group:(\w*) (.*)/,
  16712. names: ['type', 'mids'],
  16713. format: "group:%s %s"
  16714. },
  16715. { //a=rtcp-mux
  16716. name: 'rtcpMux',
  16717. reg: /^(rtcp-mux)/
  16718. },
  16719. { //a=rtcp-rsize
  16720. name: 'rtcpRsize',
  16721. reg: /^(rtcp-rsize)/
  16722. },
  16723. { // any a= that we don't understand is kepts verbatim on media.invalid
  16724. push: 'invalid',
  16725. names: ["value"]
  16726. }
  16727. ]
  16728. };
  16729. // set sensible defaults to avoid polluting the grammar with boring details
  16730. Object.keys(grammar).forEach(function (key) {
  16731. var objs = grammar[key];
  16732. objs.forEach(function (obj) {
  16733. if (!obj.reg) {
  16734. obj.reg = /(.*)/;
  16735. }
  16736. if (!obj.format) {
  16737. obj.format = "%s";
  16738. }
  16739. });
  16740. });
  16741. },{}],57:[function(require,module,exports){
  16742. var parser = require('./parser');
  16743. var writer = require('./writer');
  16744. exports.write = writer;
  16745. exports.parse = parser.parse;
  16746. exports.parseFmtpConfig = parser.parseFmtpConfig;
  16747. exports.parsePayloads = parser.parsePayloads;
  16748. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  16749. },{"./parser":58,"./writer":59}],58:[function(require,module,exports){
  16750. var toIntIfInt = function (v) {
  16751. return String(Number(v)) === v ? Number(v) : v;
  16752. };
  16753. var attachProperties = function (match, location, names, rawName) {
  16754. if (rawName && !names) {
  16755. location[rawName] = toIntIfInt(match[1]);
  16756. }
  16757. else {
  16758. for (var i = 0; i < names.length; i += 1) {
  16759. if (match[i+1] != null) {
  16760. location[names[i]] = toIntIfInt(match[i+1]);
  16761. }
  16762. }
  16763. }
  16764. };
  16765. var parseReg = function (obj, location, content) {
  16766. var needsBlank = obj.name && obj.names;
  16767. if (obj.push && !location[obj.push]) {
  16768. location[obj.push] = [];
  16769. }
  16770. else if (needsBlank && !location[obj.name]) {
  16771. location[obj.name] = {};
  16772. }
  16773. var keyLocation = obj.push ?
  16774. {} : // blank object that will be pushed
  16775. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  16776. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  16777. if (obj.push) {
  16778. location[obj.push].push(keyLocation);
  16779. }
  16780. };
  16781. var grammar = require('./grammar');
  16782. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  16783. exports.parse = function (sdp) {
  16784. var session = {}
  16785. , media = []
  16786. , location = session; // points at where properties go under (one of the above)
  16787. // parse lines we understand
  16788. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  16789. var type = l[0];
  16790. var content = l.slice(2);
  16791. if (type === 'm') {
  16792. media.push({rtp: [], fmtp: []});
  16793. location = media[media.length-1]; // point at latest media line
  16794. }
  16795. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  16796. var obj = grammar[type][j];
  16797. if (obj.reg.test(content)) {
  16798. return parseReg(obj, location, content);
  16799. }
  16800. }
  16801. });
  16802. session.media = media; // link it up
  16803. return session;
  16804. };
  16805. var fmtpReducer = function (acc, expr) {
  16806. var s = expr.split('=');
  16807. if (s.length === 2) {
  16808. acc[s[0]] = toIntIfInt(s[1]);
  16809. }
  16810. return acc;
  16811. };
  16812. exports.parseFmtpConfig = function (str) {
  16813. return str.split(';').reduce(fmtpReducer, {});
  16814. };
  16815. exports.parsePayloads = function (str) {
  16816. return str.split(' ').map(Number);
  16817. };
  16818. exports.parseRemoteCandidates = function (str) {
  16819. var candidates = [];
  16820. var parts = str.split(' ').map(toIntIfInt);
  16821. for (var i = 0; i < parts.length; i += 3) {
  16822. candidates.push({
  16823. component: parts[i],
  16824. ip: parts[i + 1],
  16825. port: parts[i + 2]
  16826. });
  16827. }
  16828. return candidates;
  16829. };
  16830. },{"./grammar":56}],59:[function(require,module,exports){
  16831. var grammar = require('./grammar');
  16832. // customized util.format - discards excess arguments and can void middle ones
  16833. var formatRegExp = /%[sdv%]/g;
  16834. var format = function (formatStr) {
  16835. var i = 1;
  16836. var args = arguments;
  16837. var len = args.length;
  16838. return formatStr.replace(formatRegExp, function (x) {
  16839. if (i >= len) {
  16840. return x; // missing argument
  16841. }
  16842. var arg = args[i];
  16843. i += 1;
  16844. switch (x) {
  16845. case '%%':
  16846. return '%';
  16847. case '%s':
  16848. return String(arg);
  16849. case '%d':
  16850. return Number(arg);
  16851. case '%v':
  16852. return '';
  16853. }
  16854. });
  16855. // NB: we discard excess arguments - they are typically undefined from makeLine
  16856. };
  16857. var makeLine = function (type, obj, location) {
  16858. var str = obj.format instanceof Function ?
  16859. (obj.format(obj.push ? location : location[obj.name])) :
  16860. obj.format;
  16861. var args = [type + '=' + str];
  16862. if (obj.names) {
  16863. for (var i = 0; i < obj.names.length; i += 1) {
  16864. var n = obj.names[i];
  16865. if (obj.name) {
  16866. args.push(location[obj.name][n]);
  16867. }
  16868. else { // for mLine and push attributes
  16869. args.push(location[obj.names[i]]);
  16870. }
  16871. }
  16872. }
  16873. else {
  16874. args.push(location[obj.name]);
  16875. }
  16876. return format.apply(null, args);
  16877. };
  16878. // RFC specified order
  16879. // TODO: extend this with all the rest
  16880. var defaultOuterOrder = [
  16881. 'v', 'o', 's', 'i',
  16882. 'u', 'e', 'p', 'c',
  16883. 'b', 't', 'r', 'z', 'a'
  16884. ];
  16885. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  16886. module.exports = function (session, opts) {
  16887. opts = opts || {};
  16888. // ensure certain properties exist
  16889. if (session.version == null) {
  16890. session.version = 0; // "v=0" must be there (only defined version atm)
  16891. }
  16892. if (session.name == null) {
  16893. session.name = " "; // "s= " must be there if no meaningful name set
  16894. }
  16895. session.media.forEach(function (mLine) {
  16896. if (mLine.payloads == null) {
  16897. mLine.payloads = "";
  16898. }
  16899. });
  16900. var outerOrder = opts.outerOrder || defaultOuterOrder;
  16901. var innerOrder = opts.innerOrder || defaultInnerOrder;
  16902. var sdp = [];
  16903. // loop through outerOrder for matching properties on session
  16904. outerOrder.forEach(function (type) {
  16905. grammar[type].forEach(function (obj) {
  16906. if (obj.name in session && session[obj.name] != null) {
  16907. sdp.push(makeLine(type, obj, session));
  16908. }
  16909. else if (obj.push in session && session[obj.push] != null) {
  16910. session[obj.push].forEach(function (el) {
  16911. sdp.push(makeLine(type, obj, el));
  16912. });
  16913. }
  16914. });
  16915. });
  16916. // then for each media line, follow the innerOrder
  16917. session.media.forEach(function (mLine) {
  16918. sdp.push(makeLine('m', grammar.m[0], mLine));
  16919. innerOrder.forEach(function (type) {
  16920. grammar[type].forEach(function (obj) {
  16921. if (obj.name in mLine && mLine[obj.name] != null) {
  16922. sdp.push(makeLine(type, obj, mLine));
  16923. }
  16924. else if (obj.push in mLine && mLine[obj.push] != null) {
  16925. mLine[obj.push].forEach(function (el) {
  16926. sdp.push(makeLine(type, obj, el));
  16927. });
  16928. }
  16929. });
  16930. });
  16931. });
  16932. return sdp.join('\r\n') + '\r\n';
  16933. };
  16934. },{"./grammar":56}],60:[function(require,module,exports){
  16935. var transform = require('sdp-transform');
  16936. var transformUtils = require('./transform-utils');
  16937. var parseSsrcs = transformUtils.parseSsrcs;
  16938. var writeSsrcs = transformUtils.writeSsrcs;
  16939. //region Constants
  16940. var DEFAULT_NUM_OF_LAYERS = 3;
  16941. //endregion
  16942. //region Ctor
  16943. function Simulcast(options) {
  16944. this.options = options ? options : {};
  16945. if (!this.options.numOfLayers) {
  16946. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  16947. }
  16948. this.layers = [];
  16949. }
  16950. //endregion
  16951. //region Stateless private utility functions
  16952. /**
  16953. * Returns a random integer between min (included) and max (excluded)
  16954. * Using Math.round() gives a non-uniform distribution!
  16955. * @returns {number}
  16956. */
  16957. function generateSSRC() {
  16958. var min = 0, max = 0xffffffff;
  16959. return Math.floor(Math.random() * (max - min)) + min;
  16960. };
  16961. function processVideo(session, action) {
  16962. if (session == null || !Array.isArray(session.media)) {
  16963. return;
  16964. }
  16965. session.media.forEach(function (mLine) {
  16966. if (mLine.type === 'video') {
  16967. action(mLine);
  16968. }
  16969. });
  16970. }
  16971. function validateDescription(desc)
  16972. {
  16973. return desc && desc != null
  16974. && desc.type && desc.type != ''
  16975. && desc.sdp && desc.sdp != '';
  16976. }
  16977. function explodeRemoteSimulcast(mLine) {
  16978. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  16979. return;
  16980. }
  16981. var sources = parseSsrcs(mLine);
  16982. var order = [];
  16983. // Find the SIM group and explode its sources.
  16984. var j = mLine.ssrcGroups.length;
  16985. while (j--) {
  16986. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  16987. continue;
  16988. }
  16989. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  16990. for (var i = 0; i < simulcastSsrcs.length; i++) {
  16991. var ssrc = simulcastSsrcs[i];
  16992. order.push(ssrc);
  16993. var parts = sources[ssrc].msid.split(' ');
  16994. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  16995. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  16996. // Remove all the groups that this SSRC participates in.
  16997. mLine.ssrcGroups.forEach(function (relatedGroup) {
  16998. if (relatedGroup.semantics === 'SIM') {
  16999. return;
  17000. }
  17001. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  17002. if (relatedSsrcs.indexOf(ssrc) === -1) {
  17003. return;
  17004. }
  17005. // Nuke all the related SSRCs.
  17006. relatedSsrcs.forEach(function (relatedSSRC) {
  17007. sources[relatedSSRC].msid = sources[ssrc].msid;
  17008. sources[relatedSSRC].cname = sources[ssrc].cname;
  17009. if (relatedSSRC !== ssrc) {
  17010. order.push(relatedSSRC);
  17011. }
  17012. });
  17013. // Schedule the related group for nuking.
  17014. })
  17015. }
  17016. mLine.ssrcs = writeSsrcs(sources, order);
  17017. mLine.ssrcGroups.splice(j, 1);
  17018. };
  17019. }
  17020. function squeezeRemoteSimulcast(mLine) {
  17021. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  17022. return;
  17023. }
  17024. var sources = parseSsrcs(mLine);
  17025. // Find the SIM group and nuke it.
  17026. mLine.ssrcGroups.some(function (simulcastGroup) {
  17027. if (simulcastGroup.semantics !== 'SIM') {
  17028. return false;
  17029. }
  17030. // Schedule the SIM group for nuking.
  17031. simulcastGroup.nuke = true;
  17032. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  17033. // Nuke all the higher layer SSRCs.
  17034. for (var i = 1; i < simulcastSsrcs.length; i++) {
  17035. var ssrc = simulcastSsrcs[i];
  17036. delete sources[ssrc];
  17037. // Remove all the groups that this SSRC participates in.
  17038. mLine.ssrcGroups.forEach(function (relatedGroup) {
  17039. if (relatedGroup.semantics === 'SIM') {
  17040. return;
  17041. }
  17042. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  17043. if (relatedSsrcs.indexOf(ssrc) === -1) {
  17044. return;
  17045. }
  17046. // Nuke all the related SSRCs.
  17047. relatedSsrcs.forEach(function (relatedSSRC) {
  17048. delete sources[relatedSSRC];
  17049. });
  17050. // Schedule the related group for nuking.
  17051. relatedGroup.nuke = true;
  17052. })
  17053. }
  17054. return true;
  17055. });
  17056. mLine.ssrcs = writeSsrcs(sources);
  17057. // Nuke all the scheduled groups.
  17058. var i = mLine.ssrcGroups.length;
  17059. while (i--) {
  17060. if (mLine.ssrcGroups[i].nuke) {
  17061. mLine.ssrcGroups.splice(i, 1);
  17062. }
  17063. }
  17064. }
  17065. function removeGoogConference(mLine) {
  17066. if (!mLine || !Array.isArray(mLine.invalid)) {
  17067. return;
  17068. }
  17069. var i = mLine.invalid.length;
  17070. while (i--) {
  17071. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  17072. mLine.invalid.splice(i, 1);
  17073. }
  17074. }
  17075. }
  17076. function assertGoogConference(mLine) {
  17077. if (!mLine) {
  17078. return;
  17079. }
  17080. if (!Array.isArray(mLine.invalid)) {
  17081. mLine.invalid = [];
  17082. }
  17083. if (!mLine.invalid.some(
  17084. function (i) { return i.value === 'x-google-flag:conference' })) {
  17085. mLine.invalid.push({'value': 'x-google-flag:conference'});
  17086. }
  17087. }
  17088. //endregion
  17089. //region "Private" functions
  17090. /**
  17091. *
  17092. * @param mLine
  17093. * @private
  17094. */
  17095. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  17096. if (!mLine || mLine.type !== 'video') {
  17097. return;
  17098. }
  17099. var sources = parseSsrcs(mLine);
  17100. if (Object.keys(sources).length === 0) {
  17101. // no sources, disable simulcast.
  17102. if (this.layers.length !== 0) {
  17103. this.layers = [];
  17104. }
  17105. return;
  17106. }
  17107. // find the base layer (we'll reuse its msid and cname).
  17108. var baseLayerSSRC = Object.keys(sources)[0];
  17109. var baseLayer = sources[baseLayerSSRC];
  17110. // todo(gp) handle screen sharing.
  17111. // check if base CNAME has changed and reinitialise layers.
  17112. if (this.layers.length > 0
  17113. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  17114. this.layers = [];
  17115. }
  17116. // (re)initialise layers
  17117. if (this.layers.length < 1) {
  17118. // first push the base layer.
  17119. this.layers.push({
  17120. ssrc: baseLayerSSRC,
  17121. msid: baseLayer.msid,
  17122. cname: baseLayer.cname
  17123. });
  17124. var rtx = false; // RFC 4588
  17125. if (Array.isArray(mLine.rtp)) {
  17126. rtx = mLine.rtp.some(
  17127. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  17128. }
  17129. if (rtx) {
  17130. this.layers[0].rtx = generateSSRC();
  17131. }
  17132. // now push additional layers.
  17133. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  17134. var layer = { ssrc: generateSSRC() };
  17135. if (rtx) {
  17136. layer.rtx = generateSSRC();
  17137. }
  17138. this.layers.push(layer);
  17139. }
  17140. }
  17141. };
  17142. /**
  17143. *
  17144. * @param mLine
  17145. * @private
  17146. */
  17147. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  17148. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  17149. var sources = {};
  17150. var msid = this.layers[0].msid;
  17151. var cname = this.layers[0].cname;
  17152. var simulcastSsrcs = [];
  17153. var ssrcGroups = [];
  17154. for (var i = 0; i < this.layers.length; i++) {
  17155. var layer = this.layers[i];
  17156. sources[layer.ssrc] = { msid: msid, cname: cname };
  17157. simulcastSsrcs.push(layer.ssrc);
  17158. if (layer.rtx) {
  17159. sources[layer.rtx] = {
  17160. msid: msid,
  17161. cname: cname
  17162. }
  17163. ssrcGroups.push({
  17164. semantics: 'FID',
  17165. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  17166. });
  17167. }
  17168. }
  17169. ssrcGroups.push({
  17170. semantics: 'SIM',
  17171. ssrcs: simulcastSsrcs.join(' ')
  17172. });
  17173. mLine.ssrcGroups = ssrcGroups;
  17174. mLine.ssrcs = writeSsrcs(sources);
  17175. }
  17176. }
  17177. //endregion
  17178. //region "Public" functions
  17179. Simulcast.prototype.isSupported = function () {
  17180. return window.chrome;
  17181. // TODO this needs improvements. For example I doubt that Chrome in Android
  17182. // has simulcast support. Also, only recent versions of Chromium have native
  17183. // simulcast support.
  17184. }
  17185. /**
  17186. *
  17187. * @param desc
  17188. * @returns {RTCSessionDescription}
  17189. */
  17190. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  17191. if (!validateDescription(desc)) {
  17192. return desc;
  17193. }
  17194. var session = transform.parse(desc.sdp);
  17195. var self = this;
  17196. processVideo(session, function (mLine) {
  17197. // Handle simulcast reception.
  17198. if (self.options.explodeRemoteSimulcast) {
  17199. explodeRemoteSimulcast(mLine);
  17200. } else {
  17201. squeezeRemoteSimulcast(mLine);
  17202. }
  17203. // If native simulcast is enabled, we must append the x-goog-conference
  17204. // attribute to the SDP.
  17205. if (self.layers.length < 1) {
  17206. removeGoogConference(mLine);
  17207. } else {
  17208. assertGoogConference(mLine);
  17209. }
  17210. });
  17211. return new RTCSessionDescription({
  17212. type: desc.type,
  17213. sdp: transform.write(session)
  17214. });
  17215. };
  17216. /**
  17217. *
  17218. * @param desc
  17219. * @returns {RTCSessionDescription}
  17220. */
  17221. Simulcast.prototype.mungeLocalDescription = function (desc) {
  17222. if (!validateDescription(desc) || !this.isSupported()) {
  17223. return desc;
  17224. }
  17225. var session = transform.parse(desc.sdp);
  17226. var self = this;
  17227. processVideo(session, function (mLine) {
  17228. // Initialize native simulcast layers, if not already done.
  17229. self._maybeInitializeLayers(mLine);
  17230. // Update the SDP with the simulcast layers.
  17231. self._restoreSimulcastView(mLine);
  17232. });
  17233. return new RTCSessionDescription({
  17234. type: desc.type,
  17235. sdp: transform.write(session)
  17236. });
  17237. };
  17238. //endregion
  17239. module.exports = Simulcast;
  17240. },{"./transform-utils":61,"sdp-transform":63}],61:[function(require,module,exports){
  17241. exports.writeSsrcs = function(sources, order) {
  17242. var ssrcs = [];
  17243. // expand sources to ssrcs
  17244. if (typeof sources !== 'undefined' &&
  17245. Object.keys(sources).length !== 0) {
  17246. if (Array.isArray(order)) {
  17247. for (var i = 0; i < order.length; i++) {
  17248. var ssrc = order[i];
  17249. var source = sources[ssrc];
  17250. Object.keys(source).forEach(function (attribute) {
  17251. ssrcs.push({
  17252. id: ssrc,
  17253. attribute: attribute,
  17254. value: source[attribute]
  17255. });
  17256. });
  17257. }
  17258. } else {
  17259. Object.keys(sources).forEach(function (ssrc) {
  17260. var source = sources[ssrc];
  17261. Object.keys(source).forEach(function (attribute) {
  17262. ssrcs.push({
  17263. id: ssrc,
  17264. attribute: attribute,
  17265. value: source[attribute]
  17266. });
  17267. });
  17268. });
  17269. }
  17270. }
  17271. return ssrcs;
  17272. };
  17273. exports.parseSsrcs = function (mLine) {
  17274. var sources = {};
  17275. // group sources attributes by ssrc.
  17276. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  17277. mLine.ssrcs.forEach(function (ssrc) {
  17278. if (!sources[ssrc.id])
  17279. sources[ssrc.id] = {};
  17280. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  17281. });
  17282. }
  17283. return sources;
  17284. };
  17285. },{}],62:[function(require,module,exports){
  17286. arguments[4][56][0].apply(exports,arguments)
  17287. },{"dup":56}],63:[function(require,module,exports){
  17288. arguments[4][57][0].apply(exports,arguments)
  17289. },{"./parser":64,"./writer":65,"dup":57}],64:[function(require,module,exports){
  17290. arguments[4][58][0].apply(exports,arguments)
  17291. },{"./grammar":62,"dup":58}],65:[function(require,module,exports){
  17292. arguments[4][59][0].apply(exports,arguments)
  17293. },{"./grammar":62,"dup":59}],66:[function(require,module,exports){
  17294. var grammar = module.exports = {
  17295. v: [{
  17296. name: 'version',
  17297. reg: /^(\d*)$/
  17298. }],
  17299. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  17300. // NB: sessionId will be a String in most cases because it is huge
  17301. name: 'origin',
  17302. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  17303. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  17304. format: "%s %s %d %s IP%d %s"
  17305. }],
  17306. // default parsing of these only (though some of these feel outdated)
  17307. s: [{ name: 'name' }],
  17308. i: [{ name: 'description' }],
  17309. u: [{ name: 'uri' }],
  17310. e: [{ name: 'email' }],
  17311. p: [{ name: 'phone' }],
  17312. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  17313. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  17314. //k: [{}], // outdated thing ignored
  17315. t: [{ //t=0 0
  17316. name: 'timing',
  17317. reg: /^(\d*) (\d*)/,
  17318. names: ['start', 'stop'],
  17319. format: "%d %d"
  17320. }],
  17321. c: [{ //c=IN IP4 10.47.197.26
  17322. name: 'connection',
  17323. reg: /^IN IP(\d) (\S*)/,
  17324. names: ['version', 'ip'],
  17325. format: "IN IP%d %s"
  17326. }],
  17327. b: [{ //b=AS:4000
  17328. push: 'bandwidth',
  17329. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  17330. names: ['type', 'limit'],
  17331. format: "%s:%s"
  17332. }],
  17333. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  17334. // NB: special - pushes to session
  17335. // TODO: rtp/fmtp should be filtered by the payloads found here?
  17336. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  17337. names: ['type', 'port', 'protocol', 'payloads'],
  17338. format: "%s %d %s %s"
  17339. }],
  17340. a: [
  17341. { //a=rtpmap:110 opus/48000/2
  17342. push: 'rtp',
  17343. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  17344. names: ['payload', 'codec', 'rate', 'encoding'],
  17345. format: function (o) {
  17346. return (o.encoding) ?
  17347. "rtpmap:%d %s/%s/%s":
  17348. "rtpmap:%d %s/%s";
  17349. }
  17350. },
  17351. {
  17352. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  17353. //a=fmtp:111 minptime=10; useinbandfec=1
  17354. push: 'fmtp',
  17355. reg: /^fmtp:(\d*) ([\S| ]*)/,
  17356. names: ['payload', 'config'],
  17357. format: "fmtp:%d %s"
  17358. },
  17359. { //a=control:streamid=0
  17360. name: 'control',
  17361. reg: /^control:(.*)/,
  17362. format: "control:%s"
  17363. },
  17364. { //a=rtcp:65179 IN IP4 193.84.77.194
  17365. name: 'rtcp',
  17366. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  17367. names: ['port', 'netType', 'ipVer', 'address'],
  17368. format: function (o) {
  17369. return (o.address != null) ?
  17370. "rtcp:%d %s IP%d %s":
  17371. "rtcp:%d";
  17372. }
  17373. },
  17374. { //a=rtcp-fb:98 trr-int 100
  17375. push: 'rtcpFbTrrInt',
  17376. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  17377. names: ['payload', 'value'],
  17378. format: "rtcp-fb:%d trr-int %d"
  17379. },
  17380. { //a=rtcp-fb:98 nack rpsi
  17381. push: 'rtcpFb',
  17382. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  17383. names: ['payload', 'type', 'subtype'],
  17384. format: function (o) {
  17385. return (o.subtype != null) ?
  17386. "rtcp-fb:%s %s %s":
  17387. "rtcp-fb:%s %s";
  17388. }
  17389. },
  17390. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  17391. //a=extmap:1/recvonly URI-gps-string
  17392. push: 'ext',
  17393. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  17394. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  17395. format: function (o) {
  17396. return (o.config != null) ?
  17397. "extmap:%s %s %s":
  17398. "extmap:%s %s";
  17399. }
  17400. },
  17401. {
  17402. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  17403. push: 'crypto',
  17404. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  17405. names: ['id', 'suite', 'config', 'sessionConfig'],
  17406. format: function (o) {
  17407. return (o.sessionConfig != null) ?
  17408. "crypto:%d %s %s %s":
  17409. "crypto:%d %s %s";
  17410. }
  17411. },
  17412. { //a=setup:actpass
  17413. name: 'setup',
  17414. reg: /^setup:(\w*)/,
  17415. format: "setup:%s"
  17416. },
  17417. { //a=mid:1
  17418. name: 'mid',
  17419. reg: /^mid:([^\s]*)/,
  17420. format: "mid:%s"
  17421. },
  17422. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  17423. name: 'msid',
  17424. reg: /^msid:(.*)/,
  17425. format: "msid:%s"
  17426. },
  17427. { //a=ptime:20
  17428. name: 'ptime',
  17429. reg: /^ptime:(\d*)/,
  17430. format: "ptime:%d"
  17431. },
  17432. { //a=maxptime:60
  17433. name: 'maxptime',
  17434. reg: /^maxptime:(\d*)/,
  17435. format: "maxptime:%d"
  17436. },
  17437. { //a=sendrecv
  17438. name: 'direction',
  17439. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  17440. },
  17441. { //a=ice-lite
  17442. name: 'icelite',
  17443. reg: /^(ice-lite)/
  17444. },
  17445. { //a=ice-ufrag:F7gI
  17446. name: 'iceUfrag',
  17447. reg: /^ice-ufrag:(\S*)/,
  17448. format: "ice-ufrag:%s"
  17449. },
  17450. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  17451. name: 'icePwd',
  17452. reg: /^ice-pwd:(\S*)/,
  17453. format: "ice-pwd:%s"
  17454. },
  17455. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  17456. name: 'fingerprint',
  17457. reg: /^fingerprint:(\S*) (\S*)/,
  17458. names: ['type', 'hash'],
  17459. format: "fingerprint:%s %s"
  17460. },
  17461. {
  17462. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  17463. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  17464. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  17465. push:'candidates',
  17466. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  17467. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  17468. format: function (o) {
  17469. var str = "candidate:%s %d %s %d %s %d typ %s";
  17470. // NB: candidate has two optional chunks, so %void middle one if it's missing
  17471. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  17472. if (o.generation != null) {
  17473. str += " generation %d";
  17474. }
  17475. return str;
  17476. }
  17477. },
  17478. { //a=end-of-candidates (keep after the candidates line for readability)
  17479. name: 'endOfCandidates',
  17480. reg: /^(end-of-candidates)/
  17481. },
  17482. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  17483. name: 'remoteCandidates',
  17484. reg: /^remote-candidates:(.*)/,
  17485. format: "remote-candidates:%s"
  17486. },
  17487. { //a=ice-options:google-ice
  17488. name: 'iceOptions',
  17489. reg: /^ice-options:(\S*)/,
  17490. format: "ice-options:%s"
  17491. },
  17492. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  17493. push: "ssrcs",
  17494. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  17495. names: ['id', 'attribute', 'value'],
  17496. format: "ssrc:%d %s:%s"
  17497. },
  17498. { //a=ssrc-group:FEC 1 2
  17499. push: "ssrcGroups",
  17500. reg: /^ssrc-group:(\w*) (.*)/,
  17501. names: ['semantics', 'ssrcs'],
  17502. format: "ssrc-group:%s %s"
  17503. },
  17504. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  17505. name: "msidSemantic",
  17506. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  17507. names: ['semantic', 'token'],
  17508. format: "msid-semantic: %s %s" // space after ":" is not accidental
  17509. },
  17510. { //a=group:BUNDLE audio video
  17511. push: 'groups',
  17512. reg: /^group:(\w*) (.*)/,
  17513. names: ['type', 'mids'],
  17514. format: "group:%s %s"
  17515. },
  17516. { //a=rtcp-mux
  17517. name: 'rtcpMux',
  17518. reg: /^(rtcp-mux)/
  17519. },
  17520. { //a=rtcp-rsize
  17521. name: 'rtcpRsize',
  17522. reg: /^(rtcp-rsize)/
  17523. },
  17524. { // any a= that we don't understand is kepts verbatim on media.invalid
  17525. push: 'invalid',
  17526. names: ["value"]
  17527. }
  17528. ]
  17529. };
  17530. // set sensible defaults to avoid polluting the grammar with boring details
  17531. Object.keys(grammar).forEach(function (key) {
  17532. var objs = grammar[key];
  17533. objs.forEach(function (obj) {
  17534. if (!obj.reg) {
  17535. obj.reg = /(.*)/;
  17536. }
  17537. if (!obj.format) {
  17538. obj.format = "%s";
  17539. }
  17540. });
  17541. });
  17542. },{}],67:[function(require,module,exports){
  17543. arguments[4][57][0].apply(exports,arguments)
  17544. },{"./parser":68,"./writer":69,"dup":57}],68:[function(require,module,exports){
  17545. var toIntIfInt = function (v) {
  17546. return String(Number(v)) === v ? Number(v) : v;
  17547. };
  17548. var attachProperties = function (match, location, names, rawName) {
  17549. if (rawName && !names) {
  17550. location[rawName] = toIntIfInt(match[1]);
  17551. }
  17552. else {
  17553. for (var i = 0; i < names.length; i += 1) {
  17554. if (match[i+1] != null) {
  17555. location[names[i]] = toIntIfInt(match[i+1]);
  17556. }
  17557. }
  17558. }
  17559. };
  17560. var parseReg = function (obj, location, content) {
  17561. var needsBlank = obj.name && obj.names;
  17562. if (obj.push && !location[obj.push]) {
  17563. location[obj.push] = [];
  17564. }
  17565. else if (needsBlank && !location[obj.name]) {
  17566. location[obj.name] = {};
  17567. }
  17568. var keyLocation = obj.push ?
  17569. {} : // blank object that will be pushed
  17570. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  17571. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  17572. if (obj.push) {
  17573. location[obj.push].push(keyLocation);
  17574. }
  17575. };
  17576. var grammar = require('./grammar');
  17577. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  17578. exports.parse = function (sdp) {
  17579. var session = {}
  17580. , media = []
  17581. , location = session; // points at where properties go under (one of the above)
  17582. // parse lines we understand
  17583. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  17584. var type = l[0];
  17585. var content = l.slice(2);
  17586. if (type === 'm') {
  17587. media.push({rtp: [], fmtp: []});
  17588. location = media[media.length-1]; // point at latest media line
  17589. }
  17590. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  17591. var obj = grammar[type][j];
  17592. if (obj.reg.test(content)) {
  17593. return parseReg(obj, location, content);
  17594. }
  17595. }
  17596. });
  17597. session.media = media; // link it up
  17598. return session;
  17599. };
  17600. var fmtpReducer = function (acc, expr) {
  17601. var s = expr.split('=');
  17602. if (s.length === 2) {
  17603. acc[s[0]] = toIntIfInt(s[1]);
  17604. }
  17605. return acc;
  17606. };
  17607. exports.parseFmtpConfig = function (str) {
  17608. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  17609. };
  17610. exports.parsePayloads = function (str) {
  17611. return str.split(' ').map(Number);
  17612. };
  17613. exports.parseRemoteCandidates = function (str) {
  17614. var candidates = [];
  17615. var parts = str.split(' ').map(toIntIfInt);
  17616. for (var i = 0; i < parts.length; i += 3) {
  17617. candidates.push({
  17618. component: parts[i],
  17619. ip: parts[i + 1],
  17620. port: parts[i + 2]
  17621. });
  17622. }
  17623. return candidates;
  17624. };
  17625. },{"./grammar":66}],69:[function(require,module,exports){
  17626. arguments[4][59][0].apply(exports,arguments)
  17627. },{"./grammar":66,"dup":59}],70:[function(require,module,exports){
  17628. var MediaStreamType = {
  17629. VIDEO_TYPE: "Video",
  17630. AUDIO_TYPE: "Audio"
  17631. };
  17632. module.exports = MediaStreamType;
  17633. },{}],71:[function(require,module,exports){
  17634. var RTCEvents = {
  17635. RTC_READY: "rtc.ready",
  17636. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  17637. LASTN_CHANGED: "rtc.lastn_changed",
  17638. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  17639. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  17640. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  17641. };
  17642. module.exports = RTCEvents;
  17643. },{}],72:[function(require,module,exports){
  17644. var Resolutions = {
  17645. "1080": {
  17646. width: 1920,
  17647. height: 1080,
  17648. order: 7
  17649. },
  17650. "fullhd": {
  17651. width: 1920,
  17652. height: 1080,
  17653. order: 7
  17654. },
  17655. "720": {
  17656. width: 1280,
  17657. height: 720,
  17658. order: 6
  17659. },
  17660. "hd": {
  17661. width: 1280,
  17662. height: 720,
  17663. order: 6
  17664. },
  17665. "960": {
  17666. width: 960,
  17667. height: 720,
  17668. order: 5
  17669. },
  17670. "640": {
  17671. width: 640,
  17672. height: 480,
  17673. order: 4
  17674. },
  17675. "vga": {
  17676. width: 640,
  17677. height: 480,
  17678. order: 4
  17679. },
  17680. "360": {
  17681. width: 640,
  17682. height: 360,
  17683. order: 3
  17684. },
  17685. "320": {
  17686. width: 320,
  17687. height: 240,
  17688. order: 2
  17689. },
  17690. "180": {
  17691. width: 320,
  17692. height: 180,
  17693. order: 1
  17694. }
  17695. };
  17696. module.exports = Resolutions;
  17697. },{}],73:[function(require,module,exports){
  17698. var StreamEventTypes = {
  17699. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  17700. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  17701. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  17702. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  17703. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  17704. TRACK_MUTE_CHANGED: "rtc.track_mute_changed"
  17705. };
  17706. module.exports = StreamEventTypes;
  17707. },{}],74:[function(require,module,exports){
  17708. var AuthenticationEvents = {
  17709. /**
  17710. * Event callback arguments:
  17711. * function(authenticationEnabled, userIdentity)
  17712. * authenticationEnabled - indicates whether authentication has been enabled
  17713. * in this session
  17714. * userIdentity - if user has been logged in then it contains user name. If
  17715. * contains 'null' or 'undefined' then user is not logged in.
  17716. */
  17717. IDENTITY_UPDATED: "authentication.identity_updated"
  17718. };
  17719. module.exports = AuthenticationEvents;
  17720. },{}],75:[function(require,module,exports){
  17721. var DesktopSharingEventTypes = {
  17722. INIT: "ds.init",
  17723. SWITCHING_DONE: "ds.switching_done",
  17724. NEW_STREAM_CREATED: "ds.new_stream_created"
  17725. };
  17726. module.exports = DesktopSharingEventTypes;
  17727. },{}],76:[function(require,module,exports){
  17728. var XMPPEvents = {
  17729. CONNECTION_FAILED: "xmpp.connection.failed",
  17730. // Indicates an interrupted connection event.
  17731. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  17732. // Indicates a restored connection event.
  17733. CONNECTION_RESTORED: "xmpp.connection.restored",
  17734. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  17735. CALL_INCOMING: "xmpp.callincoming.jingle",
  17736. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  17737. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  17738. KICKED: "xmpp.kicked",
  17739. BRIDGE_DOWN: "xmpp.bridge_down",
  17740. USER_ID_CHANGED: "xmpp.user_id_changed",
  17741. // We joined the MUC
  17742. MUC_JOINED: "xmpp.muc_joined",
  17743. // A member joined the MUC
  17744. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  17745. // A member left the MUC
  17746. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  17747. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  17748. MUC_DESTROYED: "xmpp.muc_destroyed",
  17749. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  17750. REMOTE_STATS: "xmpp.remote_stats",
  17751. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  17752. PRESENCE_STATUS: "xmpp.presence_status",
  17753. RESERVATION_ERROR: "xmpp.room_reservation_error",
  17754. SUBJECT_CHANGED: "xmpp.subject_changed",
  17755. MESSAGE_RECEIVED: "xmpp.message_received",
  17756. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  17757. PASSWORD_REQUIRED: "xmpp.password_required",
  17758. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  17759. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  17760. ETHERPAD: "xmpp.etherpad",
  17761. DEVICE_AVAILABLE: "xmpp.device_available",
  17762. VIDEO_TYPE: "xmpp.video_type",
  17763. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  17764. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  17765. AUDIO_MUTED: "xmpp.audio_muted",
  17766. VIDEO_MUTED: "xmpp.video_muted",
  17767. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  17768. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  17769. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  17770. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  17771. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  17772. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  17773. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  17774. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  17775. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  17776. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  17777. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  17778. // xmpp is connected and obtained user media
  17779. READY_TO_JOIN: 'xmpp.ready_to_join',
  17780. FOCUS_LEFT: "xmpp.focus_left",
  17781. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received"
  17782. };
  17783. module.exports = XMPPEvents;
  17784. },{}],77:[function(require,module,exports){
  17785. // Copyright Joyent, Inc. and other Node contributors.
  17786. //
  17787. // Permission is hereby granted, free of charge, to any person obtaining a
  17788. // copy of this software and associated documentation files (the
  17789. // "Software"), to deal in the Software without restriction, including
  17790. // without limitation the rights to use, copy, modify, merge, publish,
  17791. // distribute, sublicense, and/or sell copies of the Software, and to permit
  17792. // persons to whom the Software is furnished to do so, subject to the
  17793. // following conditions:
  17794. //
  17795. // The above copyright notice and this permission notice shall be included
  17796. // in all copies or substantial portions of the Software.
  17797. //
  17798. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  17799. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17800. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  17801. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  17802. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  17803. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  17804. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  17805. function EventEmitter() {
  17806. this._events = this._events || {};
  17807. this._maxListeners = this._maxListeners || undefined;
  17808. }
  17809. module.exports = EventEmitter;
  17810. // Backwards-compat with node 0.10.x
  17811. EventEmitter.EventEmitter = EventEmitter;
  17812. EventEmitter.prototype._events = undefined;
  17813. EventEmitter.prototype._maxListeners = undefined;
  17814. // By default EventEmitters will print a warning if more than 10 listeners are
  17815. // added to it. This is a useful default which helps finding memory leaks.
  17816. EventEmitter.defaultMaxListeners = 10;
  17817. // Obviously not all Emitters should be limited to 10. This function allows
  17818. // that to be increased. Set to zero for unlimited.
  17819. EventEmitter.prototype.setMaxListeners = function(n) {
  17820. if (!isNumber(n) || n < 0 || isNaN(n))
  17821. throw TypeError('n must be a positive number');
  17822. this._maxListeners = n;
  17823. return this;
  17824. };
  17825. EventEmitter.prototype.emit = function(type) {
  17826. var er, handler, len, args, i, listeners;
  17827. if (!this._events)
  17828. this._events = {};
  17829. // If there is no 'error' event listener then throw.
  17830. if (type === 'error') {
  17831. if (!this._events.error ||
  17832. (isObject(this._events.error) && !this._events.error.length)) {
  17833. er = arguments[1];
  17834. if (er instanceof Error) {
  17835. throw er; // Unhandled 'error' event
  17836. }
  17837. throw TypeError('Uncaught, unspecified "error" event.');
  17838. }
  17839. }
  17840. handler = this._events[type];
  17841. if (isUndefined(handler))
  17842. return false;
  17843. if (isFunction(handler)) {
  17844. switch (arguments.length) {
  17845. // fast cases
  17846. case 1:
  17847. handler.call(this);
  17848. break;
  17849. case 2:
  17850. handler.call(this, arguments[1]);
  17851. break;
  17852. case 3:
  17853. handler.call(this, arguments[1], arguments[2]);
  17854. break;
  17855. // slower
  17856. default:
  17857. len = arguments.length;
  17858. args = new Array(len - 1);
  17859. for (i = 1; i < len; i++)
  17860. args[i - 1] = arguments[i];
  17861. handler.apply(this, args);
  17862. }
  17863. } else if (isObject(handler)) {
  17864. len = arguments.length;
  17865. args = new Array(len - 1);
  17866. for (i = 1; i < len; i++)
  17867. args[i - 1] = arguments[i];
  17868. listeners = handler.slice();
  17869. len = listeners.length;
  17870. for (i = 0; i < len; i++)
  17871. listeners[i].apply(this, args);
  17872. }
  17873. return true;
  17874. };
  17875. EventEmitter.prototype.addListener = function(type, listener) {
  17876. var m;
  17877. if (!isFunction(listener))
  17878. throw TypeError('listener must be a function');
  17879. if (!this._events)
  17880. this._events = {};
  17881. // To avoid recursion in the case that type === "newListener"! Before
  17882. // adding it to the listeners, first emit "newListener".
  17883. if (this._events.newListener)
  17884. this.emit('newListener', type,
  17885. isFunction(listener.listener) ?
  17886. listener.listener : listener);
  17887. if (!this._events[type])
  17888. // Optimize the case of one listener. Don't need the extra array object.
  17889. this._events[type] = listener;
  17890. else if (isObject(this._events[type]))
  17891. // If we've already got an array, just append.
  17892. this._events[type].push(listener);
  17893. else
  17894. // Adding the second element, need to change to array.
  17895. this._events[type] = [this._events[type], listener];
  17896. // Check for listener leak
  17897. if (isObject(this._events[type]) && !this._events[type].warned) {
  17898. var m;
  17899. if (!isUndefined(this._maxListeners)) {
  17900. m = this._maxListeners;
  17901. } else {
  17902. m = EventEmitter.defaultMaxListeners;
  17903. }
  17904. if (m && m > 0 && this._events[type].length > m) {
  17905. this._events[type].warned = true;
  17906. console.error('(node) warning: possible EventEmitter memory ' +
  17907. 'leak detected. %d listeners added. ' +
  17908. 'Use emitter.setMaxListeners() to increase limit.',
  17909. this._events[type].length);
  17910. if (typeof console.trace === 'function') {
  17911. // not supported in IE 10
  17912. console.trace();
  17913. }
  17914. }
  17915. }
  17916. return this;
  17917. };
  17918. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  17919. EventEmitter.prototype.once = function(type, listener) {
  17920. if (!isFunction(listener))
  17921. throw TypeError('listener must be a function');
  17922. var fired = false;
  17923. function g() {
  17924. this.removeListener(type, g);
  17925. if (!fired) {
  17926. fired = true;
  17927. listener.apply(this, arguments);
  17928. }
  17929. }
  17930. g.listener = listener;
  17931. this.on(type, g);
  17932. return this;
  17933. };
  17934. // emits a 'removeListener' event iff the listener was removed
  17935. EventEmitter.prototype.removeListener = function(type, listener) {
  17936. var list, position, length, i;
  17937. if (!isFunction(listener))
  17938. throw TypeError('listener must be a function');
  17939. if (!this._events || !this._events[type])
  17940. return this;
  17941. list = this._events[type];
  17942. length = list.length;
  17943. position = -1;
  17944. if (list === listener ||
  17945. (isFunction(list.listener) && list.listener === listener)) {
  17946. delete this._events[type];
  17947. if (this._events.removeListener)
  17948. this.emit('removeListener', type, listener);
  17949. } else if (isObject(list)) {
  17950. for (i = length; i-- > 0;) {
  17951. if (list[i] === listener ||
  17952. (list[i].listener && list[i].listener === listener)) {
  17953. position = i;
  17954. break;
  17955. }
  17956. }
  17957. if (position < 0)
  17958. return this;
  17959. if (list.length === 1) {
  17960. list.length = 0;
  17961. delete this._events[type];
  17962. } else {
  17963. list.splice(position, 1);
  17964. }
  17965. if (this._events.removeListener)
  17966. this.emit('removeListener', type, listener);
  17967. }
  17968. return this;
  17969. };
  17970. EventEmitter.prototype.removeAllListeners = function(type) {
  17971. var key, listeners;
  17972. if (!this._events)
  17973. return this;
  17974. // not listening for removeListener, no need to emit
  17975. if (!this._events.removeListener) {
  17976. if (arguments.length === 0)
  17977. this._events = {};
  17978. else if (this._events[type])
  17979. delete this._events[type];
  17980. return this;
  17981. }
  17982. // emit removeListener for all listeners on all events
  17983. if (arguments.length === 0) {
  17984. for (key in this._events) {
  17985. if (key === 'removeListener') continue;
  17986. this.removeAllListeners(key);
  17987. }
  17988. this.removeAllListeners('removeListener');
  17989. this._events = {};
  17990. return this;
  17991. }
  17992. listeners = this._events[type];
  17993. if (isFunction(listeners)) {
  17994. this.removeListener(type, listeners);
  17995. } else {
  17996. // LIFO order
  17997. while (listeners.length)
  17998. this.removeListener(type, listeners[listeners.length - 1]);
  17999. }
  18000. delete this._events[type];
  18001. return this;
  18002. };
  18003. EventEmitter.prototype.listeners = function(type) {
  18004. var ret;
  18005. if (!this._events || !this._events[type])
  18006. ret = [];
  18007. else if (isFunction(this._events[type]))
  18008. ret = [this._events[type]];
  18009. else
  18010. ret = this._events[type].slice();
  18011. return ret;
  18012. };
  18013. EventEmitter.listenerCount = function(emitter, type) {
  18014. var ret;
  18015. if (!emitter._events || !emitter._events[type])
  18016. ret = 0;
  18017. else if (isFunction(emitter._events[type]))
  18018. ret = 1;
  18019. else
  18020. ret = emitter._events[type].length;
  18021. return ret;
  18022. };
  18023. function isFunction(arg) {
  18024. return typeof arg === 'function';
  18025. }
  18026. function isNumber(arg) {
  18027. return typeof arg === 'number';
  18028. }
  18029. function isObject(arg) {
  18030. return typeof arg === 'object' && arg !== null;
  18031. }
  18032. function isUndefined(arg) {
  18033. return arg === void 0;
  18034. }
  18035. },{}],78:[function(require,module,exports){
  18036. // shim for using process in browser
  18037. var process = module.exports = {};
  18038. var queue = [];
  18039. var draining = false;
  18040. function drainQueue() {
  18041. if (draining) {
  18042. return;
  18043. }
  18044. draining = true;
  18045. var currentQueue;
  18046. var len = queue.length;
  18047. while(len) {
  18048. currentQueue = queue;
  18049. queue = [];
  18050. var i = -1;
  18051. while (++i < len) {
  18052. currentQueue[i]();
  18053. }
  18054. len = queue.length;
  18055. }
  18056. draining = false;
  18057. }
  18058. process.nextTick = function (fun) {
  18059. queue.push(fun);
  18060. if (!draining) {
  18061. setTimeout(drainQueue, 0);
  18062. }
  18063. };
  18064. process.title = 'browser';
  18065. process.browser = true;
  18066. process.env = {};
  18067. process.argv = [];
  18068. process.version = ''; // empty string to avoid regexp issues
  18069. function noop() {}
  18070. process.on = noop;
  18071. process.addListener = noop;
  18072. process.once = noop;
  18073. process.off = noop;
  18074. process.removeListener = noop;
  18075. process.removeAllListeners = noop;
  18076. process.emit = noop;
  18077. process.binding = function (name) {
  18078. throw new Error('process.binding is not supported');
  18079. };
  18080. // TODO(shtylman)
  18081. process.cwd = function () { return '/' };
  18082. process.chdir = function (dir) {
  18083. throw new Error('process.chdir is not supported');
  18084. };
  18085. process.umask = function() { return 0; };
  18086. },{}]},{},[7])(7)
  18087. });