modified lib-jitsi-meet dev repo
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 669KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488
  1. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.JitsiMeetJS=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. var RTC = require("./modules/RTC/RTC");
  3. var XMPPEvents = require("./service/xmpp/XMPPEvents");
  4. var StreamEventTypes = require("./service/RTC/StreamEventTypes");
  5. var RTCEvents = require("./service/RTC/RTCEvents");
  6. var EventEmitter = require("events");
  7. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  8. var JitsiParticipant = require("./JitsiParticipant");
  9. /**
  10. * Creates a JitsiConference object with the given name and properties.
  11. * Note: this constructor is not a part of the public API (objects should be
  12. * created using JitsiConnection.createConference).
  13. * @param options.config properties / settings related to the conference that will be created.
  14. * @param options.name the name of the conference
  15. * @param options.connection the JitsiConnection object for this JitsiConference.
  16. * @constructor
  17. */
  18. function JitsiConference(options) {
  19. this.options = options;
  20. this.connection = this.options.connection;
  21. this.xmpp = this.connection.xmpp;
  22. this.eventEmitter = new EventEmitter();
  23. this.room = this.xmpp.createRoom(this.options.name, null, null, this.options.config);
  24. this.rtc = new RTC(this.room, options);
  25. setupListeners(this);
  26. this.participants = {};
  27. }
  28. /**
  29. * Joins the conference.
  30. * @param password {string} the password
  31. */
  32. JitsiConference.prototype.join = function (password) {
  33. this.room.join(password);
  34. }
  35. /**
  36. * Leaves the conference.
  37. */
  38. JitsiConference.prototype.leave = function () {
  39. this.xmpp.leaveRoom(this.room.roomjid);
  40. this.room = null;
  41. }
  42. /**
  43. * Creates the media tracks and returns them trough the callback.
  44. * @param options Object with properties / settings specifying the tracks which should be created.
  45. * should be created or some additional configurations about resolution for example.
  46. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>} A promise that returns an array of created JitsiTracks if resolved,
  47. * or a JitsiConferenceError if rejected.
  48. */
  49. JitsiConference.prototype.createLocalTracks = function (options) {
  50. return this.rtc.obtainAudioAndVideoPermissions(options || {});
  51. }
  52. /**
  53. * Returns the local tracks.
  54. */
  55. JitsiConference.prototype.getLocalTracks = function () {
  56. return this.rtc.localStreams;
  57. };
  58. /**
  59. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  60. * in JitsiConferenceEvents.
  61. * @param eventId the event ID.
  62. * @param handler handler for the event.
  63. *
  64. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  65. */
  66. JitsiConference.prototype.on = function (eventId, handler) {
  67. this.eventEmitter.on(eventId, handler);
  68. }
  69. /**
  70. * Removes event listener
  71. * @param eventId the event ID.
  72. * @param [handler] optional, the specific handler to unbind
  73. *
  74. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  75. */
  76. JitsiConference.prototype.off = function (eventId, handler) {
  77. this.eventEmitter.removeListener(eventId, listener);
  78. }
  79. // Common aliases for event emitter
  80. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on
  81. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off
  82. /**
  83. * Receives notifications from another participants for commands / custom events(send by sendPresenceCommand method).
  84. * @param command {String} the name of the command
  85. * @param handler {Function} handler for the command
  86. */
  87. JitsiConference.prototype.addCommandListener = function (command, handler) {
  88. this.room.addPresenceListener(command, handler);
  89. }
  90. /**
  91. * Removes command listener
  92. * @param command {String} the name of the command
  93. */
  94. JitsiConference.prototype.removeCommandListener = function (command) {
  95. this.room.removePresenceListener(command);
  96. }
  97. /**
  98. * Sends text message to the other participants in the conference
  99. * @param message the text message.
  100. */
  101. JitsiConference.prototype.sendTextMessage = function (message) {
  102. this.room.sendMessage(message);
  103. }
  104. /**
  105. * Send presence command.
  106. * @param name the name of the command.
  107. * @param values Object with keys and values that will be send.
  108. **/
  109. JitsiConference.prototype.sendCommand = function (name, values) {
  110. this.room.addToPresence(name, values);
  111. this.room.sendPresence();
  112. }
  113. /**
  114. * Send presence command one time.
  115. * @param name the name of the command.
  116. * @param values Object with keys and values that will be send.
  117. **/
  118. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  119. this.sendCommand(name, values);
  120. this.removeCommand(name);
  121. }
  122. /**
  123. * Send presence command.
  124. * @param name the name of the command.
  125. * @param values Object with keys and values that will be send.
  126. * @param persistent if false the command will be sent only one time
  127. **/
  128. JitsiConference.prototype.removeCommand = function (name) {
  129. this.room.removeFromPresence(name);
  130. }
  131. /**
  132. * Sets the display name for this conference.
  133. * @param name the display name to set
  134. */
  135. JitsiConference.prototype.setDisplayName = function(name) {
  136. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  137. }
  138. /**
  139. * Elects the participant with the given id to be the selected participant or the speaker.
  140. * @param id the identifier of the participant
  141. */
  142. JitsiConference.prototype.selectParticipant = function(participantId) {
  143. this.rtc.selectedEndpoint(participantId);
  144. }
  145. /**
  146. *
  147. * @param id the identifier of the participant
  148. */
  149. JitsiConference.prototype.pinParticipant = function(participantId) {
  150. this.rtc.pinEndpoint(participantId);
  151. }
  152. /**
  153. * Returns the list of participants for this conference.
  154. * @return Object a list of participant identifiers containing all conference participants.
  155. */
  156. JitsiConference.prototype.getParticipants = function() {
  157. return this.participants;
  158. }
  159. /**
  160. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  161. * null if there isn't one).
  162. * @param id the id of the participant.
  163. */
  164. JitsiConference.prototype.getParticipantById = function(id) {
  165. return this.participants[id];
  166. }
  167. JitsiConference.prototype.onMemberJoined = function (jid, email, nick) {
  168. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, Strophe.getResourceFromJid(jid));
  169. // this.participants[jid] = new JitsiParticipant();
  170. }
  171. /**
  172. * Setups the listeners needed for the conference.
  173. * @param conference the conference
  174. */
  175. function setupListeners(conference) {
  176. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING,
  177. conference.rtc.onIncommingCall.bind(conference.rtc));
  178. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  179. conference.rtc.createRemoteStream.bind(conference.rtc));
  180. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, function (stream) {
  181. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, stream);
  182. });
  183. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_REMOTE_ENDED, function (stream) {
  184. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, stream);
  185. });
  186. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, function (stream) {
  187. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, stream);
  188. });
  189. conference.rtc.addListener(StreamEventTypes.TRACK_MUTE_CHANGED, function (track) {
  190. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  191. });
  192. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  193. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  194. });
  195. // FIXME
  196. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  197. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  198. // });
  199. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  200. conference.eventEmitter.emit(JitsiConferenceEvents.ACTIVE_SPEAKER_CHANGED, id);
  201. });
  202. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  203. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  204. });
  205. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  206. function (lastNEndpoints, endpointsEnteringLastN) {
  207. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  208. lastNEndpoints, endpointsEnteringLastN);
  209. });
  210. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  211. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT,function (jid) {
  212. conference.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, Strophe.getResourceFromJid(jid));
  213. });
  214. }
  215. module.exports = JitsiConference;
  216. },{"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./modules/RTC/RTC":13,"./service/RTC/RTCEvents":71,"./service/RTC/StreamEventTypes":73,"./service/xmpp/XMPPEvents":76,"events":77}],2:[function(require,module,exports){
  217. /**
  218. * Enumeration with the errors for the conference.
  219. * @type {{string: string}}
  220. */
  221. var JitsiConferenceErrors = {
  222. /**
  223. * Indicates that a password is required in order to join the conference.
  224. */
  225. PASSWORD_REQUIRED: "conference.passwordRequired",
  226. /**
  227. * Indicates that a connection error occurred when trying to join a conference.
  228. */
  229. CONNECTION_ERROR: "conference.connectionError",
  230. /**
  231. * Indicates that there is no available videobridge.
  232. */
  233. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  234. /**
  235. * Many more errors TBD here.
  236. */
  237. };
  238. module.exports = JitsiConferenceErrors;
  239. },{}],3:[function(require,module,exports){
  240. /**
  241. * Enumeration with the events for the conference.
  242. * @type {{string: string}}
  243. */
  244. var JitsiConferenceEvents = {
  245. /**
  246. * A new media track was added to the conference.
  247. */
  248. TRACK_ADDED: "conference.trackAdded",
  249. /**
  250. * The media track was removed to the conference.
  251. */
  252. TRACK_REMOVED: "conference.trackRemoved",
  253. /**
  254. * The active speaker was changed.
  255. */
  256. ACTIVE_SPEAKER_CHANGED: "conference.activeSpeaker",
  257. /**
  258. * A new user joinned the conference.
  259. */
  260. USER_JOINED: "conference.userJoined",
  261. /**
  262. * A user has left the conference.
  263. */
  264. USER_LEFT: "conference.userLeft",
  265. /**
  266. * New text message was received.
  267. */
  268. MESSAGE_RECEIVED: "conference.messageReceived",
  269. /**
  270. * A user has changed it display name
  271. */
  272. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  273. /**
  274. * A participant avatar has changed.
  275. */
  276. AVATAR_CHANGED: "conference.avatarChanged",
  277. /**
  278. * New connection statistics are received.
  279. */
  280. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  281. /**
  282. * The Last N set is changed.
  283. */
  284. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  285. /**
  286. * You are included / excluded in somebody's last N set
  287. */
  288. IN_LAST_N_CHANGED: "conference.lastNEndpointsChanged",
  289. /**
  290. * A media track mute status was changed.
  291. */
  292. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  293. /**
  294. * Audio levels of a media track was changed.
  295. */
  296. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  297. /**
  298. * Indicates that the connection to the conference has been interrupted for some reason.
  299. */
  300. CONNECTION_INTERRUPTED: "conference.connecionInterrupted",
  301. /**
  302. * Indicates that the connection to the conference has been restored.
  303. */
  304. CONNECTION_RESTORED: "conference.connecionRestored",
  305. /**
  306. * Indicates that conference has been joined.
  307. */
  308. CONFERENCE_JOINED: "conference.joined",
  309. /**
  310. * Indicates that conference has been left.
  311. */
  312. CONFERENCE_LEFT: "conference.left"
  313. };
  314. module.exports = JitsiConferenceEvents;
  315. },{}],4:[function(require,module,exports){
  316. var JitsiConference = require("./JitsiConference");
  317. var XMPP = require("./modules/xmpp/xmpp");
  318. /**
  319. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  320. * JitsiConference interface.
  321. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  322. * @param token secret generated by the provider of Jitsi Meet video conferencing services.
  323. * The token will be send to the provider from the Jitsi Meet server deployment for authorization of the current client.
  324. * @param options Object with properties / settings related to connection with the server.
  325. * @constructor
  326. */
  327. function JitsiConnection(appID, token, options) {
  328. this.appID = appID;
  329. this.token = token;
  330. this.options = options;
  331. this.xmpp = new XMPP(options);
  332. this.conferences = {};
  333. }
  334. /**
  335. * Connect the client with the server.
  336. * @param options {object} connecting options (for example authentications parameters).
  337. */
  338. JitsiConnection.prototype.connect = function (options) {
  339. if(!options)
  340. options = {};
  341. this.xmpp.connect(options.id, options.password);
  342. }
  343. /**
  344. * Disconnect the client from the server.
  345. */
  346. JitsiConnection.prototype.disconnect = function () {
  347. this.xmpp.disconnect();
  348. }
  349. /**
  350. * This method allows renewal of the tokens if they are expiring.
  351. * @param token the new token.
  352. */
  353. JitsiConnection.prototype.setToken = function (token) {
  354. this.token = token;
  355. }
  356. /**
  357. * Creates and joins new conference.
  358. * @param name the name of the conference; if null - a generated name will be provided from the api
  359. * @param options Object with properties / settings related to the conference that will be created.
  360. * @returns {JitsiConference} returns the new conference object.
  361. */
  362. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  363. this.conferences[name] = new JitsiConference({name: name, config: options, connection: this});
  364. return this.conferences[name];
  365. }
  366. /**
  367. * Subscribes the passed listener to the event.
  368. * @param event {JitsiConnectionEvents} the connection event.
  369. * @param listener {Function} the function that will receive the event
  370. */
  371. JitsiConnection.prototype.addEventListener = function (event, listener) {
  372. this.xmpp.addListener(event, listener);
  373. }
  374. /**
  375. * Unsubscribes the passed handler.
  376. * @param event {JitsiConnectionEvents} the connection event.
  377. * @param listener {Function} the function that will receive the event
  378. */
  379. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  380. this.xmpp.removeListener(event, listener);
  381. }
  382. module.exports = JitsiConnection;
  383. },{"./JitsiConference":1,"./modules/xmpp/xmpp":33}],5:[function(require,module,exports){
  384. /**
  385. * Enumeration with the errors for the connection.
  386. * @type {{string: string}}
  387. */
  388. var JitsiConnectionErrors = {
  389. /**
  390. * Indicates that a password is required in order to join the conference.
  391. */
  392. PASSWORD_REQUIRED: "connection.passwordRequired",
  393. /**
  394. * Indicates that a connection error occurred when trying to join a conference.
  395. */
  396. CONNECTION_ERROR: "connection.connectionError",
  397. /**
  398. * Not specified errors.
  399. */
  400. OTHER_ERROR: "connection.otherError"
  401. };
  402. module.exports = JitsiConnectionErrors;
  403. },{}],6:[function(require,module,exports){
  404. /**
  405. * Enumeration with the events for the connection.
  406. * @type {{string: string}}
  407. */
  408. var JitsiConnnectionEvents = {
  409. /**
  410. * Indicates that the connection has been failed for some reason.
  411. */
  412. CONNECTION_FAILED: "connection.connecionFailed",
  413. /**
  414. * Indicates that the connection has been established.
  415. */
  416. CONNECTION_ESTABLISHED: "connection.connecionEstablished",
  417. /**
  418. * Indicates that the connection has been disconnected.
  419. */
  420. CONNECTION_DISCONNECTED: "connection.connecionDisconnected",
  421. /**
  422. * Indicates that the perfomed action cannot be executed because the
  423. * connection is not in the correct state(connected, disconnected, etc.)
  424. */
  425. WRONG_STATE: "connection.wrongState"
  426. };
  427. module.exports = JitsiConnnectionEvents;
  428. },{}],7:[function(require,module,exports){
  429. var JitsiConnection = require("./JitsiConnection");
  430. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  431. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  432. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  433. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  434. /**
  435. * Namespace for the interface of Jitsi Meet Library.
  436. */
  437. var LibJitsiMeet = {
  438. JitsiConnection: JitsiConnection,
  439. events: {
  440. conference: JitsiConferenceEvents,
  441. connection: JitsiConnectionEvents
  442. },
  443. errors: {
  444. conference: JitsiConferenceErrors,
  445. connection: JitsiConnectionErrors
  446. },
  447. init: function (options) {
  448. require("./modules/RTC/RTC").init(options || {});
  449. }
  450. }
  451. //Setups the promise object.
  452. window.Promise = window.Promise || require("es6-promise").polyfill();
  453. module.exports = LibJitsiMeet;
  454. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./modules/RTC/RTC":13,"es6-promise":35}],8:[function(require,module,exports){
  455. /**
  456. * Represents a participant in (a member of) a conference.
  457. */
  458. function JitsiParticipant(id, conference, displayName){
  459. this._id = id;
  460. this._conference = conference;
  461. this._displayName = displayName;
  462. }
  463. /**
  464. * @returns {JitsiConference} The conference that this participant belongs to.
  465. */
  466. JitsiParticipant.prototype.getConference = function() {
  467. return this._conference;
  468. }
  469. /**
  470. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  471. */
  472. JitsiParticipant.prototype.getTracks = function() {
  473. }
  474. /**
  475. * @returns {String} The ID (i.e. JID) of this participant.
  476. */
  477. JitsiParticipant.prototype.getId = function() {
  478. return this._id;
  479. }
  480. /**
  481. * @returns {String} The human-readable display name of this participant.
  482. */
  483. JitsiParticipant.prototype.getDisplayName = function() {
  484. return this._displayName;
  485. }
  486. /**
  487. * @returns {Boolean} Whether this participant is a moderator or not.
  488. */
  489. JitsiParticipant.prototype.isModerator = function() {
  490. }
  491. // Gets a link to an etherpad instance advertised by the participant?
  492. //JitsiParticipant.prototype.getEtherpad = function() {
  493. //
  494. //}
  495. /*
  496. * @returns {Boolean} Whether this participant has muted their audio.
  497. */
  498. JitsiParticipant.prototype.isAudioMuted = function() {
  499. }
  500. /*
  501. * @returns {Boolean} Whether this participant has muted their video.
  502. */
  503. JitsiParticipant.prototype.isVideoMuted = function() {
  504. }
  505. /*
  506. * @returns {???} The latest statistics reported by this participant (i.e. info used to populate the GSM bars)
  507. * TODO: do we expose this or handle it internally?
  508. */
  509. JitsiParticipant.prototype.getLatestStats = function() {
  510. }
  511. /**
  512. * @returns {String} The role of this participant.
  513. */
  514. JitsiParticipant.prototype.getRole = function() {
  515. }
  516. /*
  517. * @returns {Boolean} Whether this participant is the conference focus (i.e. jicofo).
  518. */
  519. JitsiParticipant.prototype.isFocus = function() {
  520. }
  521. /*
  522. * @returns {Boolean} Whether this participant is a conference recorder (i.e. jirecon).
  523. */
  524. JitsiParticipant.prototype.isRecorder = function() {
  525. }
  526. /*
  527. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  528. */
  529. JitsiParticipant.prototype.isSipGateway = function() {
  530. }
  531. /**
  532. * @returns {String} The ID for this participant's avatar.
  533. */
  534. JitsiParticipant.prototype.getAvatarId = function() {
  535. }
  536. /**
  537. * @returns {Boolean} Whether this participant is currently sharing their screen.
  538. */
  539. JitsiParticipant.prototype.isScreenSharing = function() {
  540. }
  541. /**
  542. * @returns {String} The user agent of this participant (i.e. browser userAgent string).
  543. */
  544. JitsiParticipant.prototype.getUserAgent = function() {
  545. }
  546. /**
  547. * Kicks the participant from the conference (requires certain privileges).
  548. */
  549. JitsiParticipant.prototype.kick = function() {
  550. }
  551. /**
  552. * Asks this participant to mute themselves.
  553. */
  554. JitsiParticipant.prototype.askToMute = function() {
  555. }
  556. module.exports = JitsiParticipant();
  557. },{}],9:[function(require,module,exports){
  558. /* global config, APP, Strophe */
  559. // cache datachannels to avoid garbage collection
  560. // https://code.google.com/p/chromium/issues/detail?id=405545
  561. var RTCEvents = require("../../service/RTC/RTCEvents");
  562. /**
  563. * Binds "ondatachannel" event listener to given PeerConnection instance.
  564. * @param peerConnection WebRTC peer connection instance.
  565. */
  566. function DataChannels(peerConnection, emitter) {
  567. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  568. this.eventEmitter = emitter;
  569. this._dataChannels = [];
  570. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  571. // Although it's not a requirement to open separate channels from both bridge
  572. // and peer as single channel can be used for sending and receiving data.
  573. // So either channel opened by the bridge or the one opened here is enough
  574. // for communication with the bridge.
  575. /*var dataChannelOptions =
  576. {
  577. reliable: true
  578. };
  579. var dataChannel
  580. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  581. // Can be used only when is in open state
  582. dataChannel.onopen = function ()
  583. {
  584. dataChannel.send("My channel !!!");
  585. };
  586. dataChannel.onmessage = function (event)
  587. {
  588. var msgData = event.data;
  589. console.info("Got My Data Channel Message:", msgData, dataChannel);
  590. };*/
  591. };
  592. /**
  593. * Callback triggered by PeerConnection when new data channel is opened
  594. * on the bridge.
  595. * @param event the event info object.
  596. */
  597. DataChannels.prototype.onDataChannel = function (event) {
  598. var dataChannel = event.channel;
  599. var self = this;
  600. dataChannel.onopen = function () {
  601. console.info("Data channel opened by the Videobridge!", dataChannel);
  602. // Code sample for sending string and/or binary data
  603. // Sends String message to the bridge
  604. //dataChannel.send("Hello bridge!");
  605. // Sends 12 bytes binary message to the bridge
  606. //dataChannel.send(new ArrayBuffer(12));
  607. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  608. };
  609. dataChannel.onerror = function (error) {
  610. console.error("Data Channel Error:", error, dataChannel);
  611. };
  612. dataChannel.onmessage = function (event) {
  613. var data = event.data;
  614. // JSON
  615. var obj;
  616. try {
  617. obj = JSON.parse(data);
  618. }
  619. catch (e) {
  620. console.error(
  621. "Failed to parse data channel message as JSON: ",
  622. data,
  623. dataChannel);
  624. }
  625. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  626. var colibriClass = obj.colibriClass;
  627. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  628. // Endpoint ID from the Videobridge.
  629. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  630. console.info(
  631. "Data channel new dominant speaker event: ",
  632. dominantSpeakerEndpoint);
  633. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  634. }
  635. else if ("InLastNChangeEvent" === colibriClass) {
  636. var oldValue = obj.oldValue;
  637. var newValue = obj.newValue;
  638. // Make sure that oldValue and newValue are of type boolean.
  639. var type;
  640. if ((type = typeof oldValue) !== 'boolean') {
  641. if (type === 'string') {
  642. oldValue = (oldValue == "true");
  643. } else {
  644. oldValue = new Boolean(oldValue).valueOf();
  645. }
  646. }
  647. if ((type = typeof newValue) !== 'boolean') {
  648. if (type === 'string') {
  649. newValue = (newValue == "true");
  650. } else {
  651. newValue = new Boolean(newValue).valueOf();
  652. }
  653. }
  654. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  655. }
  656. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  657. // The new/latest list of last-n endpoint IDs.
  658. var lastNEndpoints = obj.lastNEndpoints;
  659. // The list of endpoint IDs which are entering the list of
  660. // last-n at this time i.e. were not in the old list of last-n
  661. // endpoint IDs.
  662. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  663. console.log(
  664. "Data channel new last-n event: ",
  665. lastNEndpoints, endpointsEnteringLastN, obj);
  666. this.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  667. lastNEndpoints, endpointsEnteringLastN, obj);
  668. }
  669. else {
  670. console.debug("Data channel JSON-formatted message: ", obj);
  671. }
  672. }
  673. };
  674. dataChannel.onclose = function () {
  675. console.info("The Data Channel closed", dataChannel);
  676. var idx = self._dataChannels.indexOf(dataChannel);
  677. if (idx > -1)
  678. self._dataChannels = self._dataChannels.splice(idx, 1);
  679. };
  680. this._dataChannels.push(dataChannel);
  681. };
  682. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  683. console.log('selected endpoint changed: ', userResource);
  684. if (this._dataChannels && this._dataChannels.length != 0) {
  685. this._dataChannels.some(function (dataChannel) {
  686. if (dataChannel.readyState == 'open') {
  687. console.log('sending selected endpoint changed ' +
  688. 'notification to the bridge: ', userResource);
  689. dataChannel.send(JSON.stringify({
  690. 'colibriClass': 'SelectedEndpointChangedEvent',
  691. 'selectedEndpoint':
  692. (!userResource || userResource === null)?
  693. null : userResource
  694. }));
  695. return true;
  696. }
  697. });
  698. }
  699. }
  700. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  701. console.log('pinned endpoint changed: ', userResource);
  702. if (this._dataChannels && this._dataChannels.length != 0) {
  703. this._dataChannels.some(function (dataChannel) {
  704. if (dataChannel.readyState == 'open') {
  705. dataChannel.send(JSON.stringify({
  706. 'colibriClass': 'PinnedEndpointChangedEvent',
  707. 'pinnedEndpoint':
  708. (!userResource || userResource == null)?
  709. null : userResource
  710. }));
  711. return true;
  712. }
  713. });
  714. }
  715. }
  716. module.exports = DataChannels;
  717. },{"../../service/RTC/RTCEvents":71}],10:[function(require,module,exports){
  718. var JitsiTrack = require("./JitsiTrack");
  719. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  720. var RTC = require("./RTCUtils");
  721. var RTCBrowserType = require("./RTCBrowserType");
  722. /**
  723. * Represents a single media track (either audio or video).
  724. * @constructor
  725. */
  726. function JitsiLocalTrack(RTC, stream, eventEmitter, videoType, isGUMStream)
  727. {
  728. JitsiTrack.call(this, RTC, stream);
  729. this.eventEmitter = eventEmitter;
  730. this.videoType = videoType;
  731. this.isGUMStream = true;
  732. this.dontFireRemoveEvent = false;
  733. var self = this;
  734. if(isGUMStream === false)
  735. this.isGUMStream = isGUMStream;
  736. this.stream.onended = function () {
  737. if(!self.dontFireRemoveEvent)
  738. self.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, self);
  739. self.dontFireRemoveEvent = false;
  740. };
  741. }
  742. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  743. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  744. /**
  745. * Mutes / unmutes the track.
  746. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  747. */
  748. JitsiLocalTrack.prototype._setMute = function (mute) {
  749. var isAudio = this.type === JitsiTrack.AUDIO;
  750. this.dontFireRemoveEvent = false;
  751. if ((window.location.protocol != "https:" && this.isGUMStream) ||
  752. (isAudio && this.isGUMStream) || this.videoType === "screen" ||
  753. // FIXME FF does not support 'removeStream' method used to mute
  754. RTCBrowserType.isFirefox()) {
  755. var tracks = this._getTracks();
  756. for (var idx = 0; idx < tracks.length; idx++) {
  757. tracks[idx].enabled = !mute;
  758. }
  759. if(isAudio)
  760. this.rtc.room.setAudioMute(mute);
  761. else
  762. this.rtc.room.setVideoMute(mute);
  763. this.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  764. } else {
  765. if (mute) {
  766. this.dontFireRemoveEvent = true;
  767. this.rtc.room.removeStream(this.stream);
  768. this.stream.stop();
  769. if(isAudio)
  770. this.rtc.room.setAudioMute(mute);
  771. else
  772. this.rtc.room.setVideoMute(mute);
  773. this.stream = null;
  774. this.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  775. //FIXME: Maybe here we should set the SRC for the containers to something
  776. } else {
  777. var self = this;
  778. this.rtc.obtainAudioAndVideoPermissions(
  779. {devices: (isAudio ? ["audio"] : ["video"])}, true)
  780. .then(function (streams) {
  781. var stream = null;
  782. for(var i = 0; i < streams.length; i++) {
  783. stream = streams[i];
  784. if(stream.type === self.type) {
  785. self.stream = stream.stream;
  786. self.videoType = stream.videoType;
  787. self.isGUMStream = stream.isGUMStream;
  788. break;
  789. }
  790. }
  791. if(!stream)
  792. return;
  793. for(var i = 0; i < self.containers.length; i++)
  794. {
  795. RTC.attachMediaStream(self.containers[i], self.stream);
  796. }
  797. self.rtc.room.addStream(stream.stream,
  798. function () {
  799. if(isAudio)
  800. self.rtc.room.setAudioMute(mute);
  801. else
  802. self.rtc.room.setVideoMute(mute);
  803. self.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, self);
  804. });
  805. });
  806. }
  807. }
  808. }
  809. /**
  810. * Stops sending the media track. And removes it from the HTML.
  811. * NOTE: Works for local tracks only.
  812. */
  813. JitsiLocalTrack.prototype.stop = function () {
  814. if(!this.stream)
  815. return;
  816. this.rtc.room.removeStream(this.stream);
  817. this.stream.stop();
  818. this.detach();
  819. }
  820. /**
  821. * Starts sending the track.
  822. * NOTE: Works for local tracks only.
  823. */
  824. JitsiLocalTrack.prototype.start = function() {
  825. this.rtc.room.addStream(this.stream, function () {});
  826. }
  827. /**
  828. * Returns <tt>true</tt> - if the stream is muted
  829. * and <tt>false</tt> otherwise.
  830. * @returns {boolean} <tt>true</tt> - if the stream is muted
  831. * and <tt>false</tt> otherwise.
  832. */
  833. JitsiLocalTrack.prototype.isMuted = function () {
  834. if (!this.stream)
  835. return true;
  836. var tracks = [];
  837. var isAudio = this.type === JitsiTrack.AUDIO;
  838. if (isAudio) {
  839. tracks = this.stream.getAudioTracks();
  840. } else {
  841. if (this.stream.ended)
  842. return true;
  843. tracks = this.stream.getVideoTracks();
  844. }
  845. for (var idx = 0; idx < tracks.length; idx++) {
  846. if(tracks[idx].enabled)
  847. return false;
  848. }
  849. return true;
  850. };
  851. module.exports = JitsiLocalTrack;
  852. },{"../../service/RTC/StreamEventTypes":73,"./JitsiTrack":12,"./RTCBrowserType":14,"./RTCUtils":15}],11:[function(require,module,exports){
  853. var JitsiTrack = require("./JitsiTrack");
  854. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  855. /**
  856. * Represents a single media track (either audio or video).
  857. * @param RTC the rtc instance.
  858. * @param data object with the stream and some details about it(participant id, video type, etc.)
  859. * @param sid sid for the Media Stream
  860. * @param ssrc ssrc for the Media Stream
  861. * @param eventEmitter the event emitter
  862. * @constructor
  863. */
  864. function JitsiRemoteTrack(RTC, data, sid, ssrc, eventEmitter) {
  865. JitsiTrack.call(this, RTC, data.stream);
  866. this.rtc = RTC;
  867. this.sid = sid;
  868. this.stream = data.stream;
  869. this.peerjid = data.peerjid;
  870. this.videoType = data.videoType;
  871. this.ssrc = ssrc;
  872. this.muted = false;
  873. this.eventEmitter = eventEmitter;
  874. var self = this;
  875. if(this.stream)
  876. this.stream.onended = function () {
  877. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_ENDED, self);
  878. }
  879. }
  880. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  881. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  882. /**
  883. * Sets current muted status and fires an events for the change.
  884. * @param value the muted status.
  885. */
  886. JitsiRemoteTrack.prototype.setMute = function (value) {
  887. this.stream.muted = value;
  888. this.muted = value;
  889. this.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  890. };
  891. /**
  892. * Returns the current muted status of the track.
  893. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  894. */
  895. JitsiRemoteTrack.prototype.isMuted = function () {
  896. return this.muted;
  897. }
  898. /**
  899. * Returns the participant id which owns the track.
  900. * @returns {string} the id of the participants.
  901. */
  902. JitsiRemoteTrack.prototype.getParitcipantId = function() {
  903. return Strophe.getResourceFromJid(this.peerjid);
  904. };
  905. delete JitsiRemoteTrack.prototype.stop;
  906. delete JitsiRemoteTrack.prototype.start;
  907. module.exports = JitsiRemoteTrack;
  908. },{"../../service/RTC/StreamEventTypes":73,"./JitsiTrack":12}],12:[function(require,module,exports){
  909. var RTC = require("./RTCUtils");
  910. var RTCBrowserType = require("./RTCBrowserType");
  911. /**
  912. * This implements 'onended' callback normally fired by WebRTC after the stream
  913. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  914. * @param stream original WebRTC stream object to which 'onended' handling
  915. * will be added.
  916. */
  917. function implementOnEndedHandling(stream) {
  918. var originalStop = stream.stop;
  919. stream.stop = function () {
  920. originalStop.apply(stream);
  921. if (!stream.ended) {
  922. stream.ended = true;
  923. stream.onended();
  924. }
  925. };
  926. }
  927. /**
  928. * Represents a single media track (either audio or video).
  929. * @constructor
  930. */
  931. function JitsiTrack(RTC, stream)
  932. {
  933. /**
  934. * Array with the HTML elements that are displaying the streams.
  935. * @type {Array}
  936. */
  937. this.containers = [];
  938. this.rtc = RTC;
  939. this.stream = stream;
  940. this.type = (this.stream.getVideoTracks().length > 0)?
  941. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  942. if(this.type == "audio") {
  943. this._getTracks = function () {
  944. return this.stream.getAudioTracks();
  945. }.bind(this);
  946. } else {
  947. this._getTracks = function () {
  948. return this.stream.getVideoTracks();
  949. }.bind(this);
  950. }
  951. if (RTCBrowserType.isFirefox() && this.stream) {
  952. implementOnEndedHandling(this.stream);
  953. }
  954. }
  955. /**
  956. * JitsiTrack video type.
  957. * @type {string}
  958. */
  959. JitsiTrack.VIDEO = "video";
  960. /**
  961. * JitsiTrack audio type.
  962. * @type {string}
  963. */
  964. JitsiTrack.AUDIO = "audio";
  965. /**
  966. * Returns the type (audio or video) of this track.
  967. */
  968. JitsiTrack.prototype.getType = function() {
  969. return this.type;
  970. };
  971. /**
  972. * Returns the RTCMediaStream from the browser (?).
  973. */
  974. JitsiTrack.prototype.getOriginalStream = function() {
  975. return this.stream;
  976. }
  977. /**
  978. * Mutes the track.
  979. */
  980. JitsiTrack.prototype.mute = function () {
  981. this._setMute(true);
  982. }
  983. /**
  984. * Unmutes the stream.
  985. */
  986. JitsiTrack.prototype.unmute = function () {
  987. this._setMute(false);
  988. }
  989. /**
  990. * Attaches the MediaStream of this track to an HTML container (?).
  991. * Adds the container to the list of containers that are displaying the track.
  992. * @param container the HTML container
  993. */
  994. JitsiTrack.prototype.attach = function (container) {
  995. if(this.stream)
  996. RTC.attachMediaStream(container, this.stream);
  997. this.containers.push(container);
  998. }
  999. /**
  1000. * Removes the track from the passed HTML container.
  1001. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  1002. */
  1003. JitsiTrack.prototype.detach = function (container) {
  1004. for(var i = 0; i < this.containers.length; i++)
  1005. {
  1006. if(this.containers[i].is(container))
  1007. {
  1008. this.containers.splice(i,1);
  1009. }
  1010. if(!container)
  1011. {
  1012. this.containers[i].find(">video").remove();
  1013. }
  1014. }
  1015. if(container)
  1016. $(container).find(">video").remove();
  1017. }
  1018. /**
  1019. * Stops sending the media track. And removes it from the HTML.
  1020. * NOTE: Works for local tracks only.
  1021. */
  1022. JitsiTrack.prototype.stop = function () {
  1023. }
  1024. /**
  1025. * Starts sending the track.
  1026. * NOTE: Works for local tracks only.
  1027. */
  1028. JitsiTrack.prototype.start = function() {
  1029. }
  1030. /**
  1031. * Returns true if this is a video track and the source of the video is a
  1032. * screen capture as opposed to a camera.
  1033. */
  1034. JitsiTrack.prototype.isScreenSharing = function(){
  1035. }
  1036. /**
  1037. * Returns id of the track.
  1038. * @returns {string} id of the track or null if this is fake track.
  1039. */
  1040. JitsiTrack.prototype.getId = function () {
  1041. var tracks = this.stream.getTracks();
  1042. if(!tracks || tracks.length === 0)
  1043. return null;
  1044. return tracks[0].id;
  1045. };
  1046. module.exports = JitsiTrack;
  1047. },{"./RTCBrowserType":14,"./RTCUtils":15}],13:[function(require,module,exports){
  1048. /* global APP */
  1049. var EventEmitter = require("events");
  1050. var RTCBrowserType = require("./RTCBrowserType");
  1051. var RTCUtils = require("./RTCUtils.js");
  1052. var JitsiTrack = require("./JitsiTrack");
  1053. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  1054. var DataChannels = require("./DataChannels");
  1055. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  1056. var DesktopSharingEventTypes
  1057. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1058. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  1059. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  1060. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  1061. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  1062. var desktopsharing = require("../desktopsharing/desktopsharing");
  1063. function getMediaStreamUsage()
  1064. {
  1065. var result = {
  1066. audio: true,
  1067. video: true
  1068. };
  1069. /** There are some issues with the desktop sharing
  1070. * when this property is enabled.
  1071. * WARNING: We must change the implementation to start video/audio if we
  1072. * receive from the focus that the peer is not muted.
  1073. var isSecureConnection = window.location.protocol == "https:";
  1074. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  1075. {
  1076. result = {
  1077. audio: false,
  1078. video: false
  1079. };
  1080. }
  1081. **/
  1082. return result;
  1083. }
  1084. var rtcReady = false;
  1085. function RTC(room, options) {
  1086. this.devices = {
  1087. audio: true,
  1088. video: true
  1089. };
  1090. this.room = room;
  1091. this.localStreams = [];
  1092. this.remoteStreams = {};
  1093. this.localAudio = null;
  1094. this.localVideo = null;
  1095. this.eventEmitter = new EventEmitter();
  1096. var self = this;
  1097. this.options = options || {};
  1098. desktopsharing.addListener(
  1099. function (stream, isUsingScreenStream, callback) {
  1100. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  1101. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  1102. room.addPresenceListener("videomuted", function (values, from) {
  1103. if(self.remoteStreams[from])
  1104. self.remoteStreams[from][JitsiTrack.VIDEO].setMute(values.value == "true");
  1105. });
  1106. room.addPresenceListener("audiomuted", function (values, from) {
  1107. if(self.remoteStreams[from])
  1108. self.remoteStreams[from][JitsiTrack.AUDIO].setMute(values.value == "true");
  1109. });
  1110. }
  1111. /**
  1112. * Creates the local MediaStreams.
  1113. * @param options object for options (NOTE: currently only list of devices and resolution are supported)
  1114. * @param dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1115. * type: "audio" or "video", isMuted: true/false, videoType: "camera" or "desktop"}
  1116. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1117. * @returns {*} Promise object that will receive the new JitsiTracks
  1118. */
  1119. RTC.prototype.obtainAudioAndVideoPermissions = function (options, dontCreateJitsiTrack) {
  1120. return RTCUtils.obtainAudioAndVideoPermissions(this,
  1121. options.devices, getMediaStreamUsage(), options.resolution, dontCreateJitsiTrack);
  1122. }
  1123. RTC.prototype.onIncommingCall = function(event) {
  1124. if(this.options.config.openSctp)
  1125. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  1126. this.room.addLocalStreams(this.localStreams);
  1127. }
  1128. RTC.prototype.selectedEndpoint = function (id) {
  1129. if(this.dataChannels)
  1130. this.dataChannels.handleSelectedEndpointEvent(id);
  1131. }
  1132. RTC.prototype.pinEndpoint = function (id) {
  1133. if(this.dataChannels)
  1134. this.dataChannels.handlePinnedEndpointEvent(id);
  1135. }
  1136. RTC.prototype.addStreamListener = function (listener, eventType) {
  1137. this.eventEmitter.on(eventType, listener);
  1138. };
  1139. RTC.prototype.addListener = function (type, listener) {
  1140. this.eventEmitter.on(type, listener);
  1141. };
  1142. RTC.prototype.removeListener = function (listener, eventType) {
  1143. this.eventEmitter.removeListener(eventType, listener);
  1144. };
  1145. RTC.prototype.removeStreamListener = function (listener, eventType) {
  1146. if(!(eventType instanceof StreamEventTypes))
  1147. throw "Illegal argument";
  1148. this.eventEmitter.removeListener(eventType, listener);
  1149. };
  1150. RTC.addRTCReadyListener = function (listener) {
  1151. RTCUtils.eventEmitter.on(RTCEvents.RTC_READY, listener);
  1152. }
  1153. RTC.removeRTCReadyListener = function (listener) {
  1154. RTCUtils.eventEmitter.removeListener(RTCEvents.RTC_READY, listener);
  1155. }
  1156. RTC.isRTCReady = function () {
  1157. return rtcReady;
  1158. }
  1159. RTC.init = function (options) {
  1160. // In case of IE we continue from 'onReady' callback
  1161. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  1162. // once it is initialized.
  1163. var onReady = function () {
  1164. rtcReady = true;
  1165. RTCUtils.eventEmitter.emit(RTCEvents.RTC_READY, true);
  1166. };
  1167. RTCUtils.init(onReady, options || {});
  1168. // Call onReady() if Temasys plugin is not used
  1169. if (!RTCBrowserType.isTemasysPluginUsed()) {
  1170. onReady();
  1171. }
  1172. }
  1173. RTC.prototype.createLocalStreams = function (streams, change) {
  1174. for (var i = 0; i < streams.length; i++) {
  1175. var localStream = new JitsiLocalTrack(this, streams[i].stream,
  1176. this.eventEmitter, streams[i].videoType,
  1177. streams[i].isGUMStream);
  1178. this.localStreams.push(localStream);
  1179. if (streams[i].isMuted === true)
  1180. localStream.setMute(true);
  1181. if (streams[i].type == "audio") {
  1182. this.localAudio = localStream;
  1183. } else {
  1184. this.localVideo = localStream;
  1185. }
  1186. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  1187. if (change)
  1188. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  1189. this.eventEmitter.emit(eventType, localStream, streams[i].isMuted);
  1190. }
  1191. return this.localStreams;
  1192. };
  1193. RTC.prototype.removeLocalStream = function (stream) {
  1194. for(var i = 0; i < this.localStreams.length; i++) {
  1195. if(this.localStreams[i].getOriginalStream() === stream) {
  1196. delete this.localStreams[i];
  1197. return;
  1198. }
  1199. }
  1200. };
  1201. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  1202. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc,
  1203. RTCBrowserType.getBrowserType(), this.eventEmitter);
  1204. if(!data.peerjid)
  1205. return;
  1206. var jid = data.peerjid;
  1207. if(!this.remoteStreams[jid]) {
  1208. this.remoteStreams[jid] = {};
  1209. }
  1210. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  1211. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  1212. return remoteStream;
  1213. };
  1214. RTC.getPCConstraints = function () {
  1215. return RTCUtils.pc_constraints;
  1216. };
  1217. RTC.prototype.getUserMediaWithConstraints = function(um, success_callback,
  1218. failure_callback, resolution,
  1219. bandwidth, fps, desktopStream)
  1220. {
  1221. return RTCUtils.getUserMediaWithConstraints(this, um, success_callback,
  1222. failure_callback, resolution, bandwidth, fps, desktopStream);
  1223. };
  1224. RTC.attachMediaStream = function (elSelector, stream) {
  1225. RTCUtils.attachMediaStream(elSelector, stream);
  1226. };
  1227. RTC.getStreamID = function (stream) {
  1228. return RTCUtils.getStreamID(stream);
  1229. };
  1230. RTC.getVideoSrc = function (element) {
  1231. return RTCUtils.getVideoSrc(element);
  1232. };
  1233. RTC.setVideoSrc = function (element, src) {
  1234. RTCUtils.setVideoSrc(element, src);
  1235. };
  1236. RTC.prototype.getVideoElementName = function () {
  1237. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  1238. };
  1239. RTC.prototype.dispose = function() {
  1240. };
  1241. RTC.prototype.muteRemoteVideoStream = function (jid, value) {
  1242. var stream;
  1243. if(this.remoteStreams[jid] &&
  1244. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1245. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  1246. }
  1247. if(!stream)
  1248. return true;
  1249. if (value != stream.muted) {
  1250. stream.setMute(value);
  1251. return true;
  1252. }
  1253. return false;
  1254. };
  1255. RTC.prototype.switchVideoStreams = function (new_stream) {
  1256. this.localVideo.stream = new_stream;
  1257. this.localStreams = [];
  1258. //in firefox we have only one stream object
  1259. if (this.localAudio.getOriginalStream() != new_stream)
  1260. this.localStreams.push(this.localAudio);
  1261. this.localStreams.push(this.localVideo);
  1262. };
  1263. /**
  1264. * Creates <tt>JitsiTrack</tt> instance and replaces it with the local video.
  1265. * The method also handles the sdp changes.
  1266. * @param stream the new MediaStream received by the browser.
  1267. * @param isUsingScreenStream <tt>true</tt> if the stream is for desktop stream.
  1268. * @param callback - function that will be called after the operation is completed.
  1269. */
  1270. RTC.prototype.changeLocalVideo = function (stream, isUsingScreenStream, callback) {
  1271. var oldStream = this.localVideo.getOriginalStream();
  1272. var type = (isUsingScreenStream ? "screen" : "camera");
  1273. var localCallback = callback;
  1274. if(this.localVideo.isMuted() && this.localVideo.videoType !== type) {
  1275. localCallback = function() {
  1276. this.room.setVideoMute(false, function(mute) {
  1277. this.eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);
  1278. }.bind(this));
  1279. callback();
  1280. };
  1281. }
  1282. // FIXME: Workaround for FF/IE/Safari
  1283. if (stream && stream.videoStream) {
  1284. stream = stream.videoStream;
  1285. }
  1286. var videoStream = RTCUtils.createStream(stream, true);
  1287. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  1288. // Stop the stream to trigger onended event for old stream
  1289. oldStream.stop();
  1290. this.switchVideoStreams(videoStream, oldStream);
  1291. this.room.switchStreams(videoStream, oldStream,localCallback);
  1292. };
  1293. /**
  1294. * Creates <tt>JitsiTrack</tt> instance and replaces it with the local audio.
  1295. * The method also handles the sdp changes.
  1296. * @param stream the new MediaStream received by the browser.
  1297. * @param callback - function that will be called after the operation is completed.
  1298. */
  1299. RTC.prototype.changeLocalAudio = function (stream, callback) {
  1300. var oldStream = this.localAudio.getOriginalStream();
  1301. var newStream = RTCUtils.createStream(stream);
  1302. this.localAudio = this.createLocalStream(newStream, "audio", true);
  1303. // Stop the stream to trigger onended event for old stream
  1304. oldStream.stop();
  1305. this.room.switchStreams(newStream, oldStream, callback, true);
  1306. };
  1307. RTC.prototype.isVideoMuted = function (jid) {
  1308. if (jid === APP.xmpp.myJid()) {
  1309. var localVideo = APP.RTC.localVideo;
  1310. return (!localVideo || localVideo.isMuted());
  1311. } else {
  1312. if (!this.remoteStreams[jid] ||
  1313. !this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1314. return null;
  1315. }
  1316. return this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  1317. }
  1318. };
  1319. RTC.prototype.setVideoMute = function (mute, callback, options) {
  1320. if (!this.localVideo)
  1321. return;
  1322. if (mute == this.localVideo.isMuted())
  1323. {
  1324. APP.xmpp.sendVideoInfoPresence(mute);
  1325. if (callback)
  1326. callback(mute);
  1327. }
  1328. else
  1329. {
  1330. this.localVideo.setMute(mute);
  1331. this.room.setVideoMute(
  1332. mute,
  1333. callback,
  1334. options);
  1335. }
  1336. };
  1337. RTC.prototype.setDeviceAvailability = function (devices) {
  1338. if(!devices)
  1339. return;
  1340. if(devices.audio === true || devices.audio === false)
  1341. this.devices.audio = devices.audio;
  1342. if(devices.video === true || devices.video === false)
  1343. this.devices.video = devices.video;
  1344. this.eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  1345. };
  1346. module.exports = RTC;
  1347. },{"../../service/RTC/MediaStreamTypes":70,"../../service/RTC/RTCEvents.js":71,"../../service/RTC/StreamEventTypes.js":73,"../../service/desktopsharing/DesktopSharingEventTypes":75,"../../service/xmpp/XMPPEvents":76,"../desktopsharing/desktopsharing":17,"./DataChannels":9,"./JitsiLocalTrack.js":10,"./JitsiRemoteTrack.js":11,"./JitsiTrack":12,"./RTCBrowserType":14,"./RTCUtils.js":15,"events":77}],14:[function(require,module,exports){
  1348. var currentBrowser;
  1349. var browserVersion;
  1350. var RTCBrowserType = {
  1351. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  1352. RTC_BROWSER_OPERA: "rtc_browser.opera",
  1353. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  1354. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  1355. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  1356. getBrowserType: function () {
  1357. return currentBrowser;
  1358. },
  1359. isChrome: function () {
  1360. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  1361. },
  1362. isOpera: function () {
  1363. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  1364. },
  1365. isFirefox: function () {
  1366. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  1367. },
  1368. isIExplorer: function () {
  1369. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1370. },
  1371. isSafari: function () {
  1372. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  1373. },
  1374. isTemasysPluginUsed: function () {
  1375. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  1376. },
  1377. getFirefoxVersion: function () {
  1378. return RTCBrowserType.isFirefox() ? browserVersion : null;
  1379. },
  1380. getChromeVersion: function () {
  1381. return RTCBrowserType.isChrome() ? browserVersion : null;
  1382. },
  1383. usesPlanB: function() {
  1384. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  1385. RTCBrowserType.isTemasysPluginUsed();
  1386. },
  1387. usesUnifiedPlan: function() {
  1388. return RTCBrowserType.isFirefox();
  1389. }
  1390. // Add version getters for other browsers when needed
  1391. };
  1392. // detectOpera() must be called before detectChrome() !!!
  1393. // otherwise Opera wil be detected as Chrome
  1394. function detectChrome() {
  1395. if (navigator.webkitGetUserMedia) {
  1396. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  1397. var userAgent = navigator.userAgent.toLowerCase();
  1398. // We can assume that user agent is chrome, because it's
  1399. // enforced when 'ext' streaming method is set
  1400. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  1401. console.log("This appears to be Chrome, ver: " + ver);
  1402. return ver;
  1403. }
  1404. return null;
  1405. }
  1406. function detectOpera() {
  1407. var userAgent = navigator.userAgent;
  1408. if (userAgent.match(/Opera|OPR/)) {
  1409. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  1410. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  1411. console.info("This appears to be Opera, ver: " + version);
  1412. return version;
  1413. }
  1414. return null;
  1415. }
  1416. function detectFirefox() {
  1417. if (navigator.mozGetUserMedia) {
  1418. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1419. var version = parseInt(
  1420. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1421. console.log('This appears to be Firefox, ver: ' + version);
  1422. return version;
  1423. }
  1424. return null;
  1425. }
  1426. function detectSafari() {
  1427. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1428. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1429. console.info("This appears to be Safari");
  1430. // FIXME detect Safari version when needed
  1431. return 1;
  1432. }
  1433. return null;
  1434. }
  1435. function detectIE() {
  1436. var version;
  1437. var ua = window.navigator.userAgent;
  1438. var msie = ua.indexOf('MSIE ');
  1439. if (msie > 0) {
  1440. // IE 10 or older => return version number
  1441. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1442. }
  1443. var trident = ua.indexOf('Trident/');
  1444. if (!version && trident > 0) {
  1445. // IE 11 => return version number
  1446. var rv = ua.indexOf('rv:');
  1447. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1448. }
  1449. var edge = ua.indexOf('Edge/');
  1450. if (!version && edge > 0) {
  1451. // IE 12 => return version number
  1452. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1453. }
  1454. if (version) {
  1455. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1456. console.info("This appears to be IExplorer, ver: " + version);
  1457. }
  1458. return version;
  1459. }
  1460. function detectBrowser() {
  1461. var version;
  1462. var detectors = [
  1463. detectOpera,
  1464. detectChrome,
  1465. detectFirefox,
  1466. detectIE,
  1467. detectSafari
  1468. ];
  1469. // Try all browser detectors
  1470. for (var i = 0; i < detectors.length; i++) {
  1471. version = detectors[i]();
  1472. if (version)
  1473. return version;
  1474. }
  1475. console.error("Failed to detect browser type");
  1476. return undefined;
  1477. }
  1478. browserVersion = detectBrowser();
  1479. module.exports = RTCBrowserType;
  1480. },{}],15:[function(require,module,exports){
  1481. /* global config, require, attachMediaStream, getUserMedia */
  1482. var RTCBrowserType = require("./RTCBrowserType");
  1483. var Resolutions = require("../../service/RTC/Resolutions");
  1484. var AdapterJS = require("./adapter.screenshare");
  1485. var SDPUtil = require("../xmpp/SDPUtil");
  1486. var EventEmitter = require("events");
  1487. function DummyMediaStream(id) {
  1488. this.id = id;
  1489. this.label = id;
  1490. this.stop = function() { };
  1491. this.getAudioTracks = function() { return []; };
  1492. this.getVideoTracks = function() { return []; };
  1493. }
  1494. function getPreviousResolution(resolution) {
  1495. if(!Resolutions[resolution])
  1496. return null;
  1497. var order = Resolutions[resolution].order;
  1498. var res = null;
  1499. var resName = null;
  1500. for(var i in Resolutions) {
  1501. var tmp = Resolutions[i];
  1502. if(res == null || (res.order < tmp.order && tmp.order < order)) {
  1503. resName = i;
  1504. res = tmp;
  1505. }
  1506. }
  1507. return resName;
  1508. }
  1509. function setResolutionConstraints(constraints, resolution, isAndroid) {
  1510. if (Resolutions[resolution]) {
  1511. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1512. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1513. }
  1514. else if (isAndroid) {
  1515. // FIXME can't remember if the purpose of this was to always request
  1516. // low resolution on Android ? if yes it should be moved up front
  1517. constraints.video.mandatory.minWidth = 320;
  1518. constraints.video.mandatory.minHeight = 240;
  1519. constraints.video.mandatory.maxFrameRate = 15;
  1520. }
  1521. if (constraints.video.mandatory.minWidth)
  1522. constraints.video.mandatory.maxWidth =
  1523. constraints.video.mandatory.minWidth;
  1524. if (constraints.video.mandatory.minHeight)
  1525. constraints.video.mandatory.maxHeight =
  1526. constraints.video.mandatory.minHeight;
  1527. }
  1528. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1529. {
  1530. var constraints = {audio: false, video: false};
  1531. if (um.indexOf('video') >= 0) {
  1532. // same behaviour as true
  1533. constraints.video = { mandatory: {}, optional: [] };
  1534. constraints.video.optional.push({ googLeakyBucket: true });
  1535. setResolutionConstraints(constraints, resolution, isAndroid);
  1536. }
  1537. if (um.indexOf('audio') >= 0) {
  1538. if (!RTCBrowserType.isFirefox()) {
  1539. // same behaviour as true
  1540. constraints.audio = { mandatory: {}, optional: []};
  1541. // if it is good enough for hangouts...
  1542. constraints.audio.optional.push(
  1543. {googEchoCancellation: true},
  1544. {googAutoGainControl: true},
  1545. {googNoiseSupression: true},
  1546. {googHighpassFilter: true},
  1547. {googNoisesuppression2: true},
  1548. {googEchoCancellation2: true},
  1549. {googAutoGainControl2: true}
  1550. );
  1551. } else {
  1552. constraints.audio = true;
  1553. }
  1554. }
  1555. if (um.indexOf('screen') >= 0) {
  1556. if (RTCBrowserType.isChrome()) {
  1557. constraints.video = {
  1558. mandatory: {
  1559. chromeMediaSource: "screen",
  1560. googLeakyBucket: true,
  1561. maxWidth: window.screen.width,
  1562. maxHeight: window.screen.height,
  1563. maxFrameRate: 3
  1564. },
  1565. optional: []
  1566. };
  1567. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1568. constraints.video = {
  1569. optional: [
  1570. {
  1571. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1572. }
  1573. ]
  1574. };
  1575. } else {
  1576. console.error(
  1577. "'screen' WebRTC media source is supported only in Chrome" +
  1578. " and with Temasys plugin");
  1579. }
  1580. }
  1581. if (um.indexOf('desktop') >= 0) {
  1582. constraints.video = {
  1583. mandatory: {
  1584. chromeMediaSource: "desktop",
  1585. chromeMediaSourceId: desktopStream,
  1586. googLeakyBucket: true,
  1587. maxWidth: window.screen.width,
  1588. maxHeight: window.screen.height,
  1589. maxFrameRate: 3
  1590. },
  1591. optional: []
  1592. };
  1593. }
  1594. if (bandwidth) {
  1595. if (!constraints.video) {
  1596. //same behaviour as true
  1597. constraints.video = {mandatory: {}, optional: []};
  1598. }
  1599. constraints.video.optional.push({bandwidth: bandwidth});
  1600. }
  1601. if (fps) {
  1602. // for some cameras it might be necessary to request 30fps
  1603. // so they choose 30fps mjpg over 10fps yuy2
  1604. if (!constraints.video) {
  1605. // same behaviour as true;
  1606. constraints.video = {mandatory: {}, optional: []};
  1607. }
  1608. constraints.video.mandatory.minFrameRate = fps;
  1609. }
  1610. return constraints;
  1611. }
  1612. //Options parameter is to pass config options. Currently uses only "useIPv6".
  1613. var RTCUtils = {
  1614. eventEmitter: new EventEmitter(),
  1615. init: function (onTemasysPluginReady, options) {
  1616. var self = this;
  1617. if (RTCBrowserType.isFirefox()) {
  1618. var FFversion = RTCBrowserType.getFirefoxVersion();
  1619. if (FFversion >= 40) {
  1620. this.peerconnection = mozRTCPeerConnection;
  1621. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1622. this.pc_constraints = {};
  1623. this.attachMediaStream = function (element, stream) {
  1624. // srcObject is being standardized and FF will eventually
  1625. // support that unprefixed. FF also supports the
  1626. // "element.src = URL.createObjectURL(...)" combo, but that
  1627. // will be deprecated in favour of srcObject.
  1628. //
  1629. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1630. // https://github.com/webrtc/samples/issues/302
  1631. if (!element[0])
  1632. return;
  1633. element[0].mozSrcObject = stream;
  1634. element[0].play();
  1635. };
  1636. this.getStreamID = function (stream) {
  1637. var id = stream.id;
  1638. if (!id) {
  1639. var tracks = stream.getVideoTracks();
  1640. if (!tracks || tracks.length === 0) {
  1641. tracks = stream.getAudioTracks();
  1642. }
  1643. id = tracks[0].id;
  1644. }
  1645. return SDPUtil.filter_special_chars(id);
  1646. };
  1647. this.getVideoSrc = function (element) {
  1648. if (!element)
  1649. return null;
  1650. return element.mozSrcObject;
  1651. };
  1652. this.setVideoSrc = function (element, src) {
  1653. if (element)
  1654. element.mozSrcObject = src;
  1655. };
  1656. RTCSessionDescription = mozRTCSessionDescription;
  1657. RTCIceCandidate = mozRTCIceCandidate;
  1658. } else {
  1659. console.error(
  1660. "Firefox version too old: " + FFversion + ". Required >= 40.");
  1661. window.location.href = 'unsupported_browser.html';
  1662. return;
  1663. }
  1664. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1665. this.peerconnection = webkitRTCPeerConnection;
  1666. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1667. this.attachMediaStream = function (element, stream) {
  1668. element.attr('src', webkitURL.createObjectURL(stream));
  1669. };
  1670. this.getStreamID = function (stream) {
  1671. // streams from FF endpoints have the characters '{' and '}'
  1672. // that make jQuery choke.
  1673. return SDPUtil.filter_special_chars(stream.id);
  1674. };
  1675. this.getVideoSrc = function (element) {
  1676. if (!element)
  1677. return null;
  1678. return element.getAttribute("src");
  1679. };
  1680. this.setVideoSrc = function (element, src) {
  1681. if (element)
  1682. element.setAttribute("src", src);
  1683. };
  1684. // DTLS should now be enabled by default but..
  1685. this.pc_constraints = {'optional': [
  1686. {'DtlsSrtpKeyAgreement': 'true'}
  1687. ]};
  1688. if (options.useIPv6) {
  1689. // https://code.google.com/p/webrtc/issues/detail?id=2828
  1690. this.pc_constraints.optional.push({googIPv6: true});
  1691. }
  1692. if (navigator.userAgent.indexOf('Android') != -1) {
  1693. this.pc_constraints = {}; // disable DTLS on Android
  1694. }
  1695. if (!webkitMediaStream.prototype.getVideoTracks) {
  1696. webkitMediaStream.prototype.getVideoTracks = function () {
  1697. return this.videoTracks;
  1698. };
  1699. }
  1700. if (!webkitMediaStream.prototype.getAudioTracks) {
  1701. webkitMediaStream.prototype.getAudioTracks = function () {
  1702. return this.audioTracks;
  1703. };
  1704. }
  1705. }
  1706. // Detect IE/Safari
  1707. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1708. //AdapterJS.WebRTCPlugin.setLogLevel(
  1709. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1710. AdapterJS.webRTCReady(function (isPlugin) {
  1711. self.peerconnection = RTCPeerConnection;
  1712. self.getUserMedia = getUserMedia;
  1713. self.attachMediaStream = function (elSel, stream) {
  1714. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1715. return;
  1716. }
  1717. attachMediaStream(elSel[0], stream);
  1718. };
  1719. self.getStreamID = function (stream) {
  1720. var id = SDPUtil.filter_special_chars(stream.label);
  1721. return id;
  1722. };
  1723. self.getVideoSrc = function (element) {
  1724. if (!element) {
  1725. console.warn("Attempt to get video SRC of null element");
  1726. return null;
  1727. }
  1728. var children = element.children;
  1729. for (var i = 0; i !== children.length; ++i) {
  1730. if (children[i].name === 'streamId') {
  1731. return children[i].value;
  1732. }
  1733. }
  1734. //console.info(element.id + " SRC: " + src);
  1735. return null;
  1736. };
  1737. self.setVideoSrc = function (element, src) {
  1738. //console.info("Set video src: ", element, src);
  1739. if (!src) {
  1740. console.warn("Not attaching video stream, 'src' is null");
  1741. return;
  1742. }
  1743. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1744. var stream = AdapterJS.WebRTCPlugin.plugin
  1745. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1746. attachMediaStream(element, stream);
  1747. };
  1748. onTemasysPluginReady(isPlugin);
  1749. });
  1750. } else {
  1751. try {
  1752. console.log('Browser does not appear to be WebRTC-capable');
  1753. } catch (e) {
  1754. }
  1755. window.location.href = 'unsupported_browser.html';
  1756. }
  1757. },
  1758. getUserMediaWithConstraints: function (RTC, um, success_callback, failure_callback, resolution, bandwidth, fps, desktopStream) {
  1759. // Check if we are running on Android device
  1760. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1761. var constraints = getConstraints(
  1762. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1763. console.info("Get media constraints", constraints);
  1764. var self = this;
  1765. try {
  1766. this.getUserMedia(constraints,
  1767. function (stream) {
  1768. console.log('onUserMediaSuccess');
  1769. self.setAvailableDevices(RTC, um, true);
  1770. success_callback(stream);
  1771. },
  1772. function (error) {
  1773. self.setAvailableDevices(RTC, um, false);
  1774. console.warn('Failed to get access to local media. Error ',
  1775. error, constraints);
  1776. if (failure_callback) {
  1777. failure_callback(error, resolution);
  1778. }
  1779. });
  1780. } catch (e) {
  1781. console.error('GUM failed: ', e);
  1782. if (failure_callback) {
  1783. failure_callback(e);
  1784. }
  1785. }
  1786. },
  1787. setAvailableDevices: function (RTC, um, available) {
  1788. var devices = {};
  1789. if (um.indexOf("video") != -1) {
  1790. devices.video = available;
  1791. }
  1792. if (um.indexOf("audio") != -1) {
  1793. devices.audio = available;
  1794. }
  1795. RTC.setDeviceAvailability(devices);
  1796. },
  1797. /**
  1798. * Creates the local MediaStreams.
  1799. * @param RTC the rtc service.
  1800. * @param devices the devices that will be requested
  1801. * @param usageOptions object with devices that should be requested.
  1802. * @param resolution resolution constraints
  1803. * @param dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1804. * type: "audio" or "video", isMuted: true/false, videoType: "camera" or "desktop"}
  1805. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1806. * @returns {*} Promise object that will receive the new JitsiTracks
  1807. */
  1808. obtainAudioAndVideoPermissions: function (RTC, devices, usageOptions, resolution, dontCreateJitsiTracks) {
  1809. var self = this;
  1810. // Get AV
  1811. return new Promise(function (resolve, reject) {
  1812. var successCallback = function (stream) {
  1813. var streams = self.successCallback(RTC , stream, usageOptions);
  1814. resolve(dontCreateJitsiTracks? streams: RTC.createLocalStreams(streams));
  1815. };
  1816. if (!devices)
  1817. devices = ['audio', 'video'];
  1818. var newDevices = [];
  1819. if (usageOptions)
  1820. for (var i = 0; i < devices.length; i++) {
  1821. var device = devices[i];
  1822. if (usageOptions[device] === true)
  1823. newDevices.push(device);
  1824. }
  1825. else
  1826. newDevices = devices;
  1827. if (newDevices.length === 0) {
  1828. successCallback();
  1829. return;
  1830. }
  1831. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1832. // With FF/IE we can't split the stream into audio and video because FF
  1833. // doesn't support media stream constructors. So, we need to get the
  1834. // audio stream separately from the video stream using two distinct GUM
  1835. // calls. Not very user friendly :-( but we don't have many other
  1836. // options neither.
  1837. //
  1838. // Note that we pack those 2 streams in a single object and pass it to
  1839. // the successCallback method.
  1840. var obtainVideo = function (audioStream) {
  1841. self.getUserMediaWithConstraints(
  1842. RTC,
  1843. ['video'],
  1844. function (videoStream) {
  1845. return successCallback({
  1846. audioStream: audioStream,
  1847. videoStream: videoStream
  1848. });
  1849. },
  1850. function (error, resolution) {
  1851. console.error(
  1852. 'failed to obtain video stream - stop', error);
  1853. self.errorCallback(error, resolve, RTC, resolution, dontCreateJitsiTracks);
  1854. },
  1855. config.resolution || '360');
  1856. };
  1857. var obtainAudio = function () {
  1858. self.getUserMediaWithConstraints(
  1859. RTC,
  1860. ['audio'],
  1861. function (audioStream) {
  1862. if (newDevices.indexOf('video') !== -1)
  1863. obtainVideo(audioStream);
  1864. },
  1865. function (error) {
  1866. console.error(
  1867. 'failed to obtain audio stream - stop', error);
  1868. self.errorCallback(error, resolve, RTC, null, dontCreateJitsiTracks);
  1869. }
  1870. );
  1871. };
  1872. if (newDevices.indexOf('audio') !== -1) {
  1873. obtainAudio();
  1874. } else {
  1875. obtainVideo(null);
  1876. }
  1877. } else {
  1878. this.getUserMediaWithConstraints(
  1879. RTC,
  1880. newDevices,
  1881. function (stream) {
  1882. successCallback(stream);
  1883. },
  1884. function (error, resolution) {
  1885. self.errorCallback(error, resolve, RTC, resolution, dontCreateJitsiTracks);
  1886. },
  1887. resolution || '360');
  1888. }
  1889. }.bind(this));
  1890. },
  1891. /**
  1892. * Successful callback called from GUM.
  1893. * @param RTC the rtc service
  1894. * @param stream the new MediaStream
  1895. * @param usageOptions the list of the devices that should be queried.
  1896. * @returns {*}
  1897. */
  1898. successCallback: function (RTC, stream, usageOptions) {
  1899. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1900. // it's an object with two properties: audioStream, videoStream.
  1901. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1902. console.log('got', stream, stream.getAudioTracks().length,
  1903. stream.getVideoTracks().length);
  1904. return this.handleLocalStream(RTC, stream, usageOptions);
  1905. },
  1906. /**
  1907. * Error callback called from GUM. Retries the GUM call with different resolutions.
  1908. * @param error the error
  1909. * @param resolve the resolve funtion that will be called on success.
  1910. * @param RTC the rtc service
  1911. * @param currentResolution the last resolution used for GUM.
  1912. * @param dontCreateJitsiTracks if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1913. * type: "audio" or "video", isMuted: true/false, videoType: "camera" or "desktop"}
  1914. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1915. */
  1916. errorCallback: function (error, resolve, RTC, currentResolution, dontCreateJitsiTracks) {
  1917. var self = this;
  1918. console.error('failed to obtain audio/video stream - trying audio only', error);
  1919. var resolution = getPreviousResolution(currentResolution);
  1920. if (typeof error == "object" && error.constraintName && error.name
  1921. && (error.name == "ConstraintNotSatisfiedError" ||
  1922. error.name == "OverconstrainedError") &&
  1923. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1924. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1925. && resolution != null) {
  1926. self.getUserMediaWithConstraints(RTC, ['audio', 'video'],
  1927. function (stream) {
  1928. var streams = self.successCallback(RTC, stream);
  1929. resolve(dontCreateJitsiTracks? streams: RTC.createLocalStreams(streams));
  1930. }, function (error, resolution) {
  1931. return self.errorCallback(error, resolve, RTC, resolution, dontCreateJitsiTracks);
  1932. }, resolution);
  1933. }
  1934. else {
  1935. self.getUserMediaWithConstraints(
  1936. RTC,
  1937. ['audio'],
  1938. function (stream) {
  1939. var streams = self.successCallback(RTC, stream);
  1940. resolve(dontCreateJitsiTracks? streams: RTC.createLocalStreams(streams));
  1941. },
  1942. function (error) {
  1943. console.error('failed to obtain audio/video stream - stop',
  1944. error);
  1945. var streams = self.successCallback(RTC, null);
  1946. resolve(dontCreateJitsiTracks? streams: RTC.createLocalStreams(streams));
  1947. }
  1948. );
  1949. }
  1950. },
  1951. /**
  1952. * Handles the newly created Media Streams.
  1953. * @param service the rtc service
  1954. * @param stream the new Media Streams
  1955. * @param usageOptions the list of the devices that should be queried.
  1956. * @returns {*[]} Promise object with the new Media Streams.
  1957. */
  1958. handleLocalStream: function (service, stream, usageOptions) {
  1959. var audioStream, videoStream;
  1960. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1961. // an object with two properties: audioStream, videoStream.
  1962. if (window.webkitMediaStream) {
  1963. audioStream = new webkitMediaStream();
  1964. videoStream = new webkitMediaStream();
  1965. if (stream) {
  1966. var audioTracks = stream.getAudioTracks();
  1967. for (var i = 0; i < audioTracks.length; i++) {
  1968. audioStream.addTrack(audioTracks[i]);
  1969. }
  1970. var videoTracks = stream.getVideoTracks();
  1971. for (i = 0; i < videoTracks.length; i++) {
  1972. videoStream.addTrack(videoTracks[i]);
  1973. }
  1974. }
  1975. }
  1976. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  1977. if (stream && stream.audioStream)
  1978. audioStream = stream.audioStream;
  1979. else
  1980. audioStream = new DummyMediaStream("dummyAudio");
  1981. if (stream && stream.videoStream)
  1982. videoStream = stream.videoStream;
  1983. else
  1984. videoStream = new DummyMediaStream("dummyVideo");
  1985. }
  1986. var audioMuted = (usageOptions && usageOptions.audio === false),
  1987. videoMuted = (usageOptions && usageOptions.video === false);
  1988. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1989. videoGUM = (!usageOptions || usageOptions.video !== false);
  1990. return [
  1991. {stream: audioStream, type: "audio", isMuted: audioMuted, isGUMStream: audioGUM, videoType: null},
  1992. {stream: videoStream, type: "video", isMuted: videoMuted, isGUMStream: videoGUM, videoType: "camera"}
  1993. ];
  1994. },
  1995. createStream: function (stream, isVideo) {
  1996. var newStream = null;
  1997. if (window.webkitMediaStream) {
  1998. newStream = new webkitMediaStream();
  1999. if (newStream) {
  2000. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  2001. for (var i = 0; i < tracks.length; i++) {
  2002. newStream.addTrack(tracks[i]);
  2003. }
  2004. }
  2005. } else {
  2006. // FIXME: this is duplicated with 'handleLocalStream' !!!
  2007. if (stream) {
  2008. newStream = stream;
  2009. } else {
  2010. newStream =
  2011. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  2012. }
  2013. }
  2014. return newStream;
  2015. }
  2016. }
  2017. module.exports = RTCUtils;
  2018. },{"../../service/RTC/Resolutions":72,"../xmpp/SDPUtil":25,"./RTCBrowserType":14,"./adapter.screenshare":16,"events":77}],16:[function(require,module,exports){
  2019. /*! adapterjs - custom version from - 2015-08-12 */
  2020. // Adapter's interface.
  2021. var AdapterJS = AdapterJS || {};
  2022. // Browserify compatibility
  2023. if(typeof exports !== 'undefined') {
  2024. module.exports = AdapterJS;
  2025. }
  2026. AdapterJS.options = AdapterJS.options || {};
  2027. // uncomment to get virtual webcams
  2028. // AdapterJS.options.getAllCams = true;
  2029. // uncomment to prevent the install prompt when the plugin in not yet installed
  2030. // AdapterJS.options.hidePluginInstallPrompt = true;
  2031. // AdapterJS version
  2032. AdapterJS.VERSION = '0.11.1';
  2033. // This function will be called when the WebRTC API is ready to be used
  2034. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  2035. // the plugin
  2036. // You may Override this function to synchronise the start of your application
  2037. // with the WebRTC API being ready.
  2038. // If you decide not to override use this synchronisation, it may result in
  2039. // an extensive CPU usage on the plugin start (once per tab loaded)
  2040. // Params:
  2041. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  2042. //
  2043. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  2044. // The WebRTC API is ready.
  2045. // Override me and do whatever you want here
  2046. };
  2047. // Sets a callback function to be called when the WebRTC interface is ready.
  2048. // The first argument is the function to callback.\
  2049. // Throws an error if the first argument is not a function
  2050. AdapterJS.webRTCReady = function (callback) {
  2051. if (typeof callback !== 'function') {
  2052. throw new Error('Callback provided is not a function');
  2053. }
  2054. if (true === AdapterJS.onwebrtcreadyDone) {
  2055. // All WebRTC interfaces are ready, just call the callback
  2056. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  2057. } else {
  2058. // will be triggered automatically when your browser/plugin is ready.
  2059. AdapterJS.onwebrtcready = callback;
  2060. }
  2061. };
  2062. // Plugin namespace
  2063. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  2064. // The object to store plugin information
  2065. AdapterJS.WebRTCPlugin.pluginInfo = {
  2066. prefix : 'Tem',
  2067. plugName : 'TemWebRTCPlugin',
  2068. pluginId : 'plugin0',
  2069. type : 'application/x-temwebrtcplugin',
  2070. onload : '__TemWebRTCReady0',
  2071. portalLink : 'http://skylink.io/plugin/',
  2072. downloadLink : null, //set below
  2073. companyName: 'Temasys'
  2074. };
  2075. if(!!navigator.platform.match(/^Mac/i)) {
  2076. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  2077. }
  2078. else if(!!navigator.platform.match(/^Win/i)) {
  2079. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  2080. }
  2081. // Unique identifier of each opened page
  2082. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  2083. // Use this whenever you want to call the plugin.
  2084. AdapterJS.WebRTCPlugin.plugin = null;
  2085. // Set log level for the plugin once it is ready.
  2086. // The different values are
  2087. // This is an asynchronous function that will run when the plugin is ready
  2088. AdapterJS.WebRTCPlugin.setLogLevel = null;
  2089. // Defines webrtc's JS interface according to the plugin's implementation.
  2090. // Define plugin Browsers as WebRTC Interface.
  2091. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  2092. // This function detects whether or not a plugin is installed.
  2093. // Checks if Not IE (firefox, for example), else if it's IE,
  2094. // we're running IE and do something. If not it is not supported.
  2095. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  2096. // Lets adapter.js wait until the the document is ready before injecting the plugin
  2097. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  2098. // Inject the HTML DOM object element into the page.
  2099. AdapterJS.WebRTCPlugin.injectPlugin = null;
  2100. // States of readiness that the plugin goes through when
  2101. // being injected and stated
  2102. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  2103. NONE : 0, // no plugin use
  2104. INITIALIZING : 1, // Detected need for plugin
  2105. INJECTING : 2, // Injecting plugin
  2106. INJECTED: 3, // Plugin element injected but not usable yet
  2107. READY: 4 // Plugin ready to be used
  2108. };
  2109. // Current state of the plugin. You cannot use the plugin before this is
  2110. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  2111. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  2112. // True is AdapterJS.onwebrtcready was already called, false otherwise
  2113. // Used to make sure AdapterJS.onwebrtcready is only called once
  2114. AdapterJS.onwebrtcreadyDone = false;
  2115. // Log levels for the plugin.
  2116. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  2117. /*
  2118. Log outputs are prefixed in some cases.
  2119. INFO: Information reported by the plugin.
  2120. ERROR: Errors originating from within the plugin.
  2121. WEBRTC: Error originating from within the libWebRTC library
  2122. */
  2123. // From the least verbose to the most verbose
  2124. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  2125. NONE : 'NONE',
  2126. ERROR : 'ERROR',
  2127. WARNING : 'WARNING',
  2128. INFO: 'INFO',
  2129. VERBOSE: 'VERBOSE',
  2130. SENSITIVE: 'SENSITIVE'
  2131. };
  2132. // Does a waiting check before proceeding to load the plugin.
  2133. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  2134. // This methid will use an interval to wait for the plugin to be ready.
  2135. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  2136. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  2137. // This function will be called when plugin is ready. It sends necessary
  2138. // details to the plugin.
  2139. // The function will wait for the document to be ready and the set the
  2140. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  2141. // indicating that it can start being requested.
  2142. // This function is not in the IE/Safari condition brackets so that
  2143. // TemPluginLoaded function might be called on Chrome/Firefox.
  2144. // This function is the only private function that is not encapsulated to
  2145. // allow the plugin method to be called.
  2146. __TemWebRTCReady0 = function () {
  2147. if (document.readyState === 'complete') {
  2148. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  2149. AdapterJS.maybeThroughWebRTCReady();
  2150. } else {
  2151. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  2152. if (document.readyState === 'complete') {
  2153. // TODO: update comments, we wait for the document to be ready
  2154. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  2155. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  2156. AdapterJS.maybeThroughWebRTCReady();
  2157. }
  2158. }, 100);
  2159. }
  2160. };
  2161. AdapterJS.maybeThroughWebRTCReady = function() {
  2162. if (!AdapterJS.onwebrtcreadyDone) {
  2163. AdapterJS.onwebrtcreadyDone = true;
  2164. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  2165. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  2166. }
  2167. }
  2168. };
  2169. // Text namespace
  2170. AdapterJS.TEXT = {
  2171. PLUGIN: {
  2172. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  2173. 'to work on this browser.',
  2174. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  2175. BUTTON: 'Install Now'
  2176. },
  2177. REFRESH: {
  2178. REQUIRE_REFRESH: 'Please refresh page',
  2179. BUTTON: 'Refresh Page'
  2180. }
  2181. };
  2182. // The result of ice connection states.
  2183. // - starting: Ice connection is starting.
  2184. // - checking: Ice connection is checking.
  2185. // - connected Ice connection is connected.
  2186. // - completed Ice connection is connected.
  2187. // - done Ice connection has been completed.
  2188. // - disconnected Ice connection has been disconnected.
  2189. // - failed Ice connection has failed.
  2190. // - closed Ice connection is closed.
  2191. AdapterJS._iceConnectionStates = {
  2192. starting : 'starting',
  2193. checking : 'checking',
  2194. connected : 'connected',
  2195. completed : 'connected',
  2196. done : 'completed',
  2197. disconnected : 'disconnected',
  2198. failed : 'failed',
  2199. closed : 'closed'
  2200. };
  2201. //The IceConnection states that has been fired for each peer.
  2202. AdapterJS._iceConnectionFiredStates = [];
  2203. // Check if WebRTC Interface is defined.
  2204. AdapterJS.isDefined = null;
  2205. // This function helps to retrieve the webrtc detected browser information.
  2206. // This sets:
  2207. // - webrtcDetectedBrowser: The browser agent name.
  2208. // - webrtcDetectedVersion: The browser version.
  2209. // - webrtcDetectedType: The types of webRTC support.
  2210. // - 'moz': Mozilla implementation of webRTC.
  2211. // - 'webkit': WebKit implementation of webRTC.
  2212. // - 'plugin': Using the plugin implementation.
  2213. AdapterJS.parseWebrtcDetectedBrowser = function () {
  2214. var hasMatch, checkMatch = navigator.userAgent.match(
  2215. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  2216. if (/trident/i.test(checkMatch[1])) {
  2217. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  2218. webrtcDetectedBrowser = 'IE';
  2219. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  2220. } else if (checkMatch[1] === 'Chrome') {
  2221. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2222. if (hasMatch !== null) {
  2223. webrtcDetectedBrowser = 'opera';
  2224. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  2225. }
  2226. }
  2227. if (navigator.userAgent.indexOf('Safari')) {
  2228. if (typeof InstallTrigger !== 'undefined') {
  2229. webrtcDetectedBrowser = 'firefox';
  2230. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  2231. webrtcDetectedBrowser = 'IE';
  2232. } else if (
  2233. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  2234. webrtcDetectedBrowser = 'safari';
  2235. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  2236. webrtcDetectedBrowser = 'opera';
  2237. } else if (!!window.chrome) {
  2238. webrtcDetectedBrowser = 'chrome';
  2239. }
  2240. }
  2241. if (!webrtcDetectedBrowser) {
  2242. webrtcDetectedVersion = checkMatch[1];
  2243. }
  2244. if (!webrtcDetectedVersion) {
  2245. try {
  2246. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  2247. [navigator.appName, navigator.appVersion, '-?'];
  2248. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  2249. checkMatch.splice(1, 1, hasMatch[1]);
  2250. }
  2251. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  2252. } catch (error) { }
  2253. }
  2254. };
  2255. // To fix configuration as some browsers does not support
  2256. // the 'urls' attribute.
  2257. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  2258. if (pcConfig === null) {
  2259. return;
  2260. }
  2261. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  2262. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  2263. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  2264. delete pcConfig.iceServers[i].urls;
  2265. }
  2266. }
  2267. };
  2268. AdapterJS.addEvent = function(elem, evnt, func) {
  2269. if (elem.addEventListener) { // W3C DOM
  2270. elem.addEventListener(evnt, func, false);
  2271. } else if (elem.attachEvent) {// OLD IE DOM
  2272. elem.attachEvent('on'+evnt, func);
  2273. } else { // No much to do
  2274. elem[evnt] = func;
  2275. }
  2276. };
  2277. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  2278. // only inject once the page is ready
  2279. if (document.readyState !== 'complete') {
  2280. return;
  2281. }
  2282. var w = window;
  2283. var i = document.createElement('iframe');
  2284. i.style.position = 'fixed';
  2285. i.style.top = '-41px';
  2286. i.style.left = 0;
  2287. i.style.right = 0;
  2288. i.style.width = '100%';
  2289. i.style.height = '40px';
  2290. i.style.backgroundColor = '#ffffe1';
  2291. i.style.border = 'none';
  2292. i.style.borderBottom = '1px solid #888888';
  2293. i.style.zIndex = '9999999';
  2294. if(typeof i.style.webkitTransition === 'string') {
  2295. i.style.webkitTransition = 'all .5s ease-out';
  2296. } else if(typeof i.style.transition === 'string') {
  2297. i.style.transition = 'all .5s ease-out';
  2298. }
  2299. document.body.appendChild(i);
  2300. c = (i.contentWindow) ? i.contentWindow :
  2301. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  2302. c.document.open();
  2303. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  2304. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  2305. 'middle; cursor: default;">' + text + '</span>');
  2306. if(buttonText && buttonLink) {
  2307. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  2308. c.document.close();
  2309. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  2310. if (!!displayRefreshBar) {
  2311. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  2312. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  2313. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  2314. }
  2315. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  2316. e.preventDefault();
  2317. try {
  2318. event.cancelBubble = true;
  2319. } catch(error) { }
  2320. var pluginInstallInterval = setInterval(function(){
  2321. if(! isIE) {
  2322. navigator.plugins.refresh(false);
  2323. }
  2324. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2325. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2326. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2327. function() {
  2328. clearInterval(pluginInstallInterval);
  2329. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  2330. },
  2331. function() { //Does nothing because not used here
  2332. });
  2333. } , 500);
  2334. });
  2335. }else {
  2336. c.document.close();
  2337. }
  2338. AdapterJS.addEvent(c.document, 'click', function() {
  2339. w.document.body.removeChild(i);
  2340. });
  2341. setTimeout(function() {
  2342. if(typeof i.style.webkitTransform === 'string') {
  2343. i.style.webkitTransform = 'translateY(40px)';
  2344. } else if(typeof i.style.transform === 'string') {
  2345. i.style.transform = 'translateY(40px)';
  2346. } else {
  2347. i.style.top = '0px';
  2348. }
  2349. }, 300);
  2350. };
  2351. // -----------------------------------------------------------
  2352. // Detected webrtc implementation. Types are:
  2353. // - 'moz': Mozilla implementation of webRTC.
  2354. // - 'webkit': WebKit implementation of webRTC.
  2355. // - 'plugin': Using the plugin implementation.
  2356. webrtcDetectedType = null;
  2357. // Detected webrtc datachannel support. Types are:
  2358. // - 'SCTP': SCTP datachannel support.
  2359. // - 'RTP': RTP datachannel support.
  2360. webrtcDetectedDCSupport = null;
  2361. // Set the settings for creating DataChannels, MediaStream for
  2362. // Cross-browser compability.
  2363. // - This is only for SCTP based support browsers.
  2364. // the 'urls' attribute.
  2365. checkMediaDataChannelSettings =
  2366. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  2367. if (typeof callback !== 'function') {
  2368. return;
  2369. }
  2370. var beOfferer = true;
  2371. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  2372. // Nightly version does not require MozDontOfferDataChannel for interop
  2373. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  2374. var isPeerFirefox = peerBrowserAgent === 'firefox';
  2375. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  2376. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  2377. // Resends an updated version of constraints for MozDataChannel to work
  2378. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  2379. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  2380. try {
  2381. delete constraints.mandatory.MozDontOfferDataChannel;
  2382. } catch (error) {
  2383. console.error('Failed deleting MozDontOfferDataChannel');
  2384. console.error(error);
  2385. }
  2386. } else if ((isLocalFirefox && !isPeerFirefox)) {
  2387. constraints.mandatory.MozDontOfferDataChannel = true;
  2388. }
  2389. if (!isLocalFirefox) {
  2390. // temporary measure to remove Moz* constraints in non Firefox browsers
  2391. for (var prop in constraints.mandatory) {
  2392. if (constraints.mandatory.hasOwnProperty(prop)) {
  2393. if (prop.indexOf('Moz') !== -1) {
  2394. delete constraints.mandatory[prop];
  2395. }
  2396. }
  2397. }
  2398. }
  2399. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  2400. // interopability of the media stream
  2401. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  2402. beOfferer = false;
  2403. }
  2404. callback(beOfferer, constraints);
  2405. };
  2406. // Handles the differences for all browsers ice connection state output.
  2407. // - Tested outcomes are:
  2408. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  2409. // - Chrome (answerer) : 'checking' > 'connected'
  2410. // - Firefox (offerer) : 'checking' > 'connected'
  2411. // - Firefox (answerer): 'checking' > 'connected'
  2412. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  2413. if (typeof callback !== 'function') {
  2414. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  2415. return;
  2416. }
  2417. peerId = (peerId) ? peerId : 'peer';
  2418. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  2419. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  2420. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  2421. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  2422. AdapterJS._iceConnectionFiredStates[peerId] = [];
  2423. }
  2424. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  2425. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  2426. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  2427. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  2428. setTimeout(function () {
  2429. AdapterJS._iceConnectionFiredStates[peerId]
  2430. .push(AdapterJS._iceConnectionStates.done);
  2431. callback(AdapterJS._iceConnectionStates.done);
  2432. }, 1000);
  2433. }
  2434. callback(iceConnectionState);
  2435. }
  2436. return;
  2437. };
  2438. // Firefox:
  2439. // - Creates iceServer from the url for Firefox.
  2440. // - Create iceServer with stun url.
  2441. // - Create iceServer with turn url.
  2442. // - Ignore the transport parameter from TURN url for FF version <=27.
  2443. // - Return null for createIceServer if transport=tcp.
  2444. // - FF 27 and above supports transport parameters in TURN url,
  2445. // - So passing in the full url to create iceServer.
  2446. // Chrome:
  2447. // - Creates iceServer from the url for Chrome M33 and earlier.
  2448. // - Create iceServer with stun url.
  2449. // - Chrome M28 & above uses below TURN format.
  2450. // Plugin:
  2451. // - Creates Ice Server for Plugin Browsers
  2452. // - If Stun - Create iceServer with stun url.
  2453. // - Else - Create iceServer with turn url
  2454. // - This is a WebRTC Function
  2455. createIceServer = null;
  2456. // Firefox:
  2457. // - Creates IceServers for Firefox
  2458. // - Use .url for FireFox.
  2459. // - Multiple Urls support
  2460. // Chrome:
  2461. // - Creates iceServers from the urls for Chrome M34 and above.
  2462. // - .urls is supported since Chrome M34.
  2463. // - Multiple Urls support
  2464. // Plugin:
  2465. // - Creates Ice Servers for Plugin Browsers
  2466. // - Multiple Urls support
  2467. // - This is a WebRTC Function
  2468. createIceServers = null;
  2469. //------------------------------------------------------------
  2470. //The RTCPeerConnection object.
  2471. RTCPeerConnection = null;
  2472. // Creates RTCSessionDescription object for Plugin Browsers
  2473. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  2474. RTCSessionDescription : null;
  2475. // Creates RTCIceCandidate object for Plugin Browsers
  2476. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  2477. RTCIceCandidate : null;
  2478. // Get UserMedia (only difference is the prefix).
  2479. // Code from Adam Barth.
  2480. getUserMedia = null;
  2481. // Attach a media stream to an element.
  2482. attachMediaStream = null;
  2483. // Re-attach a media stream to an element.
  2484. reattachMediaStream = null;
  2485. // Detected browser agent name. Types are:
  2486. // - 'firefox': Firefox browser.
  2487. // - 'chrome': Chrome browser.
  2488. // - 'opera': Opera browser.
  2489. // - 'safari': Safari browser.
  2490. // - 'IE' - Internet Explorer browser.
  2491. webrtcDetectedBrowser = null;
  2492. // Detected browser version.
  2493. webrtcDetectedVersion = null;
  2494. // Check for browser types and react accordingly
  2495. if (navigator.mozGetUserMedia) {
  2496. webrtcDetectedBrowser = 'firefox';
  2497. webrtcDetectedVersion = parseInt(navigator
  2498. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2499. webrtcDetectedType = 'moz';
  2500. webrtcDetectedDCSupport = 'SCTP';
  2501. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2502. AdapterJS.maybeFixConfiguration(pcConfig);
  2503. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  2504. };
  2505. // The RTCSessionDescription object.
  2506. RTCSessionDescription = mozRTCSessionDescription;
  2507. window.RTCSessionDescription = RTCSessionDescription;
  2508. // The RTCIceCandidate object.
  2509. RTCIceCandidate = mozRTCIceCandidate;
  2510. window.RTCIceCandidate = RTCIceCandidate;
  2511. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  2512. navigator.getUserMedia = window.getUserMedia;
  2513. // Shim for MediaStreamTrack.getSources.
  2514. MediaStreamTrack.getSources = function(successCb) {
  2515. setTimeout(function() {
  2516. var infos = [
  2517. { kind: 'audio', id: 'default', label:'', facing:'' },
  2518. { kind: 'video', id: 'default', label:'', facing:'' }
  2519. ];
  2520. successCb(infos);
  2521. }, 0);
  2522. };
  2523. createIceServer = function (url, username, password) {
  2524. var iceServer = null;
  2525. var url_parts = url.split(':');
  2526. if (url_parts[0].indexOf('stun') === 0) {
  2527. iceServer = { url : url };
  2528. } else if (url_parts[0].indexOf('turn') === 0) {
  2529. if (webrtcDetectedVersion < 27) {
  2530. var turn_url_parts = url.split('?');
  2531. if (turn_url_parts.length === 1 ||
  2532. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2533. iceServer = {
  2534. url : turn_url_parts[0],
  2535. credential : password,
  2536. username : username
  2537. };
  2538. }
  2539. } else {
  2540. iceServer = {
  2541. url : url,
  2542. credential : password,
  2543. username : username
  2544. };
  2545. }
  2546. }
  2547. return iceServer;
  2548. };
  2549. createIceServers = function (urls, username, password) {
  2550. var iceServers = [];
  2551. for (i = 0; i < urls.length; i++) {
  2552. var iceServer = createIceServer(urls[i], username, password);
  2553. if (iceServer !== null) {
  2554. iceServers.push(iceServer);
  2555. }
  2556. }
  2557. return iceServers;
  2558. };
  2559. attachMediaStream = function (element, stream) {
  2560. element.mozSrcObject = stream;
  2561. if (stream !== null)
  2562. element.play();
  2563. return element;
  2564. };
  2565. reattachMediaStream = function (to, from) {
  2566. to.mozSrcObject = from.mozSrcObject;
  2567. to.play();
  2568. return to;
  2569. };
  2570. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2571. if (!callback) {
  2572. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2573. ': 1 argument required, but only 0 present.');
  2574. }
  2575. return callback([]);
  2576. };
  2577. // Fake get{Video,Audio}Tracks
  2578. if (!MediaStream.prototype.getVideoTracks) {
  2579. MediaStream.prototype.getVideoTracks = function () {
  2580. return [];
  2581. };
  2582. }
  2583. if (!MediaStream.prototype.getAudioTracks) {
  2584. MediaStream.prototype.getAudioTracks = function () {
  2585. return [];
  2586. };
  2587. }
  2588. AdapterJS.maybeThroughWebRTCReady();
  2589. } else if (navigator.webkitGetUserMedia) {
  2590. webrtcDetectedBrowser = 'chrome';
  2591. webrtcDetectedType = 'webkit';
  2592. webrtcDetectedVersion = parseInt(navigator
  2593. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2594. // check if browser is opera 20+
  2595. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2596. if (checkIfOpera !== null) {
  2597. webrtcDetectedBrowser = 'opera';
  2598. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2599. }
  2600. // check browser datachannel support
  2601. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2602. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2603. webrtcDetectedDCSupport = 'SCTP';
  2604. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2605. webrtcDetectedVersion > 24) {
  2606. webrtcDetectedDCSupport = 'RTP';
  2607. } else {
  2608. webrtcDetectedDCSupport = '';
  2609. }
  2610. createIceServer = function (url, username, password) {
  2611. var iceServer = null;
  2612. var url_parts = url.split(':');
  2613. if (url_parts[0].indexOf('stun') === 0) {
  2614. iceServer = { 'url' : url };
  2615. } else if (url_parts[0].indexOf('turn') === 0) {
  2616. iceServer = {
  2617. 'url' : url,
  2618. 'credential' : password,
  2619. 'username' : username
  2620. };
  2621. }
  2622. return iceServer;
  2623. };
  2624. createIceServers = function (urls, username, password) {
  2625. var iceServers = [];
  2626. if (webrtcDetectedVersion >= 34) {
  2627. iceServers = {
  2628. 'urls' : urls,
  2629. 'credential' : password,
  2630. 'username' : username
  2631. };
  2632. } else {
  2633. for (i = 0; i < urls.length; i++) {
  2634. var iceServer = createIceServer(urls[i], username, password);
  2635. if (iceServer !== null) {
  2636. iceServers.push(iceServer);
  2637. }
  2638. }
  2639. }
  2640. return iceServers;
  2641. };
  2642. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2643. if (webrtcDetectedVersion < 34) {
  2644. AdapterJS.maybeFixConfiguration(pcConfig);
  2645. }
  2646. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2647. };
  2648. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2649. navigator.getUserMedia = window.getUserMedia;
  2650. attachMediaStream = function (element, stream) {
  2651. if (typeof element.srcObject !== 'undefined') {
  2652. element.srcObject = stream;
  2653. } else if (typeof element.mozSrcObject !== 'undefined') {
  2654. element.mozSrcObject = stream;
  2655. } else if (typeof element.src !== 'undefined') {
  2656. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2657. } else {
  2658. console.log('Error attaching stream to element.');
  2659. }
  2660. return element;
  2661. };
  2662. reattachMediaStream = function (to, from) {
  2663. to.src = from.src;
  2664. return to;
  2665. };
  2666. AdapterJS.maybeThroughWebRTCReady();
  2667. } else { // TRY TO USE PLUGIN
  2668. // IE 9 is not offering an implementation of console.log until you open a console
  2669. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2670. /* jshint -W020 */
  2671. console = {} || console;
  2672. // Implemented based on console specs from MDN
  2673. // You may override these functions
  2674. console.log = function (arg) {};
  2675. console.info = function (arg) {};
  2676. console.error = function (arg) {};
  2677. console.dir = function (arg) {};
  2678. console.exception = function (arg) {};
  2679. console.trace = function (arg) {};
  2680. console.warn = function (arg) {};
  2681. console.count = function (arg) {};
  2682. console.debug = function (arg) {};
  2683. console.count = function (arg) {};
  2684. console.time = function (arg) {};
  2685. console.timeEnd = function (arg) {};
  2686. console.group = function (arg) {};
  2687. console.groupCollapsed = function (arg) {};
  2688. console.groupEnd = function (arg) {};
  2689. /* jshint +W020 */
  2690. }
  2691. webrtcDetectedType = 'plugin';
  2692. webrtcDetectedDCSupport = 'plugin';
  2693. AdapterJS.parseWebrtcDetectedBrowser();
  2694. isIE = webrtcDetectedBrowser === 'IE';
  2695. /* jshint -W035 */
  2696. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2697. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2698. /* empty because it needs to prevent the function from running. */
  2699. }
  2700. };
  2701. /* jshint +W035 */
  2702. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2703. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2704. // Call immediately if possible
  2705. // Once the plugin is set, the code will always take this path
  2706. callback();
  2707. } else {
  2708. // otherwise start a 100ms interval
  2709. var checkPluginReadyState = setInterval(function () {
  2710. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2711. clearInterval(checkPluginReadyState);
  2712. callback();
  2713. }
  2714. }, 100);
  2715. }
  2716. };
  2717. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2718. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2719. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2720. });
  2721. };
  2722. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2723. // only inject once the page is ready
  2724. if (document.readyState !== 'complete') {
  2725. return;
  2726. }
  2727. // Prevent multiple injections
  2728. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2729. return;
  2730. }
  2731. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2732. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2733. var frag = document.createDocumentFragment();
  2734. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2735. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2736. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2737. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2738. '<param name="pluginId" value="' +
  2739. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2740. '<param name="windowless" value="false" /> ' +
  2741. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2742. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload +
  2743. '" />' +
  2744. // uncomment to be able to use virtual cams
  2745. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2746. '</object>';
  2747. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2748. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2749. }
  2750. document.body.appendChild(frag);
  2751. // Need to re-fetch the plugin
  2752. AdapterJS.WebRTCPlugin.plugin =
  2753. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2754. } else {
  2755. // Load Plugin
  2756. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2757. AdapterJS.WebRTCPlugin.plugin.id =
  2758. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2759. // IE will only start the plugin if it's ACTUALLY visible
  2760. if (isIE) {
  2761. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2762. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2763. } else { // The size of the plugin on Safari should be 0x0px
  2764. // so that the autorisation prompt is at the top
  2765. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2766. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2767. }
  2768. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2769. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2770. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2771. '<param name="pluginId" value="' +
  2772. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2773. '<param name="windowless" value="false" /> ' +
  2774. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2775. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">';
  2776. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2777. }
  2778. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2779. };
  2780. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2781. function (comName, plugName, installedCb, notInstalledCb) {
  2782. if (!isIE) {
  2783. var pluginArray = navigator.plugins;
  2784. for (var i = 0; i < pluginArray.length; i++) {
  2785. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2786. installedCb();
  2787. return;
  2788. }
  2789. }
  2790. notInstalledCb();
  2791. } else {
  2792. try {
  2793. var axo = new ActiveXObject(comName + '.' + plugName);
  2794. } catch (e) {
  2795. notInstalledCb();
  2796. return;
  2797. }
  2798. installedCb();
  2799. }
  2800. };
  2801. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2802. if (AdapterJS.WebRTCPlugin.pluginState ===
  2803. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2804. console.error("WebRTC interface has been defined already");
  2805. return;
  2806. }
  2807. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2808. AdapterJS.isDefined = function (variable) {
  2809. return variable !== null && variable !== undefined;
  2810. };
  2811. createIceServer = function (url, username, password) {
  2812. var iceServer = null;
  2813. var url_parts = url.split(':');
  2814. if (url_parts[0].indexOf('stun') === 0) {
  2815. iceServer = {
  2816. 'url' : url,
  2817. 'hasCredentials' : false
  2818. };
  2819. } else if (url_parts[0].indexOf('turn') === 0) {
  2820. iceServer = {
  2821. 'url' : url,
  2822. 'hasCredentials' : true,
  2823. 'credential' : password,
  2824. 'username' : username
  2825. };
  2826. }
  2827. return iceServer;
  2828. };
  2829. createIceServers = function (urls, username, password) {
  2830. var iceServers = [];
  2831. for (var i = 0; i < urls.length; ++i) {
  2832. iceServers.push(createIceServer(urls[i], username, password));
  2833. }
  2834. return iceServers;
  2835. };
  2836. RTCSessionDescription = function (info) {
  2837. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2838. return AdapterJS.WebRTCPlugin.plugin.
  2839. ConstructSessionDescription(info.type, info.sdp);
  2840. };
  2841. RTCPeerConnection = function (servers, constraints) {
  2842. var iceServers = null;
  2843. if (servers) {
  2844. iceServers = servers.iceServers;
  2845. for (var i = 0; i < iceServers.length; i++) {
  2846. if (iceServers[i].urls && !iceServers[i].url) {
  2847. iceServers[i].url = iceServers[i].urls;
  2848. }
  2849. iceServers[i].hasCredentials = AdapterJS.
  2850. isDefined(iceServers[i].username) &&
  2851. AdapterJS.isDefined(iceServers[i].credential);
  2852. }
  2853. }
  2854. var mandatory = (constraints && constraints.mandatory) ?
  2855. constraints.mandatory : null;
  2856. var optional = (constraints && constraints.optional) ?
  2857. constraints.optional : null;
  2858. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2859. return AdapterJS.WebRTCPlugin.plugin.
  2860. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2861. iceServers, mandatory, optional);
  2862. };
  2863. MediaStreamTrack = {};
  2864. MediaStreamTrack.getSources = function (callback) {
  2865. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2866. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2867. });
  2868. };
  2869. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2870. constraints.audio = constraints.audio || false;
  2871. constraints.video = constraints.video || false;
  2872. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2873. AdapterJS.WebRTCPlugin.plugin.
  2874. getUserMedia(constraints, successCallback, failureCallback);
  2875. });
  2876. };
  2877. window.navigator.getUserMedia = window.getUserMedia;
  2878. attachMediaStream = function (element, stream) {
  2879. if (!element || !element.parentNode) {
  2880. return;
  2881. }
  2882. var streamId
  2883. if (stream === null) {
  2884. streamId = '';
  2885. }
  2886. else {
  2887. stream.enableSoundTracks(true);
  2888. streamId = stream.id;
  2889. }
  2890. if (element.nodeName.toLowerCase() !== 'audio') {
  2891. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2892. if (!element.isWebRTCPlugin || !element.isWebRTCPlugin()) {
  2893. var frag = document.createDocumentFragment();
  2894. var temp = document.createElement('div');
  2895. var classHTML = '';
  2896. if (element.className) {
  2897. classHTML = 'class="' + element.className + '" ';
  2898. } else if (element.attributes && element.attributes['class']) {
  2899. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2900. }
  2901. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2902. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2903. '<param name="pluginId" value="' + elementId + '" /> ' +
  2904. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2905. '<param name="windowless" value="true" /> ' +
  2906. '<param name="streamId" value="' + streamId + '" /> ' +
  2907. '</object>';
  2908. while (temp.firstChild) {
  2909. frag.appendChild(temp.firstChild);
  2910. }
  2911. var height = '';
  2912. var width = '';
  2913. if (element.getBoundingClientRect) {
  2914. var rectObject = element.getBoundingClientRect();
  2915. width = rectObject.width + 'px';
  2916. height = rectObject.height + 'px';
  2917. }
  2918. else if (element.width) {
  2919. width = element.width;
  2920. height = element.height;
  2921. } else {
  2922. // TODO: What scenario could bring us here?
  2923. }
  2924. element.parentNode.insertBefore(frag, element);
  2925. frag = document.getElementById(elementId);
  2926. frag.width = width;
  2927. frag.height = height;
  2928. element.parentNode.removeChild(element);
  2929. } else {
  2930. var children = element.children;
  2931. for (var i = 0; i !== children.length; ++i) {
  2932. if (children[i].name === 'streamId') {
  2933. children[i].value = streamId;
  2934. break;
  2935. }
  2936. }
  2937. element.setStreamId(streamId);
  2938. }
  2939. var newElement = document.getElementById(elementId);
  2940. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2941. if (isIE) { // on IE the event needs to be plugged manually
  2942. newElement.attachEvent('onplaying', newElement.onplaying);
  2943. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2944. newElement._TemOnClick = function (id) {
  2945. var arg = {
  2946. srcElement : document.getElementById(id)
  2947. };
  2948. newElement.onclick(arg);
  2949. };
  2950. }
  2951. return newElement;
  2952. } else {
  2953. return element;
  2954. }
  2955. };
  2956. reattachMediaStream = function (to, from) {
  2957. var stream = null;
  2958. var children = from.children;
  2959. for (var i = 0; i !== children.length; ++i) {
  2960. if (children[i].name === 'streamId') {
  2961. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2962. stream = AdapterJS.WebRTCPlugin.plugin
  2963. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2964. break;
  2965. }
  2966. }
  2967. if (stream !== null) {
  2968. return attachMediaStream(to, stream);
  2969. } else {
  2970. console.log('Could not find the stream associated with this element');
  2971. }
  2972. };
  2973. RTCIceCandidate = function (candidate) {
  2974. if (!candidate.sdpMid) {
  2975. candidate.sdpMid = '';
  2976. }
  2977. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2978. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2979. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2980. );
  2981. };
  2982. // inject plugin
  2983. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2984. AdapterJS.WebRTCPlugin.injectPlugin();
  2985. };
  2986. // This function will be called if the plugin is needed (browser different
  2987. // from Chrome or Firefox), but the plugin is not installed.
  2988. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2989. function() {
  2990. AdapterJS.addEvent(document,
  2991. 'readystatechange',
  2992. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2993. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2994. };
  2995. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  2996. if (AdapterJS.options.hidePluginInstallPrompt) {
  2997. return;
  2998. }
  2999. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  3000. if(downloadLink) { // if download link
  3001. var popupString;
  3002. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  3003. popupString = 'This website requires you to install the ' +
  3004. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  3005. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  3006. ' WebRTC Plugin</a>' +
  3007. ' to work on this browser.';
  3008. } else { // no portal link, just print a generic explanation
  3009. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  3010. }
  3011. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  3012. } else { // no download link, just print a generic explanation
  3013. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  3014. }
  3015. };
  3016. // Try to detect the plugin and act accordingly
  3017. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3018. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3019. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3020. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  3021. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  3022. }
  3023. (function () {
  3024. 'use strict';
  3025. var baseGetUserMedia = null;
  3026. AdapterJS.TEXT.EXTENSION = {
  3027. REQUIRE_INSTALLATION_FF: 'To enable screensharing you need to install the Skylink WebRTC tools Firefox Add-on.',
  3028. REQUIRE_INSTALLATION_CHROME: 'To enable screensharing you need to install the Skylink WebRTC tools Chrome Extension.',
  3029. REQUIRE_REFRESH: 'Please refresh this page after the Skylink WebRTC tools extension has been installed.',
  3030. BUTTON_FF: 'Install Now',
  3031. BUTTON_CHROME: 'Go to Chrome Web Store'
  3032. };
  3033. var clone = function(obj) {
  3034. if (null == obj || "object" != typeof obj) return obj;
  3035. var copy = obj.constructor();
  3036. for (var attr in obj) {
  3037. if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  3038. }
  3039. return copy;
  3040. };
  3041. if (window.navigator.mozGetUserMedia) {
  3042. baseGetUserMedia = window.navigator.getUserMedia;
  3043. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  3044. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  3045. // intercepting screensharing requests
  3046. if (constraints.video.mediaSource !== 'screen' && constraints.video.mediaSource !== 'window') {
  3047. throw new Error('Only "screen" and "window" option is available as mediaSource');
  3048. }
  3049. var updatedConstraints = clone(constraints);
  3050. //constraints.video.mediaSource = constraints.video.mediaSource;
  3051. updatedConstraints.video.mozMediaSource = updatedConstraints.video.mediaSource;
  3052. // so generally, it requires for document.readyState to be completed before the getUserMedia could be invoked.
  3053. // strange but this works anyway
  3054. var checkIfReady = setInterval(function () {
  3055. if (document.readyState === 'complete') {
  3056. clearInterval(checkIfReady);
  3057. baseGetUserMedia(updatedConstraints, successCb, function (error) {
  3058. if (error.name === 'PermissionDeniedError' && window.parent.location.protocol === 'https:') {
  3059. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_FF,
  3060. AdapterJS.TEXT.EXTENSION.BUTTON_FF,
  3061. 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname, false, true);
  3062. //window.location.href = 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname;
  3063. } else {
  3064. failureCb(error);
  3065. }
  3066. });
  3067. }
  3068. }, 1);
  3069. } else { // regular GetUserMediaRequest
  3070. baseGetUserMedia(constraints, successCb, failureCb);
  3071. }
  3072. };
  3073. getUserMedia = navigator.getUserMedia;
  3074. } else if (window.navigator.webkitGetUserMedia) {
  3075. baseGetUserMedia = window.navigator.getUserMedia;
  3076. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  3077. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  3078. if (window.webrtcDetectedBrowser !== 'chrome') {
  3079. throw new Error('Current browser does not support screensharing');
  3080. }
  3081. // would be fine since no methods
  3082. var updatedConstraints = clone(constraints);
  3083. var chromeCallback = function(error, sourceId) {
  3084. if(!error) {
  3085. updatedConstraints.video.mandatory = updatedConstraints.video.mandatory || {};
  3086. updatedConstraints.video.mandatory.chromeMediaSource = 'desktop';
  3087. updatedConstraints.video.mandatory.maxWidth = window.screen.width > 1920 ? window.screen.width : 1920;
  3088. updatedConstraints.video.mandatory.maxHeight = window.screen.height > 1080 ? window.screen.height : 1080;
  3089. if (sourceId) {
  3090. updatedConstraints.video.mandatory.chromeMediaSourceId = sourceId;
  3091. }
  3092. delete updatedConstraints.video.mediaSource;
  3093. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  3094. } else {
  3095. if (error === 'permission-denied') {
  3096. throw new Error('Permission denied for screen retrieval');
  3097. } else {
  3098. throw new Error('Failed retrieving selected screen');
  3099. }
  3100. }
  3101. };
  3102. var onIFrameCallback = function (event) {
  3103. if (!event.data) {
  3104. return;
  3105. }
  3106. if (event.data.chromeMediaSourceId) {
  3107. if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
  3108. chromeCallback('permission-denied');
  3109. } else {
  3110. chromeCallback(null, event.data.chromeMediaSourceId);
  3111. }
  3112. }
  3113. if (event.data.chromeExtensionStatus) {
  3114. if (event.data.chromeExtensionStatus === 'not-installed') {
  3115. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_CHROME,
  3116. AdapterJS.TEXT.EXTENSION.BUTTON_CHROME,
  3117. event.data.data, true, true);
  3118. } else {
  3119. chromeCallback(event.data.chromeExtensionStatus, null);
  3120. }
  3121. }
  3122. // this event listener is no more needed
  3123. window.removeEventListener('message', onIFrameCallback);
  3124. };
  3125. window.addEventListener('message', onIFrameCallback);
  3126. postFrameMessage({
  3127. captureSourceId: true
  3128. });
  3129. } else {
  3130. baseGetUserMedia(constraints, successCb, failureCb);
  3131. }
  3132. };
  3133. getUserMedia = navigator.getUserMedia;
  3134. } else {
  3135. baseGetUserMedia = window.navigator.getUserMedia;
  3136. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  3137. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  3138. // would be fine since no methods
  3139. var updatedConstraints = clone(constraints);
  3140. // wait for plugin to be ready
  3141. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3142. // check if screensharing feature is available
  3143. if (!!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature &&
  3144. !!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3145. // set the constraints
  3146. updatedConstraints.video.optional = updatedConstraints.video.optional || [];
  3147. updatedConstraints.video.optional.push({
  3148. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey || 'Screensharing'
  3149. });
  3150. delete updatedConstraints.video.mediaSource;
  3151. } else {
  3152. throw new Error('Your WebRTC plugin does not support screensharing');
  3153. }
  3154. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  3155. });
  3156. } else {
  3157. baseGetUserMedia(constraints, successCb, failureCb);
  3158. }
  3159. };
  3160. getUserMedia = window.navigator.getUserMedia;
  3161. }
  3162. if (window.webrtcDetectedBrowser === 'chrome') {
  3163. var iframe = document.createElement('iframe');
  3164. iframe.onload = function() {
  3165. iframe.isLoaded = true;
  3166. };
  3167. iframe.src = 'https://cdn.temasys.com.sg/skylink/extensions/detectRTC.html';
  3168. //'https://temasys-cdn.s3.amazonaws.com/skylink/extensions/detection-script-dev/detectRTC.html';
  3169. iframe.style.display = 'none';
  3170. (document.body || document.documentElement).appendChild(iframe);
  3171. var postFrameMessage = function (object) {
  3172. object = object || {};
  3173. if (!iframe.isLoaded) {
  3174. setTimeout(function () {
  3175. iframe.contentWindow.postMessage(object, '*');
  3176. }, 100);
  3177. return;
  3178. }
  3179. iframe.contentWindow.postMessage(object, '*');
  3180. };
  3181. }
  3182. })();
  3183. },{}],17:[function(require,module,exports){
  3184. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  3185. getUserMediaWithConstraints */
  3186. /**
  3187. * Indicates that desktop stream is currently in use(for toggle purpose).
  3188. * @type {boolean}
  3189. */
  3190. var isUsingScreenStream = false;
  3191. /**
  3192. * Indicates that switch stream operation is in progress and prevent from
  3193. * triggering new events.
  3194. * @type {boolean}
  3195. */
  3196. var switchInProgress = false;
  3197. /**
  3198. * Method used to get screen sharing stream.
  3199. *
  3200. * @type {function (stream_callback, failure_callback}
  3201. */
  3202. var obtainDesktopStream = null;
  3203. /**
  3204. * Indicates whether desktop sharing extension is installed.
  3205. * @type {boolean}
  3206. */
  3207. var extInstalled = false;
  3208. /**
  3209. * Indicates whether update of desktop sharing extension is required.
  3210. * @type {boolean}
  3211. */
  3212. var extUpdateRequired = false;
  3213. var AdapterJS = require("../RTC/adapter.screenshare");
  3214. var EventEmitter = require("events");
  3215. var eventEmitter = new EventEmitter();
  3216. var DesktopSharingEventTypes
  3217. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  3218. var RTCBrowserType = require("../RTC/RTCBrowserType");
  3219. var RTCEvents = require("../../service/RTC/RTCEvents");
  3220. /**
  3221. * Method obtains desktop stream from WebRTC 'screen' source.
  3222. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  3223. */
  3224. function obtainWebRTCScreen(streamCallback, failCallback) {
  3225. APP.RTC.getUserMediaWithConstraints(
  3226. ['screen'],
  3227. streamCallback,
  3228. failCallback
  3229. );
  3230. }
  3231. /**
  3232. * Constructs inline install URL for Chrome desktop streaming extension.
  3233. * The 'chromeExtensionId' must be defined in config.js.
  3234. * @returns {string}
  3235. */
  3236. function getWebStoreInstallUrl()
  3237. {
  3238. return "https://chrome.google.com/webstore/detail/" +
  3239. config.chromeExtensionId;
  3240. }
  3241. /**
  3242. * Checks whether extension update is required.
  3243. * @param minVersion minimal required version
  3244. * @param extVersion current extension version
  3245. * @returns {boolean}
  3246. */
  3247. function isUpdateRequired(minVersion, extVersion)
  3248. {
  3249. try
  3250. {
  3251. var s1 = minVersion.split('.');
  3252. var s2 = extVersion.split('.');
  3253. var len = Math.max(s1.length, s2.length);
  3254. for (var i = 0; i < len; i++)
  3255. {
  3256. var n1 = 0,
  3257. n2 = 0;
  3258. if (i < s1.length)
  3259. n1 = parseInt(s1[i]);
  3260. if (i < s2.length)
  3261. n2 = parseInt(s2[i]);
  3262. if (isNaN(n1) || isNaN(n2))
  3263. {
  3264. return true;
  3265. }
  3266. else if (n1 !== n2)
  3267. {
  3268. return n1 > n2;
  3269. }
  3270. }
  3271. // will happen if boths version has identical numbers in
  3272. // their components (even if one of them is longer, has more components)
  3273. return false;
  3274. }
  3275. catch (e)
  3276. {
  3277. console.error("Failed to parse extension version", e);
  3278. APP.UI.messageHandler.showError("dialog.error",
  3279. "dialog.detectext");
  3280. return true;
  3281. }
  3282. }
  3283. function checkChromeExtInstalled(callback) {
  3284. if (!chrome.runtime) {
  3285. // No API, so no extension for sure
  3286. callback(false, false);
  3287. return;
  3288. }
  3289. chrome.runtime.sendMessage(
  3290. config.chromeExtensionId,
  3291. { getVersion: true },
  3292. function (response) {
  3293. if (!response || !response.version) {
  3294. // Communication failure - assume that no endpoint exists
  3295. console.warn(
  3296. "Extension not installed?: ", chrome.runtime.lastError);
  3297. callback(false, false);
  3298. return;
  3299. }
  3300. // Check installed extension version
  3301. var extVersion = response.version;
  3302. console.log('Extension version is: ' + extVersion);
  3303. var updateRequired
  3304. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  3305. callback(!updateRequired, updateRequired);
  3306. }
  3307. );
  3308. }
  3309. function doGetStreamFromExtension(streamCallback, failCallback) {
  3310. // Sends 'getStream' msg to the extension.
  3311. // Extension id must be defined in the config.
  3312. chrome.runtime.sendMessage(
  3313. config.chromeExtensionId,
  3314. { getStream: true, sources: config.desktopSharingSources },
  3315. function (response) {
  3316. if (!response) {
  3317. failCallback(chrome.runtime.lastError);
  3318. return;
  3319. }
  3320. console.log("Response from extension: " + response);
  3321. if (response.streamId) {
  3322. APP.RTC.getUserMediaWithConstraints(
  3323. ['desktop'],
  3324. function (stream) {
  3325. streamCallback(stream);
  3326. },
  3327. failCallback,
  3328. null, null, null,
  3329. response.streamId);
  3330. } else {
  3331. failCallback("Extension failed to get the stream");
  3332. }
  3333. }
  3334. );
  3335. }
  3336. /**
  3337. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  3338. * stream for returned stream token.
  3339. */
  3340. function obtainScreenFromExtension(streamCallback, failCallback) {
  3341. if (extInstalled) {
  3342. doGetStreamFromExtension(streamCallback, failCallback);
  3343. } else {
  3344. if (extUpdateRequired) {
  3345. alert(
  3346. 'Jitsi Desktop Streamer requires update. ' +
  3347. 'Changes will take effect after next Chrome restart.');
  3348. }
  3349. chrome.webstore.install(
  3350. getWebStoreInstallUrl(),
  3351. function (arg) {
  3352. console.log("Extension installed successfully", arg);
  3353. extInstalled = true;
  3354. // We need to give a moment for the endpoint to become available
  3355. window.setTimeout(function () {
  3356. doGetStreamFromExtension(streamCallback, failCallback);
  3357. }, 500);
  3358. },
  3359. function (arg) {
  3360. console.log("Failed to install the extension", arg);
  3361. failCallback(arg);
  3362. APP.UI.messageHandler.showError("dialog.error",
  3363. "dialog.failtoinstall");
  3364. }
  3365. );
  3366. }
  3367. }
  3368. /**
  3369. * Call this method to toggle desktop sharing feature.
  3370. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  3371. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  3372. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  3373. * enabled), pass any other string or nothing in order to disable this
  3374. * feature completely.
  3375. */
  3376. function setDesktopSharing(method) {
  3377. obtainDesktopStream = null;
  3378. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  3379. // care about 'method' parameter
  3380. if (RTCBrowserType.isTemasysPluginUsed()) {
  3381. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  3382. console.info("Screensharing not supported by this plugin version");
  3383. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3384. console.info(
  3385. "Screensharing not available with Temasys plugin on this site");
  3386. } else {
  3387. obtainDesktopStream = obtainWebRTCScreen;
  3388. console.info("Using Temasys plugin for desktop sharing");
  3389. }
  3390. } else if (RTCBrowserType.isChrome()) {
  3391. if (method == "ext") {
  3392. if (RTCBrowserType.getChromeVersion() >= 34) {
  3393. obtainDesktopStream = obtainScreenFromExtension;
  3394. console.info("Using Chrome extension for desktop sharing");
  3395. initChromeExtension();
  3396. } else {
  3397. console.info("Chrome extension not supported until ver 34");
  3398. }
  3399. } else if (method == "webrtc") {
  3400. obtainDesktopStream = obtainWebRTCScreen;
  3401. console.info("Using Chrome WebRTC for desktop sharing");
  3402. }
  3403. }
  3404. if (!obtainDesktopStream) {
  3405. console.info("Desktop sharing disabled");
  3406. }
  3407. }
  3408. /**
  3409. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3410. * config.js to support inline installs. Host site must be selected as main
  3411. * website of published extension.
  3412. */
  3413. function initInlineInstalls()
  3414. {
  3415. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  3416. }
  3417. function initChromeExtension() {
  3418. // Initialize Chrome extension inline installs
  3419. initInlineInstalls();
  3420. // Check if extension is installed
  3421. checkChromeExtInstalled(function (installed, updateRequired) {
  3422. extInstalled = installed;
  3423. extUpdateRequired = updateRequired;
  3424. console.info(
  3425. "Chrome extension installed: " + extInstalled +
  3426. " updateRequired: " + extUpdateRequired);
  3427. });
  3428. }
  3429. function getVideoStreamFailed(error) {
  3430. console.error("Failed to obtain the stream to switch to", error);
  3431. switchInProgress = false;
  3432. isUsingScreenStream = false;
  3433. newStreamCreated(null);
  3434. }
  3435. function getDesktopStreamFailed(error) {
  3436. console.error("Failed to obtain the stream to switch to", error);
  3437. switchInProgress = false;
  3438. }
  3439. function streamSwitchDone() {
  3440. switchInProgress = false;
  3441. eventEmitter.emit(
  3442. DesktopSharingEventTypes.SWITCHING_DONE,
  3443. isUsingScreenStream);
  3444. }
  3445. function newStreamCreated(stream)
  3446. {
  3447. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  3448. stream, isUsingScreenStream, streamSwitchDone);
  3449. }
  3450. function onEndedHandler(stream) {
  3451. if (!switchInProgress && isUsingScreenStream) {
  3452. APP.desktopsharing.toggleScreenSharing();
  3453. }
  3454. //FIXME: to be verified
  3455. if (stream.removeEventListener) {
  3456. stream.removeEventListener('ended', onEndedHandler);
  3457. } else {
  3458. stream.detachEvent('ended', onEndedHandler);
  3459. }
  3460. }
  3461. // Called when RTC finishes initialization
  3462. function onWebRtcReady() {
  3463. setDesktopSharing(config.desktopSharing);
  3464. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  3465. }
  3466. module.exports = {
  3467. isUsingScreenStream: function () {
  3468. return isUsingScreenStream;
  3469. },
  3470. /**
  3471. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  3472. * and enabled.
  3473. */
  3474. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  3475. init: function () {
  3476. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  3477. },
  3478. addListener: function (listener, type)
  3479. {
  3480. eventEmitter.on(type, listener);
  3481. },
  3482. removeListener: function (listener, type) {
  3483. eventEmitter.removeListener(type, listener);
  3484. },
  3485. /*
  3486. * Toggles screen sharing.
  3487. */
  3488. toggleScreenSharing: function () {
  3489. if (switchInProgress || !obtainDesktopStream) {
  3490. console.warn("Switch in progress or no method defined");
  3491. return;
  3492. }
  3493. switchInProgress = true;
  3494. if (!isUsingScreenStream)
  3495. {
  3496. // Switch to desktop stream
  3497. obtainDesktopStream(
  3498. function (stream) {
  3499. // We now use screen stream
  3500. isUsingScreenStream = true;
  3501. // Hook 'ended' event to restore camera
  3502. // when screen stream stops
  3503. //FIXME: to be verified
  3504. if (stream.addEventListener) {
  3505. stream.addEventListener('ended', function () {
  3506. onEndedHandler(stream);
  3507. });
  3508. } else {
  3509. stream.attachEvent('ended', function () {
  3510. onEndedHandler(stream);
  3511. });
  3512. }
  3513. newStreamCreated(stream);
  3514. },
  3515. getDesktopStreamFailed);
  3516. } else {
  3517. // Disable screen stream
  3518. APP.RTC.getUserMediaWithConstraints(
  3519. ['video'],
  3520. function (stream) {
  3521. // We are now using camera stream
  3522. isUsingScreenStream = false;
  3523. newStreamCreated(stream);
  3524. },
  3525. getVideoStreamFailed, config.resolution || '360'
  3526. );
  3527. }
  3528. }
  3529. };
  3530. },{"../../service/RTC/RTCEvents":71,"../../service/desktopsharing/DesktopSharingEventTypes":75,"../RTC/RTCBrowserType":14,"../RTC/adapter.screenshare":16,"events":77}],18:[function(require,module,exports){
  3531. function supportsLocalStorage() {
  3532. try {
  3533. return 'localStorage' in window && window.localStorage !== null;
  3534. } catch (e) {
  3535. console.log("localstorage is not supported");
  3536. return false;
  3537. }
  3538. }
  3539. function generateUniqueId() {
  3540. function _p8() {
  3541. return (Math.random().toString(16) + "000000000").substr(2, 8);
  3542. }
  3543. return _p8() + _p8() + _p8() + _p8();
  3544. }
  3545. function Settings(conferenceID) {
  3546. this.email = '';
  3547. this.displayName = '';
  3548. this.userId;
  3549. this.language = null;
  3550. this.confSettings = null;
  3551. this.conferenceID = conferenceID;
  3552. if (supportsLocalStorage()) {
  3553. if(!window.localStorage.getItem(conferenceID))
  3554. this.confSettings = {};
  3555. else
  3556. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  3557. if(!this.confSettings.jitsiMeetId) {
  3558. this.confSettings.jitsiMeetId = generateUniqueId();
  3559. console.log("generated id",
  3560. this.confSettings.jitsiMeetId);
  3561. this.save();
  3562. }
  3563. this.userId = this.confSettings.jitsiMeetId || '';
  3564. this.email = this.confSettings.email || '';
  3565. this.displayName = this.confSettings.displayname || '';
  3566. this.language = this.confSettings.language;
  3567. } else {
  3568. console.log("local storage is not supported");
  3569. this.userId = generateUniqueId();
  3570. }
  3571. }
  3572. Settings.prototype.save = function () {
  3573. if(!supportsLocalStorage())
  3574. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  3575. }
  3576. Settings.prototype.setDisplayName = function (newDisplayName) {
  3577. this.displayName = newDisplayName;
  3578. if(this.confSettings != null)
  3579. this.confSettings.displayname = displayName;
  3580. this.save();
  3581. return this.displayName;
  3582. },
  3583. Settings.prototype.setEmail = function (newEmail) {
  3584. this.email = newEmail;
  3585. if(this.confSettings != null)
  3586. this.confSettings.email = newEmail;
  3587. this.save();
  3588. return this.email;
  3589. },
  3590. Settings.prototype.getSettings = function () {
  3591. return {
  3592. email: this.email,
  3593. displayName: this.displayName,
  3594. uid: this.userId,
  3595. language: this.language
  3596. };
  3597. },
  3598. Settings.prototype.setLanguage = function (lang) {
  3599. this.language = lang;
  3600. if(this.confSettings != null)
  3601. this.confSettings.language = lang;
  3602. this.save();
  3603. }
  3604. module.exports = Settings;
  3605. },{}],19:[function(require,module,exports){
  3606. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  3607. var Moderator = require("./moderator");
  3608. var EventEmitter = require("events");
  3609. var parser = {
  3610. packet2JSON: function (packet, nodes) {
  3611. var self = this;
  3612. $(packet).children().each(function (index) {
  3613. var tagName = $(this).prop("tagName");
  3614. var node = {}
  3615. node["tagName"] = tagName;
  3616. node.attributes = {};
  3617. $($(this)[0].attributes).each(function( index, attr ) {
  3618. node.attributes[ attr.name ] = attr.value;
  3619. } );
  3620. var text = Strophe.getText($(this)[0]);
  3621. if(text)
  3622. node.value = text;
  3623. node.children = [];
  3624. nodes.push(node);
  3625. self.packet2JSON($(this), node.children);
  3626. })
  3627. },
  3628. JSON2packet: function (nodes, packet) {
  3629. for(var i = 0; i < nodes.length; i++)
  3630. {
  3631. var node = nodes[i];
  3632. if(!node || node === null){
  3633. continue;
  3634. }
  3635. packet.c(node.tagName, node.attributes);
  3636. if(node.value)
  3637. packet.t(node.value);
  3638. if(node.children)
  3639. this.JSON2packet(node.children, packet);
  3640. packet.up();
  3641. }
  3642. packet.up();
  3643. }
  3644. };
  3645. function ChatRoom(connection, jid, password, XMPP, options)
  3646. {
  3647. this.eventEmitter = new EventEmitter();
  3648. this.xmpp = XMPP;
  3649. this.connection = connection;
  3650. this.roomjid = Strophe.getBareJidFromJid(jid);
  3651. this.myroomjid = jid;
  3652. this.password = password;
  3653. console.info("Joined MUC as " + this.myroomjid);
  3654. this.members = {};
  3655. this.presMap = {};
  3656. this.presHandlers = {};
  3657. this.joined = false;
  3658. this.role = null;
  3659. this.focusMucJid = null;
  3660. this.bridgeIsDown = false;
  3661. this.options = options || {};
  3662. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter);
  3663. this.initPresenceMap();
  3664. this.session = null;
  3665. var self = this;
  3666. }
  3667. ChatRoom.prototype.initPresenceMap = function () {
  3668. this.presMap['to'] = this.myroomjid;
  3669. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  3670. this.presMap["nodes"] = [];
  3671. this.presMap["nodes"].push( {
  3672. "tagName": "user-agent",
  3673. "value": navigator.userAgent,
  3674. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  3675. });
  3676. };
  3677. ChatRoom.prototype.join = function (password) {
  3678. if(password)
  3679. this.password = password;
  3680. this.moderator.allocateConferenceFocus(function()
  3681. {
  3682. this.sendPresence();
  3683. }.bind(this));
  3684. }
  3685. ChatRoom.prototype.sendPresence = function () {
  3686. if (!this.presMap['to']) {
  3687. // Too early to send presence - not initialized
  3688. return;
  3689. }
  3690. var pres = $pres({to: this.presMap['to'] });
  3691. pres.c('x', {xmlns: this.presMap['xns']});
  3692. if (this.password) {
  3693. pres.c('password').t(this.password).up();
  3694. }
  3695. pres.up();
  3696. // Send XEP-0115 'c' stanza that contains our capabilities info
  3697. if (this.connection.caps) {
  3698. this.connection.caps.node = this.xmpp.options.clientNode;
  3699. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  3700. }
  3701. parser.JSON2packet(this.presMap.nodes, pres);
  3702. this.connection.send(pres);
  3703. };
  3704. ChatRoom.prototype.doLeave = function () {
  3705. console.log("do leave", this.myroomjid);
  3706. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  3707. this.presMap.length = 0;
  3708. this.connection.send(pres);
  3709. };
  3710. ChatRoom.prototype.createNonAnonymousRoom = function () {
  3711. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  3712. var getForm = $iq({type: 'get', to: this.roomjid})
  3713. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  3714. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  3715. var self = this;
  3716. this.connection.sendIQ(getForm, function (form) {
  3717. if (!$(form).find(
  3718. '>query>x[xmlns="jabber:x:data"]' +
  3719. '>field[var="muc#roomconfig_whois"]').length) {
  3720. console.error('non-anonymous rooms not supported');
  3721. return;
  3722. }
  3723. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  3724. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  3725. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  3726. formSubmit.c('field', {'var': 'FORM_TYPE'})
  3727. .c('value')
  3728. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  3729. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  3730. .c('value').t('anyone').up().up();
  3731. self.connection.sendIQ(formSubmit);
  3732. }, function (error) {
  3733. console.error("Error getting room configuration form");
  3734. });
  3735. };
  3736. ChatRoom.prototype.onPresence = function (pres) {
  3737. var from = pres.getAttribute('from');
  3738. // Parse roles.
  3739. var member = {};
  3740. member.show = $(pres).find('>show').text();
  3741. member.status = $(pres).find('>status').text();
  3742. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  3743. member.affiliation = tmp.attr('affiliation');
  3744. member.role = tmp.attr('role');
  3745. // Focus recognition
  3746. member.jid = tmp.attr('jid');
  3747. member.isFocus = false;
  3748. if (member.jid
  3749. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") == 0) {
  3750. member.isFocus = true;
  3751. }
  3752. $(pres).find(">x").remove();
  3753. var nodes = [];
  3754. parser.packet2JSON(pres, nodes);
  3755. for(var i = 0; i < nodes.length; i++)
  3756. {
  3757. var node = nodes[i];
  3758. switch(node.tagName)
  3759. {
  3760. case "nick":
  3761. member.nick = node.value;
  3762. if(!member.isFocus) {
  3763. var displayName = !this.xmpp.options.displayJids
  3764. ? member.nick : Strophe.getResourceFromJid(from);
  3765. if (displayName && displayName.length > 0) {
  3766. this.eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  3767. }
  3768. console.info("Display name: " + displayName, pres);
  3769. }
  3770. break;
  3771. case "userId":
  3772. member.id = node.value;
  3773. break;
  3774. case "email":
  3775. member.email = node.value;
  3776. break;
  3777. case "bridgeIsDown":
  3778. if(!this.bridgeIsDown) {
  3779. this.bridgeIsDown = true;
  3780. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  3781. }
  3782. break;
  3783. default :
  3784. this.processNode(node, from);
  3785. }
  3786. }
  3787. if (from == this.myroomjid) {
  3788. if (member.affiliation == 'owner')
  3789. if (this.role !== member.role) {
  3790. this.role = member.role;
  3791. this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  3792. member, this.isModerator());
  3793. }
  3794. if (!this.joined) {
  3795. this.joined = true;
  3796. this.eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  3797. }
  3798. } else if (this.members[from] === undefined) {
  3799. // new participant
  3800. this.members[from] = member;
  3801. console.log('entered', from, member);
  3802. if (member.isFocus) {
  3803. this.focusMucJid = from;
  3804. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  3805. }
  3806. else {
  3807. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, member.id || member.email, member.nick);
  3808. }
  3809. } else {
  3810. // Presence update for existing participant
  3811. // Watch role change:
  3812. if (this.members[from].role != member.role) {
  3813. this.members[from].role = member.role;
  3814. this.eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  3815. member.role, member.nick);
  3816. }
  3817. }
  3818. if(!member.isFocus)
  3819. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id || member.email);
  3820. // Trigger status message update
  3821. if (member.status) {
  3822. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  3823. }
  3824. };
  3825. ChatRoom.prototype.processNode = function (node, from) {
  3826. if(this.presHandlers[node.tagName])
  3827. this.presHandlers[node.tagName](node, from);
  3828. };
  3829. ChatRoom.prototype.sendMessage = function (body, nickname) {
  3830. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  3831. msg.c('body', body).up();
  3832. if (nickname) {
  3833. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  3834. }
  3835. this.connection.send(msg);
  3836. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  3837. };
  3838. ChatRoom.prototype.setSubject = function (subject) {
  3839. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  3840. msg.c('subject', subject);
  3841. this.connection.send(msg);
  3842. console.log("topic changed to " + subject);
  3843. };
  3844. ChatRoom.prototype.onParticipantLeft = function (jid) {
  3845. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  3846. this.moderator.onMucMemberLeft(jid);
  3847. };
  3848. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  3849. // room destroyed ?
  3850. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  3851. '>destroy').length) {
  3852. var reason;
  3853. var reasonSelect = $(pres).find(
  3854. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  3855. '>destroy>reason');
  3856. if (reasonSelect.length) {
  3857. reason = reasonSelect.text();
  3858. }
  3859. this.xmpp.disposeConference(false);
  3860. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  3861. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(jid)];
  3862. return true;
  3863. }
  3864. // Status code 110 indicates that this notification is "self-presence".
  3865. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  3866. delete this.members[from];
  3867. this.onParticipantLeft(from);
  3868. }
  3869. // If the status code is 110 this means we're leaving and we would like
  3870. // to remove everyone else from our view, so we trigger the event.
  3871. else if (Object.keys(this.members).length > 1) {
  3872. for (var i in this.members) {
  3873. var member = this.members[i];
  3874. delete this.members[i];
  3875. this.onParticipantLeft(member);
  3876. }
  3877. }
  3878. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  3879. if (this.myroomjid === from) {
  3880. this.xmpp.disposeConference(false);
  3881. this.eventEmitter.emit(XMPPEvents.KICKED);
  3882. }
  3883. }
  3884. };
  3885. ChatRoom.prototype.onMessage = function (msg, from) {
  3886. var nick =
  3887. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  3888. .text() ||
  3889. Strophe.getResourceFromJid(from);
  3890. var txt = $(msg).find('>body').text();
  3891. var type = msg.getAttribute("type");
  3892. if (type == "error") {
  3893. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  3894. $(msg).find('>text').text(), txt);
  3895. return true;
  3896. }
  3897. var subject = $(msg).find('>subject');
  3898. if (subject.length) {
  3899. var subjectText = subject.text();
  3900. if (subjectText || subjectText == "") {
  3901. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  3902. console.log("Subject is changed to " + subjectText);
  3903. }
  3904. }
  3905. // xep-0203 delay
  3906. var stamp = $(msg).find('>delay').attr('stamp');
  3907. if (!stamp) {
  3908. // or xep-0091 delay, UTC timestamp
  3909. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  3910. if (stamp) {
  3911. // the format is CCYYMMDDThh:mm:ss
  3912. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  3913. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  3914. }
  3915. }
  3916. if (txt) {
  3917. console.log('chat', nick, txt);
  3918. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  3919. from, nick, txt, this.myroomjid, stamp);
  3920. }
  3921. }
  3922. ChatRoom.prototype.onPresenceError = function (pres, from) {
  3923. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  3924. console.log('on password required', from);
  3925. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  3926. } else if ($(pres).find(
  3927. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  3928. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  3929. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  3930. // enter the room by replying with 'not-authorized'. This would
  3931. // result in reconnection from authorized domain.
  3932. // We're either missing Jicofo/Prosody config for anonymous
  3933. // domains or something is wrong.
  3934. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  3935. } else {
  3936. console.warn('onPresError ', pres);
  3937. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  3938. }
  3939. } else {
  3940. console.warn('onPresError ', pres);
  3941. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  3942. }
  3943. };
  3944. ChatRoom.prototype.kick = function (jid) {
  3945. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  3946. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  3947. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  3948. .c('reason').t('You have been kicked.').up().up().up();
  3949. this.connection.sendIQ(
  3950. kickIQ,
  3951. function (result) {
  3952. console.log('Kick participant with jid: ', jid, result);
  3953. },
  3954. function (error) {
  3955. console.log('Kick participant error: ', error);
  3956. });
  3957. };
  3958. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  3959. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  3960. var ob = this;
  3961. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  3962. function (res) {
  3963. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  3964. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  3965. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  3966. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  3967. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  3968. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  3969. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  3970. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  3971. ob.connection.sendIQ(formsubmit,
  3972. onSuccess,
  3973. onError);
  3974. } else {
  3975. onNotSupported();
  3976. }
  3977. }, onError);
  3978. };
  3979. ChatRoom.prototype.addToPresence = function (key, values) {
  3980. values.tagName = key;
  3981. this.presMap["nodes"].push(values);
  3982. };
  3983. ChatRoom.prototype.removeFromPresence = function (key) {
  3984. for(var i = 0; i < this.presMap.nodes.length; i++)
  3985. {
  3986. if(key === this.presMap.nodes[i].tagName)
  3987. this.presMap.nodes.splice(i, 1);
  3988. }
  3989. };
  3990. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  3991. this.presHandlers[name] = handler;
  3992. }
  3993. ChatRoom.prototype.removePresenceListener = function (name) {
  3994. delete this.presHandlers[name];
  3995. }
  3996. ChatRoom.prototype.isModerator = function (jid) {
  3997. return this.role === 'moderator';
  3998. };
  3999. ChatRoom.prototype.getMemberRole = function (peerJid) {
  4000. if (this.members[peerJid]) {
  4001. return this.members[peerJid].role;
  4002. }
  4003. return null;
  4004. };
  4005. ChatRoom.prototype.setJingleSession = function(session){
  4006. this.session = session;
  4007. this.session.room = this;
  4008. };
  4009. ChatRoom.prototype.removeStream = function (stream) {
  4010. if(!this.session)
  4011. return;
  4012. this.session.peerconnection.removeStream(stream)
  4013. }
  4014. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  4015. if(this.session) {
  4016. // FIXME: will block switchInProgress on true value in case of exception
  4017. this.session.switchStreams(stream, oldStream, callback, isAudio);
  4018. } else {
  4019. // We are done immediately
  4020. console.warn("No conference handler or conference not started yet");
  4021. callback();
  4022. }
  4023. };
  4024. ChatRoom.prototype.addStream = function (stream, callback) {
  4025. if(this.session) {
  4026. // FIXME: will block switchInProgress on true value in case of exception
  4027. this.session.addStream(stream, callback);
  4028. } else {
  4029. // We are done immediately
  4030. console.warn("No conference handler or conference not started yet");
  4031. callback();
  4032. }
  4033. }
  4034. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  4035. var self = this;
  4036. var localCallback = function (mute) {
  4037. self.sendVideoInfoPresence(mute);
  4038. if(callback)
  4039. callback(mute)
  4040. };
  4041. if(this.session)
  4042. {
  4043. this.session.setVideoMute(
  4044. mute, localCallback, options);
  4045. }
  4046. else {
  4047. localCallback(mute);
  4048. }
  4049. };
  4050. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  4051. //This will be for remote streams only
  4052. // if (this.forceMuted && !mute) {
  4053. // console.info("Asking focus for unmute");
  4054. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  4055. // // FIXME: wait for result before resetting muted status
  4056. // this.forceMuted = false;
  4057. // }
  4058. return this.sendAudioInfoPresence(mute, callback);
  4059. };
  4060. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  4061. this.removeFromPresence("audiomuted");
  4062. this.addToPresence("audiomuted",
  4063. {attributes:
  4064. {"audions": "http://jitsi.org/jitmeet/audio"},
  4065. value: mute.toString()});
  4066. }
  4067. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  4068. this.addAudioInfoToPresence(mute);
  4069. if(this.connection) {
  4070. this.sendPresence();
  4071. }
  4072. if(callback)
  4073. callback();
  4074. };
  4075. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  4076. this.removeFromPresence("videomuted");
  4077. this.addToPresence("videomuted",
  4078. {attributes:
  4079. {"videons": "http://jitsi.org/jitmeet/video"},
  4080. value: mute.toString()});
  4081. }
  4082. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  4083. this.addVideoInfoToPresence(mute);
  4084. if(!this.connection)
  4085. return;
  4086. this.sendPresence();
  4087. };
  4088. ChatRoom.prototype.addListener = function(type, listener) {
  4089. this.eventEmitter.on(type, listener);
  4090. };
  4091. ChatRoom.prototype.removeListener = function (type, listener) {
  4092. this.eventEmitter.removeListener(type, listener);
  4093. };
  4094. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  4095. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  4096. }
  4097. ChatRoom.prototype.addLocalStreams = function (localStreams) {
  4098. this.session.addLocalStreams(localStreams);
  4099. }
  4100. module.exports = ChatRoom;
  4101. },{"../../service/xmpp/XMPPEvents":76,"./moderator":27,"events":77}],20:[function(require,module,exports){
  4102. /*
  4103. * JingleSession provides an API to manage a single Jingle session. We will
  4104. * have different implementations depending on the underlying interface used
  4105. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  4106. */
  4107. function JingleSession(me, sid, connection, service, eventEmitter) {
  4108. /**
  4109. * Our JID.
  4110. */
  4111. this.me = me;
  4112. /**
  4113. * The Jingle session identifier.
  4114. */
  4115. this.sid = sid;
  4116. /**
  4117. * The XMPP connection.
  4118. */
  4119. this.connection = connection;
  4120. /**
  4121. * The XMPP service.
  4122. */
  4123. this.service = service;
  4124. /**
  4125. * The event emitter.
  4126. */
  4127. this.eventEmitter = eventEmitter;
  4128. /**
  4129. * Whether to use dripping or not. Dripping is sending trickle candidates
  4130. * not one-by-one.
  4131. * Note: currently we do not support 'false'.
  4132. */
  4133. this.usedrip = true;
  4134. /**
  4135. * When dripping is used, stores ICE candidates which are to be sent.
  4136. */
  4137. this.drip_container = [];
  4138. // Media constraints. Is this WebRTC only?
  4139. this.media_constraints = null;
  4140. // ICE servers config (RTCConfiguration?).
  4141. this.ice_config = {};
  4142. // The chat room instance associated with the session.
  4143. this.room = null;
  4144. }
  4145. /**
  4146. * Prepares this object to initiate a session.
  4147. * @param peerjid the JID of the remote peer.
  4148. * @param isInitiator whether we will be the Jingle initiator.
  4149. * @param media_constraints
  4150. * @param ice_config
  4151. */
  4152. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  4153. media_constraints, ice_config) {
  4154. this.media_constraints = media_constraints;
  4155. this.ice_config = ice_config;
  4156. if (this.state !== null) {
  4157. console.error('attempt to initiate on session ' + this.sid +
  4158. 'in state ' + this.state);
  4159. return;
  4160. }
  4161. this.state = 'pending';
  4162. this.initiator = isInitiator ? this.me : peerjid;
  4163. this.responder = !isInitiator ? this.me : peerjid;
  4164. this.peerjid = peerjid;
  4165. this.doInitialize();
  4166. };
  4167. /**
  4168. * Finishes initialization.
  4169. */
  4170. JingleSession.prototype.doInitialize = function() {};
  4171. /**
  4172. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  4173. * Note: currently only used on transport-info
  4174. */
  4175. JingleSession.prototype.addIceCandidates = function(contents) {};
  4176. /**
  4177. * Handles an 'add-source' event.
  4178. *
  4179. * @param contents an array of Jingle 'content' elements.
  4180. */
  4181. JingleSession.prototype.addSources = function(contents) {};
  4182. /**
  4183. * Handles a 'remove-source' event.
  4184. *
  4185. * @param contents an array of Jingle 'content' elements.
  4186. */
  4187. JingleSession.prototype.removeSources = function(contents) {};
  4188. /**
  4189. * Terminates this Jingle session (stops sending media and closes the streams?)
  4190. */
  4191. JingleSession.prototype.terminate = function() {};
  4192. /**
  4193. * Sends a Jingle session-terminate message to the peer and terminates the
  4194. * session.
  4195. * @param reason
  4196. * @param text
  4197. */
  4198. JingleSession.prototype.sendTerminate = function(reason, text) {};
  4199. /**
  4200. * Handles an offer from the remote peer (prepares to accept a session).
  4201. * @param jingle the 'jingle' XML element.
  4202. */
  4203. JingleSession.prototype.setOffer = function(jingle) {};
  4204. /**
  4205. * Handles an answer from the remote peer (prepares to accept a session).
  4206. * @param jingle the 'jingle' XML element.
  4207. */
  4208. JingleSession.prototype.setAnswer = function(jingle) {};
  4209. module.exports = JingleSession;
  4210. },{}],21:[function(require,module,exports){
  4211. /* jshint -W117 */
  4212. var JingleSession = require("./JingleSession");
  4213. var TraceablePeerConnection = require("./TraceablePeerConnection");
  4214. var SDPDiffer = require("./SDPDiffer");
  4215. var SDPUtil = require("./SDPUtil");
  4216. var SDP = require("./SDP");
  4217. var async = require("async");
  4218. var transform = require("sdp-transform");
  4219. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  4220. var RTCBrowserType = require("../RTC/RTCBrowserType");
  4221. var SSRCReplacement = require("./LocalSSRCReplacement");
  4222. var RTC = require("../RTC/RTC");
  4223. // Jingle stuff
  4224. function JingleSessionPC(me, sid, connection, service) {
  4225. JingleSession.call(this, me, sid, connection, service);
  4226. this.initiator = null;
  4227. this.responder = null;
  4228. this.peerjid = null;
  4229. this.state = null;
  4230. this.localSDP = null;
  4231. this.remoteSDP = null;
  4232. this.relayedStreams = [];
  4233. this.usetrickle = true;
  4234. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  4235. this.hadstuncandidate = false;
  4236. this.hadturncandidate = false;
  4237. this.lasticecandidate = false;
  4238. this.statsinterval = null;
  4239. this.reason = null;
  4240. this.addssrc = [];
  4241. this.removessrc = [];
  4242. this.pendingop = null;
  4243. this.switchstreams = false;
  4244. this.wait = true;
  4245. this.localStreamsSSRC = null;
  4246. this.ssrcOwners = {};
  4247. this.ssrcVideoTypes = {};
  4248. /**
  4249. * The indicator which determines whether the (local) video has been muted
  4250. * in response to a user command in contrast to an automatic decision made
  4251. * by the application logic.
  4252. */
  4253. this.videoMuteByUser = false;
  4254. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  4255. // We start with the queue paused. We resume it when the signaling state is
  4256. // stable and the ice connection state is connected.
  4257. this.modifySourcesQueue.pause();
  4258. }
  4259. JingleSessionPC.prototype = JingleSession.prototype;
  4260. JingleSessionPC.prototype.constructor = JingleSessionPC;
  4261. JingleSessionPC.prototype.setOffer = function(offer) {
  4262. this.setRemoteDescription(offer, 'offer');
  4263. };
  4264. JingleSessionPC.prototype.setAnswer = function(answer) {
  4265. this.setRemoteDescription(answer, 'answer');
  4266. };
  4267. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  4268. var signalingState = this.peerconnection.signalingState;
  4269. var iceConnectionState = this.peerconnection.iceConnectionState;
  4270. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  4271. this.modifySourcesQueue.resume();
  4272. } else {
  4273. this.modifySourcesQueue.pause();
  4274. }
  4275. };
  4276. JingleSessionPC.prototype.doInitialize = function () {
  4277. var self = this;
  4278. this.hadstuncandidate = false;
  4279. this.hadturncandidate = false;
  4280. this.lasticecandidate = false;
  4281. this.isreconnect = false;
  4282. this.peerconnection = new TraceablePeerConnection(
  4283. this.connection.jingle.ice_config,
  4284. RTC.getPCConstraints(),
  4285. this);
  4286. this.peerconnection.onicecandidate = function (event) {
  4287. self.sendIceCandidate(event.candidate);
  4288. };
  4289. this.peerconnection.onaddstream = function (event) {
  4290. if (event.stream.id !== 'default') {
  4291. console.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  4292. self.remoteStreamAdded(event);
  4293. } else {
  4294. // This is a recvonly stream. Clients that implement Unified Plan,
  4295. // such as Firefox use recvonly "streams/channels/tracks" for
  4296. // receiving remote stream/tracks, as opposed to Plan B where there
  4297. // are only 3 channels: audio, video and data.
  4298. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  4299. }
  4300. };
  4301. this.peerconnection.onremovestream = function (event) {
  4302. // Remove the stream from remoteStreams
  4303. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  4304. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  4305. };
  4306. this.peerconnection.onsignalingstatechange = function (event) {
  4307. if (!(self && self.peerconnection)) return;
  4308. self.updateModifySourcesQueue();
  4309. };
  4310. /**
  4311. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  4312. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  4313. * RTCPeerConnection.iceConnectionState changes.
  4314. *
  4315. * @param event the event containing information about the change
  4316. */
  4317. this.peerconnection.oniceconnectionstatechange = function (event) {
  4318. if (!(self && self.peerconnection)) return;
  4319. self.updateModifySourcesQueue();
  4320. switch (self.peerconnection.iceConnectionState) {
  4321. case 'connected':
  4322. // Informs interested parties that the connection has been restored.
  4323. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  4324. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  4325. self.isreconnect = false;
  4326. break;
  4327. case 'disconnected':
  4328. self.isreconnect = true;
  4329. // Informs interested parties that the connection has been interrupted.
  4330. if (self.peerconnection.signalingState === 'stable')
  4331. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  4332. break;
  4333. case 'failed':
  4334. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4335. break;
  4336. }
  4337. onIceConnectionStateChange(self.sid, self);
  4338. };
  4339. this.peerconnection.onnegotiationneeded = function (event) {
  4340. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  4341. };
  4342. this.relayedStreams.forEach(function(stream) {
  4343. self.peerconnection.addStream(stream);
  4344. });
  4345. };
  4346. JingleSessionPC.prototype.addLocalStreams = function (localStreams) {
  4347. var self = this;
  4348. // add any local and relayed stream
  4349. localStreams.forEach(function(stream) {
  4350. self.peerconnection.addStream(stream.getOriginalStream());
  4351. });
  4352. }
  4353. function onIceConnectionStateChange(sid, session) {
  4354. switch (session.peerconnection.iceConnectionState) {
  4355. case 'checking':
  4356. session.timeChecking = (new Date()).getTime();
  4357. session.firstconnect = true;
  4358. break;
  4359. case 'completed': // on caller side
  4360. case 'connected':
  4361. if (session.firstconnect) {
  4362. session.firstconnect = false;
  4363. var metadata = {};
  4364. metadata.setupTime
  4365. = (new Date()).getTime() - session.timeChecking;
  4366. session.peerconnection.getStats(function (res) {
  4367. if(res && res.result) {
  4368. res.result().forEach(function (report) {
  4369. if (report.type == 'googCandidatePair' &&
  4370. report.stat('googActiveConnection') == 'true') {
  4371. metadata.localCandidateType
  4372. = report.stat('googLocalCandidateType');
  4373. metadata.remoteCandidateType
  4374. = report.stat('googRemoteCandidateType');
  4375. // log pair as well so we can get nice pie
  4376. // charts
  4377. metadata.candidatePair
  4378. = report.stat('googLocalCandidateType') +
  4379. ';' +
  4380. report.stat('googRemoteCandidateType');
  4381. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  4382. {
  4383. metadata.ipv6 = true;
  4384. }
  4385. }
  4386. });
  4387. }
  4388. });
  4389. }
  4390. break;
  4391. }
  4392. }
  4393. JingleSessionPC.prototype.accept = function () {
  4394. this.state = 'active';
  4395. var pranswer = this.peerconnection.localDescription;
  4396. if (!pranswer || pranswer.type != 'pranswer') {
  4397. return;
  4398. }
  4399. console.log('going from pranswer to answer');
  4400. if (this.usetrickle) {
  4401. // remove candidates already sent from session-accept
  4402. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  4403. for (var i = 0; i < lines.length; i++) {
  4404. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  4405. }
  4406. }
  4407. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  4408. // FIXME: change any inactive to sendrecv or whatever they were originally
  4409. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  4410. }
  4411. var prsdp = new SDP(pranswer.sdp);
  4412. var accept = $iq({to: this.peerjid,
  4413. type: 'set'})
  4414. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4415. action: 'session-accept',
  4416. initiator: this.initiator,
  4417. responder: this.responder,
  4418. sid: this.sid });
  4419. // FIXME why do we generate session-accept in 3 different places ?
  4420. prsdp.toJingle(
  4421. accept,
  4422. this.initiator == this.me ? 'initiator' : 'responder',
  4423. this.localStreamsSSRC);
  4424. var sdp = this.peerconnection.localDescription.sdp;
  4425. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  4426. // FIXME: change any inactive to sendrecv or whatever they were originally
  4427. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  4428. }
  4429. var self = this;
  4430. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  4431. function () {
  4432. //console.log('setLocalDescription success');
  4433. self.setLocalDescription();
  4434. SSRCReplacement.processSessionInit(accept);
  4435. self.connection.sendIQ(accept,
  4436. function () {
  4437. var ack = {};
  4438. ack.source = 'answer';
  4439. $(document).trigger('ack.jingle', [self.sid, ack]);
  4440. },
  4441. function (stanza) {
  4442. var error = ($(stanza).find('error').length) ? {
  4443. code: $(stanza).find('error').attr('code'),
  4444. reason: $(stanza).find('error :first')[0].tagName
  4445. }:{};
  4446. error.source = 'answer';
  4447. JingleSessionPC.onJingleError(self.sid, error);
  4448. },
  4449. 10000);
  4450. },
  4451. function (e) {
  4452. console.error('setLocalDescription failed', e);
  4453. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4454. }
  4455. );
  4456. };
  4457. JingleSessionPC.prototype.terminate = function (reason) {
  4458. this.state = 'ended';
  4459. this.reason = reason;
  4460. this.peerconnection.close();
  4461. if (this.statsinterval !== null) {
  4462. window.clearInterval(this.statsinterval);
  4463. this.statsinterval = null;
  4464. }
  4465. };
  4466. JingleSessionPC.prototype.active = function () {
  4467. return this.state == 'active';
  4468. };
  4469. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  4470. var self = this;
  4471. if (candidate && !this.lasticecandidate) {
  4472. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  4473. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  4474. if (!(ice && jcand)) {
  4475. console.error('failed to get ice && jcand');
  4476. return;
  4477. }
  4478. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  4479. if (jcand.type === 'srflx') {
  4480. this.hadstuncandidate = true;
  4481. } else if (jcand.type === 'relay') {
  4482. this.hadturncandidate = true;
  4483. }
  4484. if (this.usetrickle) {
  4485. if (this.usedrip) {
  4486. if (this.drip_container.length === 0) {
  4487. // start 20ms callout
  4488. window.setTimeout(function () {
  4489. if (self.drip_container.length === 0) return;
  4490. self.sendIceCandidates(self.drip_container);
  4491. self.drip_container = [];
  4492. }, 20);
  4493. }
  4494. this.drip_container.push(candidate);
  4495. return;
  4496. } else {
  4497. self.sendIceCandidate([candidate]);
  4498. }
  4499. }
  4500. } else {
  4501. //console.log('sendIceCandidate: last candidate.');
  4502. if (!this.usetrickle) {
  4503. //console.log('should send full offer now...');
  4504. //FIXME why do we generate session-accept in 3 different places ?
  4505. var init = $iq({to: this.peerjid,
  4506. type: 'set'})
  4507. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4508. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  4509. initiator: this.initiator,
  4510. sid: this.sid});
  4511. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  4512. var sendJingle = function (ssrc) {
  4513. if(!ssrc)
  4514. ssrc = {};
  4515. self.localSDP.toJingle(
  4516. init,
  4517. self.initiator == self.me ? 'initiator' : 'responder',
  4518. ssrc);
  4519. SSRCReplacement.processSessionInit(init);
  4520. self.connection.sendIQ(init,
  4521. function () {
  4522. //console.log('session initiate ack');
  4523. var ack = {};
  4524. ack.source = 'offer';
  4525. $(document).trigger('ack.jingle', [self.sid, ack]);
  4526. },
  4527. function (stanza) {
  4528. self.state = 'error';
  4529. self.peerconnection.close();
  4530. var error = ($(stanza).find('error').length) ? {
  4531. code: $(stanza).find('error').attr('code'),
  4532. reason: $(stanza).find('error :first')[0].tagName,
  4533. }:{};
  4534. error.source = 'offer';
  4535. JingleSessionPC.onJingleError(self.sid, error);
  4536. },
  4537. 10000);
  4538. };
  4539. sendJingle();
  4540. }
  4541. this.lasticecandidate = true;
  4542. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  4543. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  4544. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  4545. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  4546. }
  4547. }
  4548. };
  4549. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  4550. console.log('sendIceCandidates', candidates);
  4551. var cand = $iq({to: this.peerjid, type: 'set'})
  4552. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4553. action: 'transport-info',
  4554. initiator: this.initiator,
  4555. sid: this.sid});
  4556. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  4557. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  4558. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  4559. if (cands.length > 0) {
  4560. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  4561. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  4562. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  4563. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  4564. }).c('transport', ice);
  4565. for (var i = 0; i < cands.length; i++) {
  4566. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  4567. }
  4568. // add fingerprint
  4569. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  4570. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  4571. tmp.required = true;
  4572. cand.c(
  4573. 'fingerprint',
  4574. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  4575. .t(tmp.fingerprint);
  4576. delete tmp.fingerprint;
  4577. cand.attrs(tmp);
  4578. cand.up();
  4579. }
  4580. cand.up(); // transport
  4581. cand.up(); // content
  4582. }
  4583. }
  4584. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  4585. //console.log('was this the last candidate', this.lasticecandidate);
  4586. this.connection.sendIQ(cand,
  4587. function () {
  4588. var ack = {};
  4589. ack.source = 'transportinfo';
  4590. $(document).trigger('ack.jingle', [this.sid, ack]);
  4591. },
  4592. function (stanza) {
  4593. var error = ($(stanza).find('error').length) ? {
  4594. code: $(stanza).find('error').attr('code'),
  4595. reason: $(stanza).find('error :first')[0].tagName,
  4596. }:{};
  4597. error.source = 'transportinfo';
  4598. JingleSessionPC.onJingleError(this.sid, error);
  4599. },
  4600. 10000);
  4601. };
  4602. JingleSessionPC.prototype.sendOffer = function () {
  4603. //console.log('sendOffer...');
  4604. var self = this;
  4605. this.peerconnection.createOffer(function (sdp) {
  4606. self.createdOffer(sdp);
  4607. },
  4608. function (e) {
  4609. console.error('createOffer failed', e);
  4610. },
  4611. this.media_constraints
  4612. );
  4613. };
  4614. // FIXME createdOffer is never used in jitsi-meet
  4615. JingleSessionPC.prototype.createdOffer = function (sdp) {
  4616. //console.log('createdOffer', sdp);
  4617. var self = this;
  4618. this.localSDP = new SDP(sdp.sdp);
  4619. //this.localSDP.mangle();
  4620. var sendJingle = function () {
  4621. var init = $iq({to: this.peerjid,
  4622. type: 'set'})
  4623. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4624. action: 'session-initiate',
  4625. initiator: this.initiator,
  4626. sid: this.sid});
  4627. self.localSDP.toJingle(
  4628. init,
  4629. this.initiator == this.me ? 'initiator' : 'responder',
  4630. this.localStreamsSSRC);
  4631. SSRCReplacement.processSessionInit(init);
  4632. self.connection.sendIQ(init,
  4633. function () {
  4634. var ack = {};
  4635. ack.source = 'offer';
  4636. $(document).trigger('ack.jingle', [self.sid, ack]);
  4637. },
  4638. function (stanza) {
  4639. self.state = 'error';
  4640. self.peerconnection.close();
  4641. var error = ($(stanza).find('error').length) ? {
  4642. code: $(stanza).find('error').attr('code'),
  4643. reason: $(stanza).find('error :first')[0].tagName,
  4644. }:{};
  4645. error.source = 'offer';
  4646. JingleSessionPC.onJingleError(self.sid, error);
  4647. },
  4648. 10000);
  4649. }
  4650. sdp.sdp = this.localSDP.raw;
  4651. this.peerconnection.setLocalDescription(sdp,
  4652. function () {
  4653. if(self.usetrickle)
  4654. {
  4655. sendJingle();
  4656. }
  4657. self.setLocalDescription();
  4658. //console.log('setLocalDescription success');
  4659. },
  4660. function (e) {
  4661. console.error('setLocalDescription failed', e);
  4662. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4663. }
  4664. );
  4665. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  4666. for (var i = 0; i < cands.length; i++) {
  4667. var cand = SDPUtil.parse_icecandidate(cands[i]);
  4668. if (cand.type == 'srflx') {
  4669. this.hadstuncandidate = true;
  4670. } else if (cand.type == 'relay') {
  4671. this.hadturncandidate = true;
  4672. }
  4673. }
  4674. };
  4675. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  4676. var self = this;
  4677. $(contents).each(function (idx, content) {
  4678. var name = $(content).attr('name');
  4679. var mediaType = this.getAttribute('name');
  4680. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  4681. ssrcs.each(function () {
  4682. var ssrc = this.getAttribute('ssrc');
  4683. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  4684. function () {
  4685. var owner = this.getAttribute('owner');
  4686. self.ssrcOwners[ssrc] = owner;
  4687. }
  4688. );
  4689. });
  4690. });
  4691. };
  4692. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  4693. return this.ssrcOwners[ssrc];
  4694. };
  4695. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  4696. //console.log('setting remote description... ', desctype);
  4697. this.remoteSDP = new SDP('');
  4698. this.remoteSDP.fromJingle(elem);
  4699. this.readSsrcInfo($(elem).find(">content"));
  4700. if (this.peerconnection.remoteDescription !== null) {
  4701. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  4702. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  4703. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  4704. for (var i = 0; i < pranswer.media.length; i++) {
  4705. // make sure we have ice ufrag and pwd
  4706. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  4707. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  4708. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  4709. } else {
  4710. console.warn('no ice ufrag?');
  4711. }
  4712. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  4713. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  4714. } else {
  4715. console.warn('no ice pwd?');
  4716. }
  4717. }
  4718. // copy over candidates
  4719. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  4720. for (var j = 0; j < lines.length; j++) {
  4721. this.remoteSDP.media[i] += lines[j] + '\r\n';
  4722. }
  4723. }
  4724. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  4725. }
  4726. }
  4727. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  4728. this.peerconnection.setRemoteDescription(remotedesc,
  4729. function () {
  4730. //console.log('setRemoteDescription success');
  4731. },
  4732. function (e) {
  4733. console.error('setRemoteDescription error', e);
  4734. JingleSessionPC.onJingleFatalError(self, e);
  4735. }
  4736. );
  4737. };
  4738. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  4739. var self = this;
  4740. if (this.peerconnection.signalingState == 'closed') {
  4741. return;
  4742. }
  4743. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  4744. console.log('trickle ice candidate arriving before session accept...');
  4745. // create a PRANSWER for setRemoteDescription
  4746. if (!this.remoteSDP) {
  4747. var cobbled = 'v=0\r\n' +
  4748. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  4749. 's=-\r\n' +
  4750. 't=0 0\r\n';
  4751. // first, take some things from the local description
  4752. for (var i = 0; i < this.localSDP.media.length; i++) {
  4753. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  4754. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  4755. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  4756. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  4757. }
  4758. cobbled += 'a=inactive\r\n';
  4759. }
  4760. this.remoteSDP = new SDP(cobbled);
  4761. }
  4762. // then add things like ice and dtls from remote candidate
  4763. elem.each(function () {
  4764. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  4765. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  4766. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  4767. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  4768. var tmp = $(this).find('transport');
  4769. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  4770. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  4771. tmp = $(this).find('transport>fingerprint');
  4772. if (tmp.length) {
  4773. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  4774. } else {
  4775. console.log('no dtls fingerprint (webrtc issue #1718?)');
  4776. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  4777. }
  4778. break;
  4779. }
  4780. }
  4781. }
  4782. });
  4783. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  4784. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  4785. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  4786. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  4787. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  4788. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  4789. }).length == this.remoteSDP.media.length;
  4790. if (iscomplete) {
  4791. console.log('setting pranswer');
  4792. try {
  4793. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  4794. function() {
  4795. },
  4796. function(e) {
  4797. console.log('setRemoteDescription pranswer failed', e.toString());
  4798. });
  4799. } catch (e) {
  4800. console.error('setting pranswer failed', e);
  4801. }
  4802. } else {
  4803. //console.log('not yet setting pranswer');
  4804. }
  4805. }
  4806. // operate on each content element
  4807. elem.each(function () {
  4808. // would love to deactivate this, but firefox still requires it
  4809. var idx = -1;
  4810. var i;
  4811. for (i = 0; i < self.remoteSDP.media.length; i++) {
  4812. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  4813. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  4814. idx = i;
  4815. break;
  4816. }
  4817. }
  4818. if (idx == -1) { // fall back to localdescription
  4819. for (i = 0; i < self.localSDP.media.length; i++) {
  4820. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  4821. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  4822. idx = i;
  4823. break;
  4824. }
  4825. }
  4826. }
  4827. var name = $(this).attr('name');
  4828. // TODO: check ice-pwd and ice-ufrag?
  4829. $(this).find('transport>candidate').each(function () {
  4830. var line, candidate;
  4831. line = SDPUtil.candidateFromJingle(this);
  4832. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  4833. sdpMid: name,
  4834. candidate: line});
  4835. try {
  4836. self.peerconnection.addIceCandidate(candidate);
  4837. } catch (e) {
  4838. console.error('addIceCandidate failed', e.toString(), line);
  4839. }
  4840. });
  4841. });
  4842. };
  4843. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  4844. //console.log('createAnswer', provisional);
  4845. var self = this;
  4846. this.peerconnection.createAnswer(
  4847. function (sdp) {
  4848. self.createdAnswer(sdp, provisional);
  4849. },
  4850. function (e) {
  4851. console.error('createAnswer failed', e);
  4852. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4853. },
  4854. this.media_constraints
  4855. );
  4856. };
  4857. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  4858. //console.log('createAnswer callback');
  4859. var self = this;
  4860. this.localSDP = new SDP(sdp.sdp);
  4861. //this.localSDP.mangle();
  4862. this.usepranswer = provisional === true;
  4863. if (this.usetrickle) {
  4864. if (this.usepranswer) {
  4865. sdp.type = 'pranswer';
  4866. for (var i = 0; i < this.localSDP.media.length; i++) {
  4867. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  4868. }
  4869. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  4870. }
  4871. }
  4872. var self = this;
  4873. var sendJingle = function (ssrcs) {
  4874. // FIXME why do we generate session-accept in 3 different places ?
  4875. var accept = $iq({to: self.peerjid,
  4876. type: 'set'})
  4877. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4878. action: 'session-accept',
  4879. initiator: self.initiator,
  4880. responder: self.responder,
  4881. sid: self.sid });
  4882. self.localSDP.toJingle(
  4883. accept,
  4884. self.initiator == self.me ? 'initiator' : 'responder',
  4885. ssrcs);
  4886. SSRCReplacement.processSessionInit(accept);
  4887. self.connection.sendIQ(accept,
  4888. function () {
  4889. var ack = {};
  4890. ack.source = 'answer';
  4891. $(document).trigger('ack.jingle', [self.sid, ack]);
  4892. },
  4893. function (stanza) {
  4894. var error = ($(stanza).find('error').length) ? {
  4895. code: $(stanza).find('error').attr('code'),
  4896. reason: $(stanza).find('error :first')[0].tagName,
  4897. }:{};
  4898. error.source = 'answer';
  4899. JingleSessionPC.onJingleError(self.sid, error);
  4900. },
  4901. 10000);
  4902. }
  4903. sdp.sdp = this.localSDP.raw;
  4904. this.peerconnection.setLocalDescription(sdp,
  4905. function () {
  4906. //console.log('setLocalDescription success');
  4907. if (self.usetrickle && !self.usepranswer) {
  4908. sendJingle();
  4909. }
  4910. self.setLocalDescription();
  4911. },
  4912. function (e) {
  4913. console.error('setLocalDescription failed', e);
  4914. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4915. }
  4916. );
  4917. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  4918. for (var j = 0; j < cands.length; j++) {
  4919. var cand = SDPUtil.parse_icecandidate(cands[j]);
  4920. if (cand.type == 'srflx') {
  4921. this.hadstuncandidate = true;
  4922. } else if (cand.type == 'relay') {
  4923. this.hadturncandidate = true;
  4924. }
  4925. }
  4926. };
  4927. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  4928. var self = this,
  4929. term = $iq({to: this.peerjid,
  4930. type: 'set'})
  4931. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4932. action: 'session-terminate',
  4933. initiator: this.initiator,
  4934. sid: this.sid})
  4935. .c('reason')
  4936. .c(reason || 'success');
  4937. if (text) {
  4938. term.up().c('text').t(text);
  4939. }
  4940. this.connection.sendIQ(term,
  4941. function () {
  4942. self.peerconnection.close();
  4943. self.peerconnection = null;
  4944. self.terminate();
  4945. var ack = {};
  4946. ack.source = 'terminate';
  4947. $(document).trigger('ack.jingle', [self.sid, ack]);
  4948. },
  4949. function (stanza) {
  4950. var error = ($(stanza).find('error').length) ? {
  4951. code: $(stanza).find('error').attr('code'),
  4952. reason: $(stanza).find('error :first')[0].tagName,
  4953. }:{};
  4954. $(document).trigger('ack.jingle', [self.sid, error]);
  4955. },
  4956. 10000);
  4957. if (this.statsinterval !== null) {
  4958. window.clearInterval(this.statsinterval);
  4959. this.statsinterval = null;
  4960. }
  4961. };
  4962. JingleSessionPC.prototype.addSource = function (elem, fromJid) {
  4963. var self = this;
  4964. // FIXME: dirty waiting
  4965. if (!this.peerconnection.localDescription)
  4966. {
  4967. console.warn("addSource - localDescription not ready yet")
  4968. setTimeout(function()
  4969. {
  4970. self.addSource(elem, fromJid);
  4971. },
  4972. 200
  4973. );
  4974. return;
  4975. }
  4976. console.log('addssrc', new Date().getTime());
  4977. console.log('ice', this.peerconnection.iceConnectionState);
  4978. this.readSsrcInfo(elem);
  4979. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  4980. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  4981. $(elem).each(function (idx, content) {
  4982. var name = $(content).attr('name');
  4983. var lines = '';
  4984. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  4985. var semantics = this.getAttribute('semantics');
  4986. var ssrcs = $(this).find('>source').map(function () {
  4987. return this.getAttribute('ssrc');
  4988. }).get();
  4989. if (ssrcs.length != 0) {
  4990. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  4991. }
  4992. });
  4993. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  4994. tmp.each(function () {
  4995. var ssrc = $(this).attr('ssrc');
  4996. if(mySdp.containsSSRC(ssrc)){
  4997. /**
  4998. * This happens when multiple participants change their streams at the same time and
  4999. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  5000. * addssrc are scheduled for update IQ. See
  5001. */
  5002. console.warn("Got add stream request for my own ssrc: "+ssrc);
  5003. return;
  5004. }
  5005. if (sdp.containsSSRC(ssrc)) {
  5006. console.warn("Source-add request for existing SSRC: " + ssrc);
  5007. return;
  5008. }
  5009. $(this).find('>parameter').each(function () {
  5010. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  5011. if ($(this).attr('value') && $(this).attr('value').length)
  5012. lines += ':' + $(this).attr('value');
  5013. lines += '\r\n';
  5014. });
  5015. });
  5016. sdp.media.forEach(function(media, idx) {
  5017. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  5018. return;
  5019. sdp.media[idx] += lines;
  5020. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  5021. self.addssrc[idx] += lines;
  5022. });
  5023. sdp.raw = sdp.session + sdp.media.join('');
  5024. });
  5025. this.modifySourcesQueue.push(function() {
  5026. // When a source is added and if this is FF, a new channel is allocated
  5027. // for receiving the added source. We need to diffuse the SSRC of this
  5028. // new recvonly channel to the rest of the peers.
  5029. console.log('modify sources done');
  5030. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  5031. console.log("SDPs", mySdp, newSdp);
  5032. self.notifyMySSRCUpdate(mySdp, newSdp);
  5033. });
  5034. };
  5035. JingleSessionPC.prototype.removeSource = function (elem, fromJid) {
  5036. var self = this;
  5037. // FIXME: dirty waiting
  5038. if (!this.peerconnection.localDescription)
  5039. {
  5040. console.warn("removeSource - localDescription not ready yet")
  5041. setTimeout(function()
  5042. {
  5043. self.removeSource(elem, fromJid);
  5044. },
  5045. 200
  5046. );
  5047. return;
  5048. }
  5049. console.log('removessrc', new Date().getTime());
  5050. console.log('ice', this.peerconnection.iceConnectionState);
  5051. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  5052. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  5053. $(elem).each(function (idx, content) {
  5054. var name = $(content).attr('name');
  5055. var lines = '';
  5056. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  5057. var semantics = this.getAttribute('semantics');
  5058. var ssrcs = $(this).find('>source').map(function () {
  5059. return this.getAttribute('ssrc');
  5060. }).get();
  5061. if (ssrcs.length != 0) {
  5062. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  5063. }
  5064. });
  5065. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  5066. tmp.each(function () {
  5067. var ssrc = $(this).attr('ssrc');
  5068. // This should never happen, but can be useful for bug detection
  5069. if(mySdp.containsSSRC(ssrc)){
  5070. console.error("Got remove stream request for my own ssrc: "+ssrc);
  5071. return;
  5072. }
  5073. $(this).find('>parameter').each(function () {
  5074. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  5075. if ($(this).attr('value') && $(this).attr('value').length)
  5076. lines += ':' + $(this).attr('value');
  5077. lines += '\r\n';
  5078. });
  5079. });
  5080. sdp.media.forEach(function(media, idx) {
  5081. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  5082. return;
  5083. sdp.media[idx] += lines;
  5084. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  5085. self.removessrc[idx] += lines;
  5086. });
  5087. sdp.raw = sdp.session + sdp.media.join('');
  5088. });
  5089. this.modifySourcesQueue.push(function() {
  5090. // When a source is removed and if this is FF, the recvonly channel that
  5091. // receives the remote stream is deactivated . We need to diffuse the
  5092. // recvonly SSRC removal to the rest of the peers.
  5093. console.log('modify sources done');
  5094. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  5095. console.log("SDPs", mySdp, newSdp);
  5096. self.notifyMySSRCUpdate(mySdp, newSdp);
  5097. });
  5098. };
  5099. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  5100. var self = this;
  5101. if (this.peerconnection.signalingState == 'closed') return;
  5102. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  5103. // There is nothing to do since scheduled job might have been executed by another succeeding call
  5104. this.setLocalDescription();
  5105. if(successCallback){
  5106. successCallback();
  5107. }
  5108. queueCallback();
  5109. return;
  5110. }
  5111. // Reset switch streams flag
  5112. this.switchstreams = false;
  5113. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  5114. // add sources
  5115. this.addssrc.forEach(function(lines, idx) {
  5116. sdp.media[idx] += lines;
  5117. });
  5118. this.addssrc = [];
  5119. // remove sources
  5120. this.removessrc.forEach(function(lines, idx) {
  5121. lines = lines.split('\r\n');
  5122. lines.pop(); // remove empty last element;
  5123. lines.forEach(function(line) {
  5124. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  5125. });
  5126. });
  5127. this.removessrc = [];
  5128. sdp.raw = sdp.session + sdp.media.join('');
  5129. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  5130. function() {
  5131. if(self.signalingState == 'closed') {
  5132. console.error("createAnswer attempt on closed state");
  5133. queueCallback("createAnswer attempt on closed state");
  5134. return;
  5135. }
  5136. self.peerconnection.createAnswer(
  5137. function(modifiedAnswer) {
  5138. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  5139. if (self.pendingop !== null) {
  5140. var sdp = new SDP(modifiedAnswer.sdp);
  5141. if (sdp.media.length > 1) {
  5142. switch(self.pendingop) {
  5143. case 'mute':
  5144. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  5145. break;
  5146. case 'unmute':
  5147. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  5148. break;
  5149. }
  5150. sdp.raw = sdp.session + sdp.media.join('');
  5151. modifiedAnswer.sdp = sdp.raw;
  5152. }
  5153. self.pendingop = null;
  5154. }
  5155. // FIXME: pushing down an answer while ice connection state
  5156. // is still checking is bad...
  5157. //console.log(self.peerconnection.iceConnectionState);
  5158. // trying to work around another chrome bug
  5159. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  5160. self.peerconnection.setLocalDescription(modifiedAnswer,
  5161. function() {
  5162. //console.log('modified setLocalDescription ok');
  5163. self.setLocalDescription();
  5164. if(successCallback){
  5165. successCallback();
  5166. }
  5167. queueCallback();
  5168. },
  5169. function(error) {
  5170. console.error('modified setLocalDescription failed', error);
  5171. queueCallback(error);
  5172. }
  5173. );
  5174. },
  5175. function(error) {
  5176. console.error('modified answer failed', error);
  5177. queueCallback(error);
  5178. }
  5179. );
  5180. },
  5181. function(error) {
  5182. console.error('modify failed', error);
  5183. queueCallback(error);
  5184. }
  5185. );
  5186. };
  5187. /**
  5188. * Switches video streams.
  5189. * @param new_stream new stream that will be used as video of this session.
  5190. * @param oldStream old video stream of this session.
  5191. * @param success_callback callback executed after successful stream switch.
  5192. */
  5193. JingleSessionPC.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  5194. var self = this;
  5195. // Remember SDP to figure out added/removed SSRCs
  5196. var oldSdp = null;
  5197. if(self.peerconnection) {
  5198. if(self.peerconnection.localDescription) {
  5199. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  5200. }
  5201. self.peerconnection.removeStream(oldStream, true);
  5202. if(new_stream)
  5203. self.peerconnection.addStream(new_stream);
  5204. }
  5205. // Conference is not active
  5206. if(!oldSdp || !self.peerconnection) {
  5207. success_callback();
  5208. return;
  5209. }
  5210. self.switchstreams = true;
  5211. self.modifySourcesQueue.push(function() {
  5212. console.log('modify sources done');
  5213. success_callback();
  5214. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  5215. console.log("SDPs", oldSdp, newSdp);
  5216. self.notifyMySSRCUpdate(oldSdp, newSdp);
  5217. });
  5218. };
  5219. /**
  5220. * Adds streams.
  5221. * @param stream new stream that will be added.
  5222. * @param success_callback callback executed after successful stream addition.
  5223. */
  5224. JingleSessionPC.prototype.addStream = function (stream, callback) {
  5225. var self = this;
  5226. // Remember SDP to figure out added/removed SSRCs
  5227. var oldSdp = null;
  5228. if(this.peerconnection) {
  5229. if(this.peerconnection.localDescription) {
  5230. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  5231. }
  5232. if(stream)
  5233. this.peerconnection.addStream(stream);
  5234. }
  5235. // Conference is not active
  5236. if(!oldSdp || !this.peerconnection) {
  5237. callback();
  5238. return;
  5239. }
  5240. this.modifySourcesQueue.push(function() {
  5241. console.log('modify sources done');
  5242. callback();
  5243. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  5244. console.log("SDPs", oldSdp, newSdp);
  5245. self.notifyMySSRCUpdate(oldSdp, newSdp);
  5246. });
  5247. }
  5248. /**
  5249. * Figures out added/removed ssrcs and send update IQs.
  5250. * @param old_sdp SDP object for old description.
  5251. * @param new_sdp SDP object for new description.
  5252. */
  5253. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  5254. if (!(this.peerconnection.signalingState == 'stable' &&
  5255. this.peerconnection.iceConnectionState == 'connected')){
  5256. console.log("Too early to send updates");
  5257. return;
  5258. }
  5259. // send source-remove IQ.
  5260. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  5261. var remove = $iq({to: this.peerjid, type: 'set'})
  5262. .c('jingle', {
  5263. xmlns: 'urn:xmpp:jingle:1',
  5264. action: 'source-remove',
  5265. initiator: this.initiator,
  5266. sid: this.sid
  5267. }
  5268. );
  5269. var removed = sdpDiffer.toJingle(remove);
  5270. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  5271. // it in the current form
  5272. if (removed)
  5273. remove = SSRCReplacement.processSourceRemove(remove);
  5274. if (removed && remove) {
  5275. console.info("Sending source-remove", remove);
  5276. this.connection.sendIQ(remove,
  5277. function (res) {
  5278. console.info('got remove result', res);
  5279. },
  5280. function (err) {
  5281. console.error('got remove error', err);
  5282. }
  5283. );
  5284. } else {
  5285. console.log('removal not necessary');
  5286. }
  5287. // send source-add IQ.
  5288. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  5289. var add = $iq({to: this.peerjid, type: 'set'})
  5290. .c('jingle', {
  5291. xmlns: 'urn:xmpp:jingle:1',
  5292. action: 'source-add',
  5293. initiator: this.initiator,
  5294. sid: this.sid
  5295. }
  5296. );
  5297. var added = sdpDiffer.toJingle(add);
  5298. // Let 'source-add' IQ through the hack and see if we're allowed to send
  5299. // it in the current form
  5300. if (added)
  5301. add = SSRCReplacement.processSourceAdd(add);
  5302. if (added && add) {
  5303. console.info("Sending source-add", add);
  5304. this.connection.sendIQ(add,
  5305. function (res) {
  5306. console.info('got add result', res);
  5307. },
  5308. function (err) {
  5309. console.error('got add error', err);
  5310. }
  5311. );
  5312. } else {
  5313. console.log('addition not necessary');
  5314. }
  5315. };
  5316. /**
  5317. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  5318. *
  5319. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  5320. * tracks; otherwise, <tt>false</tt>
  5321. * @param callback a function to be invoked with <tt>mute</tt> after all video
  5322. * tracks have been enabled/disabled. The function may, optionally, return
  5323. * another function which is to be invoked after the whole mute/unmute operation
  5324. * has completed successfully.
  5325. * @param options an object which specifies optional arguments such as the
  5326. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  5327. * specifies whether the method was initiated in response to a user command (in
  5328. * contrast to an automatic decision made by the application logic)
  5329. */
  5330. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  5331. var byUser;
  5332. if (options) {
  5333. byUser = options.byUser;
  5334. if (typeof byUser === 'undefined') {
  5335. byUser = true;
  5336. }
  5337. } else {
  5338. byUser = true;
  5339. }
  5340. // The user's command to mute the (local) video takes precedence over any
  5341. // automatic decision made by the application logic.
  5342. if (byUser) {
  5343. this.videoMuteByUser = mute;
  5344. } else if (this.videoMuteByUser) {
  5345. return;
  5346. }
  5347. this.hardMuteVideo(mute);
  5348. var self = this;
  5349. var oldSdp = null;
  5350. if(self.peerconnection) {
  5351. if(self.peerconnection.localDescription) {
  5352. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  5353. }
  5354. }
  5355. this.modifySourcesQueue.push(function() {
  5356. console.log('modify sources done');
  5357. callback(mute);
  5358. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  5359. console.log("SDPs", oldSdp, newSdp);
  5360. self.notifyMySSRCUpdate(oldSdp, newSdp);
  5361. });
  5362. };
  5363. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  5364. this.pendingop = muted ? 'mute' : 'unmute';
  5365. };
  5366. JingleSessionPC.prototype.sendMute = function (muted, content) {
  5367. var info = $iq({to: this.peerjid,
  5368. type: 'set'})
  5369. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5370. action: 'session-info',
  5371. initiator: this.initiator,
  5372. sid: this.sid });
  5373. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  5374. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  5375. if (content) {
  5376. info.attrs({'name': content});
  5377. }
  5378. this.connection.send(info);
  5379. };
  5380. JingleSessionPC.prototype.sendRinging = function () {
  5381. var info = $iq({to: this.peerjid,
  5382. type: 'set'})
  5383. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5384. action: 'session-info',
  5385. initiator: this.initiator,
  5386. sid: this.sid });
  5387. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  5388. this.connection.send(info);
  5389. };
  5390. JingleSessionPC.prototype.getStats = function (interval) {
  5391. var self = this;
  5392. var recv = {audio: 0, video: 0};
  5393. var lost = {audio: 0, video: 0};
  5394. var lastrecv = {audio: 0, video: 0};
  5395. var lastlost = {audio: 0, video: 0};
  5396. var loss = {audio: 0, video: 0};
  5397. var delta = {audio: 0, video: 0};
  5398. this.statsinterval = window.setInterval(function () {
  5399. if (self && self.peerconnection && self.peerconnection.getStats) {
  5400. self.peerconnection.getStats(function (stats) {
  5401. var results = stats.result();
  5402. // TODO: there are so much statistics you can get from this..
  5403. for (var i = 0; i < results.length; ++i) {
  5404. if (results[i].type == 'ssrc') {
  5405. var packetsrecv = results[i].stat('packetsReceived');
  5406. var packetslost = results[i].stat('packetsLost');
  5407. if (packetsrecv && packetslost) {
  5408. packetsrecv = parseInt(packetsrecv, 10);
  5409. packetslost = parseInt(packetslost, 10);
  5410. if (results[i].stat('googFrameRateReceived')) {
  5411. lastlost.video = lost.video;
  5412. lastrecv.video = recv.video;
  5413. recv.video = packetsrecv;
  5414. lost.video = packetslost;
  5415. } else {
  5416. lastlost.audio = lost.audio;
  5417. lastrecv.audio = recv.audio;
  5418. recv.audio = packetsrecv;
  5419. lost.audio = packetslost;
  5420. }
  5421. }
  5422. }
  5423. }
  5424. delta.audio = recv.audio - lastrecv.audio;
  5425. delta.video = recv.video - lastrecv.video;
  5426. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  5427. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  5428. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  5429. });
  5430. }
  5431. }, interval || 3000);
  5432. return this.statsinterval;
  5433. };
  5434. JingleSessionPC.onJingleError = function (session, error)
  5435. {
  5436. console.error("Jingle error", error);
  5437. }
  5438. JingleSessionPC.onJingleFatalError = function (session, error)
  5439. {
  5440. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5441. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  5442. }
  5443. JingleSessionPC.prototype.setLocalDescription = function () {
  5444. var self = this;
  5445. var newssrcs = [];
  5446. var session = transform.parse(this.peerconnection.localDescription.sdp);
  5447. session.media.forEach(function (media) {
  5448. if (media.ssrcs != null && media.ssrcs.length > 0) {
  5449. // TODO(gp) maybe exclude FID streams?
  5450. media.ssrcs.forEach(function (ssrc) {
  5451. if (ssrc.attribute !== 'cname') {
  5452. return;
  5453. }
  5454. newssrcs.push({
  5455. 'ssrc': ssrc.id,
  5456. 'type': media.type
  5457. });
  5458. });
  5459. }
  5460. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  5461. {
  5462. newssrcs.push({
  5463. 'ssrc': self.localStreamsSSRC[media.type],
  5464. 'type': media.type
  5465. });
  5466. }
  5467. });
  5468. console.log('new ssrcs', newssrcs);
  5469. // Bind us as local SSRCs owner
  5470. if (newssrcs.length > 0) {
  5471. for (var i = 1; i <= newssrcs.length; i ++) {
  5472. var ssrc = newssrcs[i-1].ssrc;
  5473. var myJid = self.connection.emuc.myroomjid;
  5474. self.ssrcOwners[ssrc] = myJid;
  5475. }
  5476. }
  5477. }
  5478. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  5479. JingleSessionPC.prototype.sendKeyframe = function () {
  5480. var pc = this.peerconnection;
  5481. console.log('sendkeyframe', pc.iceConnectionState);
  5482. if (pc.iceConnectionState !== 'connected') return; // safe...
  5483. var self = this;
  5484. pc.setRemoteDescription(
  5485. pc.remoteDescription,
  5486. function () {
  5487. pc.createAnswer(
  5488. function (modifiedAnswer) {
  5489. pc.setLocalDescription(
  5490. modifiedAnswer,
  5491. function () {
  5492. // noop
  5493. },
  5494. function (error) {
  5495. console.log('triggerKeyframe setLocalDescription failed', error);
  5496. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  5497. }
  5498. );
  5499. },
  5500. function (error) {
  5501. console.log('triggerKeyframe createAnswer failed', error);
  5502. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  5503. }
  5504. );
  5505. },
  5506. function (error) {
  5507. console.log('triggerKeyframe setRemoteDescription failed', error);
  5508. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  5509. }
  5510. );
  5511. }
  5512. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  5513. var self = this;
  5514. var thessrc;
  5515. var streamId = RTC.getStreamID(data.stream);
  5516. // look up an associated JID for a stream id
  5517. if (!streamId) {
  5518. console.error("No stream ID for", data.stream);
  5519. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  5520. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  5521. var ssrclines
  5522. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  5523. ssrclines = ssrclines.filter(function (line) {
  5524. // NOTE(gp) previously we filtered on the mslabel, but that property
  5525. // is not always present.
  5526. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  5527. if (RTCBrowserType.isTemasysPluginUsed()) {
  5528. return ((line.indexOf('mslabel:' + streamId) !== -1));
  5529. } else {
  5530. return ((line.indexOf('msid:' + streamId) !== -1));
  5531. }
  5532. });
  5533. if (ssrclines.length) {
  5534. thessrc = ssrclines[0].substring(7).split(' ')[0];
  5535. if (!self.ssrcOwners[thessrc]) {
  5536. console.error("No SSRC owner known for: " + thessrc);
  5537. return;
  5538. }
  5539. data.peerjid = self.ssrcOwners[thessrc];
  5540. console.log('associated jid', self.ssrcOwners[thessrc]);
  5541. } else {
  5542. console.error("No SSRC lines for ", streamId);
  5543. }
  5544. }
  5545. this.room.remoteStreamAdded(data, this.sid, thessrc);
  5546. var isVideo = data.stream.getVideoTracks().length > 0;
  5547. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  5548. if (isVideo &&
  5549. data.peerjid && this.peerjid === data.peerjid &&
  5550. data.stream.getVideoTracks().length === 0 &&
  5551. RTC.localVideo.getTracks().length > 0) {
  5552. window.setTimeout(function () {
  5553. self.sendKeyframe();
  5554. }, 3000);
  5555. }
  5556. }
  5557. module.exports = JingleSessionPC;
  5558. },{"../../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){
  5559. /* global $ */
  5560. /*
  5561. Here we do modifications of local video SSRCs. There are 2 situations we have
  5562. to handle:
  5563. 1. We generate SSRC for local recvonly video stream. This is the case when we
  5564. have no local camera and it is not generated automatically, but SSRC=1 is
  5565. used implicitly. If that happens RTCP packets will be dropped by the JVB
  5566. and we won't be able to request video key frames correctly.
  5567. 2. A hack to re-use SSRC of the first video stream for any new stream created
  5568. in future. It turned out that Chrome may keep on using the SSRC of removed
  5569. video stream in RTCP even though a new one has been created. So we just
  5570. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  5571. notifications are blocked once first video SSRC is advertised to the focus.
  5572. What this hack does:
  5573. 1. Stores the SSRC of the first video stream created by
  5574. a) scanning Jingle session-accept/session-invite for existing video SSRC
  5575. b) watching for 'source-add' for new video stream if it has not been
  5576. created in step a)
  5577. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  5578. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  5579. returned to the other parts of the application.
  5580. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  5581. blocks those notifications. This makes Jicofo and all participants think
  5582. that it exists all the time even if the video stream has been removed or
  5583. replaced locally. Thanks to that there is no additional signaling activity
  5584. on video mute or when switching to the desktop stream.
  5585. */
  5586. var SDP = require('./SDP');
  5587. var RTCBrowserType = require('../RTC/RTCBrowserType');
  5588. /**
  5589. * The hack is enabled on all browsers except FF by default
  5590. * FIXME finish the hack once removeStream method is implemented in FF
  5591. * @type {boolean}
  5592. */
  5593. var isEnabled = !RTCBrowserType.isFirefox();
  5594. /**
  5595. * Stored SSRC of local video stream.
  5596. */
  5597. var localVideoSSRC;
  5598. /**
  5599. * SSRC used for recvonly video stream when we have no local camera.
  5600. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  5601. * instead of 1.
  5602. */
  5603. var localRecvOnlySSRC;
  5604. /**
  5605. * cname for <tt>localRecvOnlySSRC</tt>
  5606. */
  5607. var localRecvOnlyCName;
  5608. /**
  5609. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  5610. * from given Jingle IQ.
  5611. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  5612. * @param actionName display name of the action which will be printed in log
  5613. * messages.
  5614. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  5615. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  5616. * other SSRCs left to be signaled after removing it.
  5617. */
  5618. var filterOutSource = function (modifyIq, actionName) {
  5619. var modifyIqTree = $(modifyIq.tree());
  5620. if (!localVideoSSRC)
  5621. return modifyIqTree[0];
  5622. var videoSSRC = modifyIqTree.find(
  5623. '>jingle>content[name="video"]' +
  5624. '>description>source[ssrc="' + localVideoSSRC + '"]');
  5625. if (!videoSSRC.length) {
  5626. return modifyIqTree[0];
  5627. }
  5628. console.info(
  5629. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  5630. videoSSRC.remove();
  5631. // Check if any sources still left to be added/removed
  5632. if (modifyIqTree.find('>jingle>content>description>source').length) {
  5633. return modifyIqTree[0];
  5634. } else {
  5635. return null;
  5636. }
  5637. };
  5638. /**
  5639. * Scans given Jingle IQ for video SSRC and stores it.
  5640. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  5641. */
  5642. var storeLocalVideoSSRC = function (jingleIq) {
  5643. var videoSSRCs =
  5644. $(jingleIq.tree())
  5645. .find('>jingle>content[name="video"]>description>source');
  5646. videoSSRCs.each(function (idx, ssrcElem) {
  5647. if (localVideoSSRC)
  5648. return;
  5649. // We consider SSRC real only if it has msid attribute
  5650. // recvonly streams in FF do not have it as well as local SSRCs
  5651. // we generate for recvonly streams in Chrome
  5652. var ssrSel = $(ssrcElem);
  5653. var msid = ssrSel.find('>parameter[name="msid"]');
  5654. if (msid.length) {
  5655. var ssrcVal = ssrSel.attr('ssrc');
  5656. if (ssrcVal) {
  5657. localVideoSSRC = ssrcVal;
  5658. console.info('Stored local video SSRC' +
  5659. ' for future re-use: ' + localVideoSSRC);
  5660. }
  5661. }
  5662. });
  5663. };
  5664. /**
  5665. * Generates new SSRC for local video recvonly stream.
  5666. * FIXME what about eventual SSRC collision ?
  5667. */
  5668. function generateRecvonlySSRC() {
  5669. //
  5670. localRecvOnlySSRC =
  5671. Math.random().toString(10).substring(2, 11);
  5672. localRecvOnlyCName =
  5673. Math.random().toString(36).substring(2);
  5674. console.info(
  5675. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  5676. ", cname: " + localRecvOnlyCName);
  5677. }
  5678. var LocalSSRCReplacement = {
  5679. /**
  5680. * Method must be called before 'session-initiate' or 'session-invite' is
  5681. * sent. Scans the IQ for local video SSRC and stores it if detected.
  5682. *
  5683. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  5684. * which will be scanned for local video SSRC.
  5685. */
  5686. processSessionInit: function (sessionInit) {
  5687. if (!isEnabled)
  5688. return;
  5689. if (localVideoSSRC) {
  5690. console.error("Local SSRC stored already: " + localVideoSSRC);
  5691. return;
  5692. }
  5693. storeLocalVideoSSRC(sessionInit);
  5694. },
  5695. /**
  5696. * If we have local video SSRC stored searched given
  5697. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  5698. * with the stored one.
  5699. * @param localDescription local description object that will have local
  5700. * video SSRC replaced with the stored one
  5701. * @returns modified <tt>localDescription</tt> object.
  5702. */
  5703. mungeLocalVideoSSRC: function (localDescription) {
  5704. if (!isEnabled)
  5705. return localDescription;
  5706. if (!localDescription) {
  5707. console.warn("localDescription is null or undefined");
  5708. return localDescription;
  5709. }
  5710. // IF we have local video SSRC stored make sure it is replaced
  5711. // with old SSRC
  5712. if (localVideoSSRC) {
  5713. var newSdp = new SDP(localDescription.sdp);
  5714. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  5715. !newSdp.containsSSRC(localVideoSSRC)) {
  5716. // Get new video SSRC
  5717. var map = newSdp.getMediaSsrcMap();
  5718. var videoPart = map[1];
  5719. var videoSSRCs = videoPart.ssrcs;
  5720. var newSSRC = Object.keys(videoSSRCs)[0];
  5721. console.info(
  5722. "Replacing new video SSRC: " + newSSRC +
  5723. " with " + localVideoSSRC);
  5724. localDescription.sdp =
  5725. newSdp.raw.replace(
  5726. new RegExp('a=ssrc:' + newSSRC, 'g'),
  5727. 'a=ssrc:' + localVideoSSRC);
  5728. }
  5729. } else {
  5730. // Make sure we have any SSRC for recvonly video stream
  5731. var sdp = new SDP(localDescription.sdp);
  5732. if (sdp.media[1] && sdp.media[1].indexOf('a=ssrc:') === -1 &&
  5733. sdp.media[1].indexOf('a=recvonly') !== -1) {
  5734. if (!localRecvOnlySSRC) {
  5735. generateRecvonlySSRC();
  5736. }
  5737. console.info('No SSRC in video recvonly stream' +
  5738. ' - adding SSRC: ' + localRecvOnlySSRC);
  5739. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  5740. ' cname:' + localRecvOnlyCName + '\r\n';
  5741. localDescription.sdp = sdp.session + sdp.media.join('');
  5742. }
  5743. }
  5744. return localDescription;
  5745. },
  5746. /**
  5747. * Method must be called before 'source-add' notification is sent. In case
  5748. * we have local video SSRC advertised already it will be removed from the
  5749. * notification. If no other SSRCs are described by given IQ null will be
  5750. * returned which means that there is no point in sending the notification.
  5751. * @param sourceAdd 'source-add' Jingle IQ to be processed
  5752. * @returns modified 'source-add' IQ which can be sent to the focus or
  5753. * <tt>null</tt> if no notification shall be sent. It is no longer
  5754. * a Strophe IQ Builder instance, but DOM element tree.
  5755. */
  5756. processSourceAdd: function (sourceAdd) {
  5757. if (!isEnabled)
  5758. return sourceAdd;
  5759. if (!localVideoSSRC) {
  5760. // Store local SSRC if available
  5761. storeLocalVideoSSRC(sourceAdd);
  5762. return sourceAdd;
  5763. } else {
  5764. return filterOutSource(sourceAdd, 'source-add');
  5765. }
  5766. },
  5767. /**
  5768. * Method must be called before 'source-remove' notification is sent.
  5769. * Removes local video SSRC from the notification. If there are no other
  5770. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  5771. * means that there is no point in sending the notification.
  5772. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  5773. * @returns modified 'source-remove' IQ which can be sent to the focus or
  5774. * <tt>null</tt> if no notification shall be sent. It is no longer
  5775. * a Strophe IQ Builder instance, but DOM element tree.
  5776. */
  5777. processSourceRemove: function (sourceRemove) {
  5778. if (!isEnabled)
  5779. return sourceRemove;
  5780. return filterOutSource(sourceRemove, 'source-remove');
  5781. },
  5782. /**
  5783. * Turns the hack on or off
  5784. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  5785. * to disable it
  5786. */
  5787. setEnabled: function (enabled) {
  5788. isEnabled = enabled;
  5789. }
  5790. };
  5791. module.exports = LocalSSRCReplacement;
  5792. },{"../RTC/RTCBrowserType":14,"./SDP":23}],23:[function(require,module,exports){
  5793. /* jshint -W117 */
  5794. var SDPUtil = require("./SDPUtil");
  5795. // SDP STUFF
  5796. function SDP(sdp) {
  5797. this.media = sdp.split('\r\nm=');
  5798. for (var i = 1; i < this.media.length; i++) {
  5799. this.media[i] = 'm=' + this.media[i];
  5800. if (i != this.media.length - 1) {
  5801. this.media[i] += '\r\n';
  5802. }
  5803. }
  5804. this.session = this.media.shift() + '\r\n';
  5805. this.raw = this.session + this.media.join('');
  5806. }
  5807. /**
  5808. * Returns map of MediaChannel mapped per channel idx.
  5809. */
  5810. SDP.prototype.getMediaSsrcMap = function() {
  5811. var self = this;
  5812. var media_ssrcs = {};
  5813. var tmp;
  5814. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  5815. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  5816. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  5817. var media = {
  5818. mediaindex: mediaindex,
  5819. mid: mid,
  5820. ssrcs: {},
  5821. ssrcGroups: []
  5822. };
  5823. media_ssrcs[mediaindex] = media;
  5824. tmp.forEach(function (line) {
  5825. var linessrc = line.substring(7).split(' ')[0];
  5826. // allocate new ChannelSsrc
  5827. if(!media.ssrcs[linessrc]) {
  5828. media.ssrcs[linessrc] = {
  5829. ssrc: linessrc,
  5830. lines: []
  5831. };
  5832. }
  5833. media.ssrcs[linessrc].lines.push(line);
  5834. });
  5835. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  5836. tmp.forEach(function(line){
  5837. var semantics = line.substr(0, idx).substr(13);
  5838. var ssrcs = line.substr(14 + semantics.length).split(' ');
  5839. if (ssrcs.length != 0) {
  5840. media.ssrcGroups.push({
  5841. semantics: semantics,
  5842. ssrcs: ssrcs
  5843. });
  5844. }
  5845. });
  5846. }
  5847. return media_ssrcs;
  5848. };
  5849. /**
  5850. * Returns <tt>true</tt> if this SDP contains given SSRC.
  5851. * @param ssrc the ssrc to check.
  5852. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  5853. */
  5854. SDP.prototype.containsSSRC = function(ssrc) {
  5855. var medias = this.getMediaSsrcMap();
  5856. var contains = false;
  5857. Object.keys(medias).forEach(function(mediaindex){
  5858. var media = medias[mediaindex];
  5859. //console.log("Check", channel, ssrc);
  5860. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  5861. contains = true;
  5862. }
  5863. });
  5864. return contains;
  5865. };
  5866. // remove iSAC and CN from SDP
  5867. SDP.prototype.mangle = function () {
  5868. var i, j, mline, lines, rtpmap, newdesc;
  5869. for (i = 0; i < this.media.length; i++) {
  5870. lines = this.media[i].split('\r\n');
  5871. lines.pop(); // remove empty last element
  5872. mline = SDPUtil.parse_mline(lines.shift());
  5873. if (mline.media != 'audio')
  5874. continue;
  5875. newdesc = '';
  5876. mline.fmt.length = 0;
  5877. for (j = 0; j < lines.length; j++) {
  5878. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  5879. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  5880. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  5881. continue;
  5882. mline.fmt.push(rtpmap.id);
  5883. newdesc += lines[j] + '\r\n';
  5884. } else {
  5885. newdesc += lines[j] + '\r\n';
  5886. }
  5887. }
  5888. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  5889. this.media[i] += newdesc;
  5890. }
  5891. this.raw = this.session + this.media.join('');
  5892. };
  5893. // remove lines matching prefix from session section
  5894. SDP.prototype.removeSessionLines = function(prefix) {
  5895. var self = this;
  5896. var lines = SDPUtil.find_lines(this.session, prefix);
  5897. lines.forEach(function(line) {
  5898. self.session = self.session.replace(line + '\r\n', '');
  5899. });
  5900. this.raw = this.session + this.media.join('');
  5901. return lines;
  5902. }
  5903. // remove lines matching prefix from a media section specified by mediaindex
  5904. // TODO: non-numeric mediaindex could match mid
  5905. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  5906. var self = this;
  5907. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  5908. lines.forEach(function(line) {
  5909. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  5910. });
  5911. this.raw = this.session + this.media.join('');
  5912. return lines;
  5913. }
  5914. // add content's to a jingle element
  5915. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  5916. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  5917. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  5918. var self = this;
  5919. // new bundle plan
  5920. if (SDPUtil.find_line(this.session, 'a=group:')) {
  5921. lines = SDPUtil.find_lines(this.session, 'a=group:');
  5922. for (i = 0; i < lines.length; i++) {
  5923. tmp = lines[i].split(' ');
  5924. var semantics = tmp.shift().substr(8);
  5925. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  5926. for (j = 0; j < tmp.length; j++) {
  5927. elem.c('content', {name: tmp[j]}).up();
  5928. }
  5929. elem.up();
  5930. }
  5931. }
  5932. for (i = 0; i < this.media.length; i++) {
  5933. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  5934. if (!(mline.media === 'audio' ||
  5935. mline.media === 'video' ||
  5936. mline.media === 'application'))
  5937. {
  5938. continue;
  5939. }
  5940. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  5941. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  5942. } else {
  5943. if(ssrcs && ssrcs[mline.media])
  5944. {
  5945. ssrc = ssrcs[mline.media];
  5946. }
  5947. else
  5948. ssrc = false;
  5949. }
  5950. elem.c('content', {creator: thecreator, name: mline.media});
  5951. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  5952. // prefer identifier from a=mid if present
  5953. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  5954. elem.attrs({ name: mid });
  5955. }
  5956. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  5957. {
  5958. elem.c('description',
  5959. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  5960. media: mline.media });
  5961. if (ssrc) {
  5962. elem.attrs({ssrc: ssrc});
  5963. }
  5964. for (j = 0; j < mline.fmt.length; j++) {
  5965. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  5966. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  5967. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  5968. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  5969. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  5970. for (k = 0; k < tmp.length; k++) {
  5971. elem.c('parameter', tmp[k]).up();
  5972. }
  5973. }
  5974. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  5975. elem.up();
  5976. }
  5977. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  5978. elem.c('encryption', {required: 1});
  5979. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  5980. crypto.forEach(function(line) {
  5981. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  5982. });
  5983. elem.up(); // end of encryption
  5984. }
  5985. if (ssrc) {
  5986. // new style mapping
  5987. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  5988. // FIXME: group by ssrc and support multiple different ssrcs
  5989. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  5990. if(ssrclines.length > 0) {
  5991. ssrclines.forEach(function (line) {
  5992. idx = line.indexOf(' ');
  5993. var linessrc = line.substr(0, idx).substr(7);
  5994. if (linessrc != ssrc) {
  5995. elem.up();
  5996. ssrc = linessrc;
  5997. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  5998. }
  5999. var kv = line.substr(idx + 1);
  6000. elem.c('parameter');
  6001. if (kv.indexOf(':') == -1) {
  6002. elem.attrs({ name: kv });
  6003. } else {
  6004. var k = kv.split(':', 2)[0];
  6005. elem.attrs({ name: k });
  6006. var v = kv.split(':', 2)[1];
  6007. v = SDPUtil.filter_special_chars(v);
  6008. elem.attrs({ value: v });
  6009. }
  6010. elem.up();
  6011. });
  6012. }
  6013. else
  6014. {
  6015. elem.up();
  6016. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  6017. elem.c('parameter');
  6018. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  6019. elem.up();
  6020. var msid = null;
  6021. if(mline.media == "audio")
  6022. {
  6023. msid = APP.RTC.localAudio.getId();
  6024. }
  6025. else
  6026. {
  6027. msid = APP.RTC.localVideo.getId();
  6028. }
  6029. if(msid != null)
  6030. {
  6031. msid = SDPUtil.filter_special_chars(msid);
  6032. elem.c('parameter');
  6033. elem.attrs({name: "msid", value:msid});
  6034. elem.up();
  6035. elem.c('parameter');
  6036. elem.attrs({name: "mslabel", value:msid});
  6037. elem.up();
  6038. elem.c('parameter');
  6039. elem.attrs({name: "label", value:msid});
  6040. elem.up();
  6041. }
  6042. }
  6043. elem.up();
  6044. // XEP-0339 handle ssrc-group attributes
  6045. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  6046. ssrc_group_lines.forEach(function(line) {
  6047. idx = line.indexOf(' ');
  6048. var semantics = line.substr(0, idx).substr(13);
  6049. var ssrcs = line.substr(14 + semantics.length).split(' ');
  6050. if (ssrcs.length != 0) {
  6051. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  6052. ssrcs.forEach(function(ssrc) {
  6053. elem.c('source', { ssrc: ssrc })
  6054. .up();
  6055. });
  6056. elem.up();
  6057. }
  6058. });
  6059. }
  6060. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  6061. elem.c('rtcp-mux').up();
  6062. }
  6063. // XEP-0293 -- map a=rtcp-fb:*
  6064. this.RtcpFbToJingle(i, elem, '*');
  6065. // XEP-0294
  6066. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  6067. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  6068. for (j = 0; j < lines.length; j++) {
  6069. tmp = SDPUtil.parse_extmap(lines[j]);
  6070. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  6071. uri: tmp.uri,
  6072. id: tmp.value });
  6073. if (tmp.hasOwnProperty('direction')) {
  6074. switch (tmp.direction) {
  6075. case 'sendonly':
  6076. elem.attrs({senders: 'responder'});
  6077. break;
  6078. case 'recvonly':
  6079. elem.attrs({senders: 'initiator'});
  6080. break;
  6081. case 'sendrecv':
  6082. elem.attrs({senders: 'both'});
  6083. break;
  6084. case 'inactive':
  6085. elem.attrs({senders: 'none'});
  6086. break;
  6087. }
  6088. }
  6089. // TODO: handle params
  6090. elem.up();
  6091. }
  6092. }
  6093. elem.up(); // end of description
  6094. }
  6095. // map ice-ufrag/pwd, dtls fingerprint, candidates
  6096. this.TransportToJingle(i, elem);
  6097. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  6098. elem.attrs({senders: 'both'});
  6099. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  6100. elem.attrs({senders: 'initiator'});
  6101. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  6102. elem.attrs({senders: 'responder'});
  6103. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  6104. elem.attrs({senders: 'none'});
  6105. }
  6106. if (mline.port == '0') {
  6107. // estos hack to reject an m-line
  6108. elem.attrs({senders: 'rejected'});
  6109. }
  6110. elem.up(); // end of content
  6111. }
  6112. elem.up();
  6113. return elem;
  6114. };
  6115. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  6116. var i = mediaindex;
  6117. var tmp;
  6118. var self = this;
  6119. elem.c('transport');
  6120. // XEP-0343 DTLS/SCTP
  6121. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  6122. {
  6123. var sctpmap = SDPUtil.find_line(
  6124. this.media[i], 'a=sctpmap:', self.session);
  6125. if (sctpmap)
  6126. {
  6127. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  6128. elem.c('sctpmap',
  6129. {
  6130. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  6131. number: sctpAttrs[0], /* SCTP port */
  6132. protocol: sctpAttrs[1], /* protocol */
  6133. });
  6134. // Optional stream count attribute
  6135. if (sctpAttrs.length > 2)
  6136. elem.attrs({ streams: sctpAttrs[2]});
  6137. elem.up();
  6138. }
  6139. }
  6140. // XEP-0320
  6141. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  6142. fingerprints.forEach(function(line) {
  6143. tmp = SDPUtil.parse_fingerprint(line);
  6144. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  6145. elem.c('fingerprint').t(tmp.fingerprint);
  6146. delete tmp.fingerprint;
  6147. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  6148. if (line) {
  6149. tmp.setup = line.substr(8);
  6150. }
  6151. elem.attrs(tmp);
  6152. elem.up(); // end of fingerprint
  6153. });
  6154. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  6155. if (tmp) {
  6156. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6157. elem.attrs(tmp);
  6158. // XEP-0176
  6159. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  6160. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  6161. lines.forEach(function (line) {
  6162. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  6163. });
  6164. }
  6165. }
  6166. elem.up(); // end of transport
  6167. }
  6168. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  6169. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  6170. lines.forEach(function (line) {
  6171. var tmp = SDPUtil.parse_rtcpfb(line);
  6172. if (tmp.type == 'trr-int') {
  6173. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  6174. elem.up();
  6175. } else {
  6176. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  6177. if (tmp.params.length > 0) {
  6178. elem.attrs({'subtype': tmp.params[0]});
  6179. }
  6180. elem.up();
  6181. }
  6182. });
  6183. };
  6184. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  6185. var media = '';
  6186. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  6187. if (tmp.length) {
  6188. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  6189. if (tmp.attr('value')) {
  6190. media += tmp.attr('value');
  6191. } else {
  6192. media += '0';
  6193. }
  6194. media += '\r\n';
  6195. }
  6196. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  6197. tmp.each(function () {
  6198. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  6199. if ($(this).attr('subtype')) {
  6200. media += ' ' + $(this).attr('subtype');
  6201. }
  6202. media += '\r\n';
  6203. });
  6204. return media;
  6205. };
  6206. // construct an SDP from a jingle stanza
  6207. SDP.prototype.fromJingle = function (jingle) {
  6208. var self = this;
  6209. this.raw = 'v=0\r\n' +
  6210. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  6211. 's=-\r\n' +
  6212. 't=0 0\r\n';
  6213. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  6214. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  6215. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  6216. var contents = $(group).find('>content').map(function (idx, content) {
  6217. return content.getAttribute('name');
  6218. }).get();
  6219. if (contents.length > 0) {
  6220. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  6221. }
  6222. });
  6223. }
  6224. this.session = this.raw;
  6225. jingle.find('>content').each(function () {
  6226. var m = self.jingle2media($(this));
  6227. self.media.push(m);
  6228. });
  6229. // reconstruct msid-semantic -- apparently not necessary
  6230. /*
  6231. var msid = SDPUtil.parse_ssrc(this.raw);
  6232. if (msid.hasOwnProperty('mslabel')) {
  6233. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  6234. }
  6235. */
  6236. this.raw = this.session + this.media.join('');
  6237. };
  6238. // translate a jingle content element into an an SDP media part
  6239. SDP.prototype.jingle2media = function (content) {
  6240. var media = '',
  6241. desc = content.find('description'),
  6242. ssrc = desc.attr('ssrc'),
  6243. self = this,
  6244. tmp;
  6245. var sctp = content.find(
  6246. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  6247. tmp = { media: desc.attr('media') };
  6248. tmp.port = '1';
  6249. if (content.attr('senders') == 'rejected') {
  6250. // estos hack to reject an m-line.
  6251. tmp.port = '0';
  6252. }
  6253. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  6254. if (sctp.length)
  6255. tmp.proto = 'DTLS/SCTP';
  6256. else
  6257. tmp.proto = 'RTP/SAVPF';
  6258. } else {
  6259. tmp.proto = 'RTP/AVPF';
  6260. }
  6261. if (!sctp.length)
  6262. {
  6263. tmp.fmt = desc.find('payload-type').map(
  6264. function () { return this.getAttribute('id'); }).get();
  6265. media += SDPUtil.build_mline(tmp) + '\r\n';
  6266. }
  6267. else
  6268. {
  6269. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  6270. media += 'a=sctpmap:' + sctp.attr('number') +
  6271. ' ' + sctp.attr('protocol');
  6272. var streamCount = sctp.attr('streams');
  6273. if (streamCount)
  6274. media += ' ' + streamCount + '\r\n';
  6275. else
  6276. media += '\r\n';
  6277. }
  6278. media += 'c=IN IP4 0.0.0.0\r\n';
  6279. if (!sctp.length)
  6280. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  6281. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  6282. if (tmp.length) {
  6283. if (tmp.attr('ufrag')) {
  6284. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  6285. }
  6286. if (tmp.attr('pwd')) {
  6287. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  6288. }
  6289. tmp.find('>fingerprint').each(function () {
  6290. // FIXME: check namespace at some point
  6291. media += 'a=fingerprint:' + this.getAttribute('hash');
  6292. media += ' ' + $(this).text();
  6293. media += '\r\n';
  6294. if (this.getAttribute('setup')) {
  6295. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  6296. }
  6297. });
  6298. }
  6299. switch (content.attr('senders')) {
  6300. case 'initiator':
  6301. media += 'a=sendonly\r\n';
  6302. break;
  6303. case 'responder':
  6304. media += 'a=recvonly\r\n';
  6305. break;
  6306. case 'none':
  6307. media += 'a=inactive\r\n';
  6308. break;
  6309. case 'both':
  6310. media += 'a=sendrecv\r\n';
  6311. break;
  6312. }
  6313. media += 'a=mid:' + content.attr('name') + '\r\n';
  6314. // <description><rtcp-mux/></description>
  6315. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  6316. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  6317. if (desc.find('rtcp-mux').length) {
  6318. media += 'a=rtcp-mux\r\n';
  6319. }
  6320. if (desc.find('encryption').length) {
  6321. desc.find('encryption>crypto').each(function () {
  6322. media += 'a=crypto:' + this.getAttribute('tag');
  6323. media += ' ' + this.getAttribute('crypto-suite');
  6324. media += ' ' + this.getAttribute('key-params');
  6325. if (this.getAttribute('session-params')) {
  6326. media += ' ' + this.getAttribute('session-params');
  6327. }
  6328. media += '\r\n';
  6329. });
  6330. }
  6331. desc.find('payload-type').each(function () {
  6332. media += SDPUtil.build_rtpmap(this) + '\r\n';
  6333. if ($(this).find('>parameter').length) {
  6334. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  6335. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  6336. media += '\r\n';
  6337. }
  6338. // xep-0293
  6339. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  6340. });
  6341. // xep-0293
  6342. media += self.RtcpFbFromJingle(desc, '*');
  6343. // xep-0294
  6344. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  6345. tmp.each(function () {
  6346. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  6347. });
  6348. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  6349. media += SDPUtil.candidateFromJingle(this);
  6350. });
  6351. // XEP-0339 handle ssrc-group attributes
  6352. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6353. var semantics = this.getAttribute('semantics');
  6354. var ssrcs = $(this).find('>source').map(function() {
  6355. return this.getAttribute('ssrc');
  6356. }).get();
  6357. if (ssrcs.length != 0) {
  6358. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6359. }
  6360. });
  6361. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  6362. tmp.each(function () {
  6363. var ssrc = this.getAttribute('ssrc');
  6364. $(this).find('>parameter').each(function () {
  6365. var name = this.getAttribute('name');
  6366. var value = this.getAttribute('value');
  6367. value = SDPUtil.filter_special_chars(value);
  6368. media += 'a=ssrc:' + ssrc + ' ' + name;
  6369. if (value && value.length)
  6370. media += ':' + value;
  6371. media += '\r\n';
  6372. });
  6373. });
  6374. return media;
  6375. };
  6376. module.exports = SDP;
  6377. },{"./SDPUtil":25}],24:[function(require,module,exports){
  6378. var SDPUtil = require("./SDPUtil");
  6379. function SDPDiffer(mySDP, otherSDP) {
  6380. this.mySDP = mySDP;
  6381. this.otherSDP = otherSDP;
  6382. }
  6383. /**
  6384. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  6385. * @param otherSdp the other SDP to check ssrc with.
  6386. */
  6387. SDPDiffer.prototype.getNewMedia = function() {
  6388. // this could be useful in Array.prototype.
  6389. function arrayEquals(array) {
  6390. // if the other array is a falsy value, return
  6391. if (!array)
  6392. return false;
  6393. // compare lengths - can save a lot of time
  6394. if (this.length != array.length)
  6395. return false;
  6396. for (var i = 0, l=this.length; i < l; i++) {
  6397. // Check if we have nested arrays
  6398. if (this[i] instanceof Array && array[i] instanceof Array) {
  6399. // recurse into the nested arrays
  6400. if (!this[i].equals(array[i]))
  6401. return false;
  6402. }
  6403. else if (this[i] != array[i]) {
  6404. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  6405. return false;
  6406. }
  6407. }
  6408. return true;
  6409. }
  6410. var myMedias = this.mySDP.getMediaSsrcMap();
  6411. var othersMedias = this.otherSDP.getMediaSsrcMap();
  6412. var newMedia = {};
  6413. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  6414. var myMedia = myMedias[othersMediaIdx];
  6415. var othersMedia = othersMedias[othersMediaIdx];
  6416. if(!myMedia && othersMedia) {
  6417. // Add whole channel
  6418. newMedia[othersMediaIdx] = othersMedia;
  6419. return;
  6420. }
  6421. // Look for new ssrcs accross the channel
  6422. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  6423. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  6424. // Allocate channel if we've found ssrc that doesn't exist in our channel
  6425. if(!newMedia[othersMediaIdx]){
  6426. newMedia[othersMediaIdx] = {
  6427. mediaindex: othersMedia.mediaindex,
  6428. mid: othersMedia.mid,
  6429. ssrcs: {},
  6430. ssrcGroups: []
  6431. };
  6432. }
  6433. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  6434. }
  6435. });
  6436. // Look for new ssrc groups across the channels
  6437. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  6438. // try to match the other ssrc-group with an ssrc-group of ours
  6439. var matched = false;
  6440. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  6441. var mySsrcGroup = myMedia.ssrcGroups[i];
  6442. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  6443. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  6444. matched = true;
  6445. break;
  6446. }
  6447. }
  6448. if (!matched) {
  6449. // Allocate channel if we've found an ssrc-group that doesn't
  6450. // exist in our channel
  6451. if(!newMedia[othersMediaIdx]){
  6452. newMedia[othersMediaIdx] = {
  6453. mediaindex: othersMedia.mediaindex,
  6454. mid: othersMedia.mid,
  6455. ssrcs: {},
  6456. ssrcGroups: []
  6457. };
  6458. }
  6459. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  6460. }
  6461. });
  6462. });
  6463. return newMedia;
  6464. };
  6465. /**
  6466. * Sends SSRC update IQ.
  6467. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  6468. * @param sid session identifier that will be put into the IQ.
  6469. * @param initiator initiator identifier.
  6470. * @param toJid destination Jid
  6471. * @param isAdd indicates if this is remove or add operation.
  6472. */
  6473. SDPDiffer.prototype.toJingle = function(modify) {
  6474. var sdpMediaSsrcs = this.getNewMedia();
  6475. var self = this;
  6476. // FIXME: only announce video ssrcs since we mix audio and dont need
  6477. // the audio ssrcs therefore
  6478. var modified = false;
  6479. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  6480. modified = true;
  6481. var media = sdpMediaSsrcs[mediaindex];
  6482. modify.c('content', {name: media.mid});
  6483. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  6484. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  6485. // generate sources from lines
  6486. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  6487. var mediaSsrc = media.ssrcs[ssrcNum];
  6488. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  6489. modify.attrs({ssrc: mediaSsrc.ssrc});
  6490. // iterate over ssrc lines
  6491. mediaSsrc.lines.forEach(function (line) {
  6492. var idx = line.indexOf(' ');
  6493. var kv = line.substr(idx + 1);
  6494. modify.c('parameter');
  6495. if (kv.indexOf(':') == -1) {
  6496. modify.attrs({ name: kv });
  6497. } else {
  6498. var nv = kv.split(':', 2);
  6499. var name = nv[0];
  6500. var value = SDPUtil.filter_special_chars(nv[1]);
  6501. modify.attrs({ name: name });
  6502. modify.attrs({ value: value });
  6503. }
  6504. modify.up(); // end of parameter
  6505. });
  6506. modify.up(); // end of source
  6507. });
  6508. // generate source groups from lines
  6509. media.ssrcGroups.forEach(function(ssrcGroup) {
  6510. if (ssrcGroup.ssrcs.length != 0) {
  6511. modify.c('ssrc-group', {
  6512. semantics: ssrcGroup.semantics,
  6513. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  6514. });
  6515. ssrcGroup.ssrcs.forEach(function (ssrc) {
  6516. modify.c('source', { ssrc: ssrc })
  6517. .up(); // end of source
  6518. });
  6519. modify.up(); // end of ssrc-group
  6520. }
  6521. });
  6522. modify.up(); // end of description
  6523. modify.up(); // end of content
  6524. });
  6525. return modified;
  6526. };
  6527. module.exports = SDPDiffer;
  6528. },{"./SDPUtil":25}],25:[function(require,module,exports){
  6529. SDPUtil = {
  6530. filter_special_chars: function (text) {
  6531. return text.replace(/[\\\/\{,\}\+]/g, "");
  6532. },
  6533. iceparams: function (mediadesc, sessiondesc) {
  6534. var data = null;
  6535. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  6536. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  6537. data = {
  6538. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  6539. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  6540. };
  6541. }
  6542. return data;
  6543. },
  6544. parse_iceufrag: function (line) {
  6545. return line.substring(12);
  6546. },
  6547. build_iceufrag: function (frag) {
  6548. return 'a=ice-ufrag:' + frag;
  6549. },
  6550. parse_icepwd: function (line) {
  6551. return line.substring(10);
  6552. },
  6553. build_icepwd: function (pwd) {
  6554. return 'a=ice-pwd:' + pwd;
  6555. },
  6556. parse_mid: function (line) {
  6557. return line.substring(6);
  6558. },
  6559. parse_mline: function (line) {
  6560. var parts = line.substring(2).split(' '),
  6561. data = {};
  6562. data.media = parts.shift();
  6563. data.port = parts.shift();
  6564. data.proto = parts.shift();
  6565. if (parts[parts.length - 1] === '') { // trailing whitespace
  6566. parts.pop();
  6567. }
  6568. data.fmt = parts;
  6569. return data;
  6570. },
  6571. build_mline: function (mline) {
  6572. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  6573. },
  6574. parse_rtpmap: function (line) {
  6575. var parts = line.substring(9).split(' '),
  6576. data = {};
  6577. data.id = parts.shift();
  6578. parts = parts[0].split('/');
  6579. data.name = parts.shift();
  6580. data.clockrate = parts.shift();
  6581. data.channels = parts.length ? parts.shift() : '1';
  6582. return data;
  6583. },
  6584. /**
  6585. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  6586. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  6587. * @returns [SCTP port number, protocol, streams]
  6588. */
  6589. parse_sctpmap: function (line)
  6590. {
  6591. var parts = line.substring(10).split(' ');
  6592. var sctpPort = parts[0];
  6593. var protocol = parts[1];
  6594. // Stream count is optional
  6595. var streamCount = parts.length > 2 ? parts[2] : null;
  6596. return [sctpPort, protocol, streamCount];// SCTP port
  6597. },
  6598. build_rtpmap: function (el) {
  6599. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  6600. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  6601. line += '/' + el.getAttribute('channels');
  6602. }
  6603. return line;
  6604. },
  6605. parse_crypto: function (line) {
  6606. var parts = line.substring(9).split(' '),
  6607. data = {};
  6608. data.tag = parts.shift();
  6609. data['crypto-suite'] = parts.shift();
  6610. data['key-params'] = parts.shift();
  6611. if (parts.length) {
  6612. data['session-params'] = parts.join(' ');
  6613. }
  6614. return data;
  6615. },
  6616. parse_fingerprint: function (line) { // RFC 4572
  6617. var parts = line.substring(14).split(' '),
  6618. data = {};
  6619. data.hash = parts.shift();
  6620. data.fingerprint = parts.shift();
  6621. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  6622. return data;
  6623. },
  6624. parse_fmtp: function (line) {
  6625. var parts = line.split(' '),
  6626. i, key, value,
  6627. data = [];
  6628. parts.shift();
  6629. parts = parts.join(' ').split(';');
  6630. for (i = 0; i < parts.length; i++) {
  6631. key = parts[i].split('=')[0];
  6632. while (key.length && key[0] == ' ') {
  6633. key = key.substring(1);
  6634. }
  6635. value = parts[i].split('=')[1];
  6636. if (key && value) {
  6637. data.push({name: key, value: value});
  6638. } else if (key) {
  6639. // rfc 4733 (DTMF) style stuff
  6640. data.push({name: '', value: key});
  6641. }
  6642. }
  6643. return data;
  6644. },
  6645. parse_icecandidate: function (line) {
  6646. var candidate = {},
  6647. elems = line.split(' ');
  6648. candidate.foundation = elems[0].substring(12);
  6649. candidate.component = elems[1];
  6650. candidate.protocol = elems[2].toLowerCase();
  6651. candidate.priority = elems[3];
  6652. candidate.ip = elems[4];
  6653. candidate.port = elems[5];
  6654. // elems[6] => "typ"
  6655. candidate.type = elems[7];
  6656. candidate.generation = 0; // default value, may be overwritten below
  6657. for (var i = 8; i < elems.length; i += 2) {
  6658. switch (elems[i]) {
  6659. case 'raddr':
  6660. candidate['rel-addr'] = elems[i + 1];
  6661. break;
  6662. case 'rport':
  6663. candidate['rel-port'] = elems[i + 1];
  6664. break;
  6665. case 'generation':
  6666. candidate.generation = elems[i + 1];
  6667. break;
  6668. case 'tcptype':
  6669. candidate.tcptype = elems[i + 1];
  6670. break;
  6671. default: // TODO
  6672. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  6673. }
  6674. }
  6675. candidate.network = '1';
  6676. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  6677. return candidate;
  6678. },
  6679. build_icecandidate: function (cand) {
  6680. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  6681. line += ' ';
  6682. switch (cand.type) {
  6683. case 'srflx':
  6684. case 'prflx':
  6685. case 'relay':
  6686. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  6687. line += 'raddr';
  6688. line += ' ';
  6689. line += cand['rel-addr'];
  6690. line += ' ';
  6691. line += 'rport';
  6692. line += ' ';
  6693. line += cand['rel-port'];
  6694. line += ' ';
  6695. }
  6696. break;
  6697. }
  6698. if (cand.hasOwnAttribute('tcptype')) {
  6699. line += 'tcptype';
  6700. line += ' ';
  6701. line += cand.tcptype;
  6702. line += ' ';
  6703. }
  6704. line += 'generation';
  6705. line += ' ';
  6706. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  6707. return line;
  6708. },
  6709. parse_ssrc: function (desc) {
  6710. // proprietary mapping of a=ssrc lines
  6711. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  6712. // and parse according to that
  6713. var lines = desc.split('\r\n'),
  6714. data = {};
  6715. for (var i = 0; i < lines.length; i++) {
  6716. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  6717. var idx = lines[i].indexOf(' ');
  6718. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  6719. }
  6720. }
  6721. return data;
  6722. },
  6723. parse_rtcpfb: function (line) {
  6724. var parts = line.substr(10).split(' ');
  6725. var data = {};
  6726. data.pt = parts.shift();
  6727. data.type = parts.shift();
  6728. data.params = parts;
  6729. return data;
  6730. },
  6731. parse_extmap: function (line) {
  6732. var parts = line.substr(9).split(' ');
  6733. var data = {};
  6734. data.value = parts.shift();
  6735. if (data.value.indexOf('/') != -1) {
  6736. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  6737. data.value = data.value.substr(0, data.value.indexOf('/'));
  6738. } else {
  6739. data.direction = 'both';
  6740. }
  6741. data.uri = parts.shift();
  6742. data.params = parts;
  6743. return data;
  6744. },
  6745. find_line: function (haystack, needle, sessionpart) {
  6746. var lines = haystack.split('\r\n');
  6747. for (var i = 0; i < lines.length; i++) {
  6748. if (lines[i].substring(0, needle.length) == needle) {
  6749. return lines[i];
  6750. }
  6751. }
  6752. if (!sessionpart) {
  6753. return false;
  6754. }
  6755. // search session part
  6756. lines = sessionpart.split('\r\n');
  6757. for (var j = 0; j < lines.length; j++) {
  6758. if (lines[j].substring(0, needle.length) == needle) {
  6759. return lines[j];
  6760. }
  6761. }
  6762. return false;
  6763. },
  6764. find_lines: function (haystack, needle, sessionpart) {
  6765. var lines = haystack.split('\r\n'),
  6766. needles = [];
  6767. for (var i = 0; i < lines.length; i++) {
  6768. if (lines[i].substring(0, needle.length) == needle)
  6769. needles.push(lines[i]);
  6770. }
  6771. if (needles.length || !sessionpart) {
  6772. return needles;
  6773. }
  6774. // search session part
  6775. lines = sessionpart.split('\r\n');
  6776. for (var j = 0; j < lines.length; j++) {
  6777. if (lines[j].substring(0, needle.length) == needle) {
  6778. needles.push(lines[j]);
  6779. }
  6780. }
  6781. return needles;
  6782. },
  6783. candidateToJingle: function (line) {
  6784. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  6785. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  6786. if (line.indexOf('candidate:') === 0) {
  6787. line = 'a=' + line;
  6788. } else if (line.substring(0, 12) != 'a=candidate:') {
  6789. console.log('parseCandidate called with a line that is not a candidate line');
  6790. console.log(line);
  6791. return null;
  6792. }
  6793. if (line.substring(line.length - 2) == '\r\n') // chomp it
  6794. line = line.substring(0, line.length - 2);
  6795. var candidate = {},
  6796. elems = line.split(' '),
  6797. i;
  6798. if (elems[6] != 'typ') {
  6799. console.log('did not find typ in the right place');
  6800. console.log(line);
  6801. return null;
  6802. }
  6803. candidate.foundation = elems[0].substring(12);
  6804. candidate.component = elems[1];
  6805. candidate.protocol = elems[2].toLowerCase();
  6806. candidate.priority = elems[3];
  6807. candidate.ip = elems[4];
  6808. candidate.port = elems[5];
  6809. // elems[6] => "typ"
  6810. candidate.type = elems[7];
  6811. candidate.generation = '0'; // default, may be overwritten below
  6812. for (i = 8; i < elems.length; i += 2) {
  6813. switch (elems[i]) {
  6814. case 'raddr':
  6815. candidate['rel-addr'] = elems[i + 1];
  6816. break;
  6817. case 'rport':
  6818. candidate['rel-port'] = elems[i + 1];
  6819. break;
  6820. case 'generation':
  6821. candidate.generation = elems[i + 1];
  6822. break;
  6823. case 'tcptype':
  6824. candidate.tcptype = elems[i + 1];
  6825. break;
  6826. default: // TODO
  6827. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  6828. }
  6829. }
  6830. candidate.network = '1';
  6831. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  6832. return candidate;
  6833. },
  6834. candidateFromJingle: function (cand) {
  6835. var line = 'a=candidate:';
  6836. line += cand.getAttribute('foundation');
  6837. line += ' ';
  6838. line += cand.getAttribute('component');
  6839. line += ' ';
  6840. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  6841. line += ' ';
  6842. line += cand.getAttribute('priority');
  6843. line += ' ';
  6844. line += cand.getAttribute('ip');
  6845. line += ' ';
  6846. line += cand.getAttribute('port');
  6847. line += ' ';
  6848. line += 'typ';
  6849. line += ' ' + cand.getAttribute('type');
  6850. line += ' ';
  6851. switch (cand.getAttribute('type')) {
  6852. case 'srflx':
  6853. case 'prflx':
  6854. case 'relay':
  6855. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  6856. line += 'raddr';
  6857. line += ' ';
  6858. line += cand.getAttribute('rel-addr');
  6859. line += ' ';
  6860. line += 'rport';
  6861. line += ' ';
  6862. line += cand.getAttribute('rel-port');
  6863. line += ' ';
  6864. }
  6865. break;
  6866. }
  6867. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  6868. line += 'tcptype';
  6869. line += ' ';
  6870. line += cand.getAttribute('tcptype');
  6871. line += ' ';
  6872. }
  6873. line += 'generation';
  6874. line += ' ';
  6875. line += cand.getAttribute('generation') || '0';
  6876. return line + '\r\n';
  6877. }
  6878. };
  6879. module.exports = SDPUtil;
  6880. },{}],26:[function(require,module,exports){
  6881. var RTC = require('../RTC/RTC');
  6882. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  6883. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  6884. var SSRCReplacement = require("./LocalSSRCReplacement");
  6885. function TraceablePeerConnection(ice_config, constraints, session) {
  6886. var self = this;
  6887. this.session = session;
  6888. var RTCPeerConnectionType = null;
  6889. if (RTCBrowserType.isFirefox()) {
  6890. RTCPeerConnectionType = mozRTCPeerConnection;
  6891. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  6892. RTCPeerConnectionType = RTCPeerConnection;
  6893. } else {
  6894. RTCPeerConnectionType = webkitRTCPeerConnection;
  6895. }
  6896. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  6897. this.updateLog = [];
  6898. this.stats = {};
  6899. this.statsinterval = null;
  6900. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  6901. var Interop = require('sdp-interop').Interop;
  6902. this.interop = new Interop();
  6903. var Simulcast = require('sdp-simulcast');
  6904. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  6905. // override as desired
  6906. this.trace = function (what, info) {
  6907. /*console.warn('WTRACE', what, info);
  6908. if (info && RTCBrowserType.isIExplorer()) {
  6909. if (info.length > 1024) {
  6910. console.warn('WTRACE', what, info.substr(1024));
  6911. }
  6912. if (info.length > 2048) {
  6913. console.warn('WTRACE', what, info.substr(2048));
  6914. }
  6915. }*/
  6916. self.updateLog.push({
  6917. time: new Date(),
  6918. type: what,
  6919. value: info || ""
  6920. });
  6921. };
  6922. this.onicecandidate = null;
  6923. this.peerconnection.onicecandidate = function (event) {
  6924. // FIXME: this causes stack overflow with Temasys Plugin
  6925. if (!RTCBrowserType.isTemasysPluginUsed())
  6926. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  6927. if (self.onicecandidate !== null) {
  6928. self.onicecandidate(event);
  6929. }
  6930. };
  6931. this.onaddstream = null;
  6932. this.peerconnection.onaddstream = function (event) {
  6933. self.trace('onaddstream', event.stream.id);
  6934. if (self.onaddstream !== null) {
  6935. self.onaddstream(event);
  6936. }
  6937. };
  6938. this.onremovestream = null;
  6939. this.peerconnection.onremovestream = function (event) {
  6940. self.trace('onremovestream', event.stream.id);
  6941. if (self.onremovestream !== null) {
  6942. self.onremovestream(event);
  6943. }
  6944. };
  6945. this.onsignalingstatechange = null;
  6946. this.peerconnection.onsignalingstatechange = function (event) {
  6947. self.trace('onsignalingstatechange', self.signalingState);
  6948. if (self.onsignalingstatechange !== null) {
  6949. self.onsignalingstatechange(event);
  6950. }
  6951. };
  6952. this.oniceconnectionstatechange = null;
  6953. this.peerconnection.oniceconnectionstatechange = function (event) {
  6954. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  6955. if (self.oniceconnectionstatechange !== null) {
  6956. self.oniceconnectionstatechange(event);
  6957. }
  6958. };
  6959. this.onnegotiationneeded = null;
  6960. this.peerconnection.onnegotiationneeded = function (event) {
  6961. self.trace('onnegotiationneeded');
  6962. if (self.onnegotiationneeded !== null) {
  6963. self.onnegotiationneeded(event);
  6964. }
  6965. };
  6966. self.ondatachannel = null;
  6967. this.peerconnection.ondatachannel = function (event) {
  6968. self.trace('ondatachannel', event);
  6969. if (self.ondatachannel !== null) {
  6970. self.ondatachannel(event);
  6971. }
  6972. };
  6973. // XXX: do all non-firefox browsers which we support also support this?
  6974. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  6975. this.statsinterval = window.setInterval(function() {
  6976. self.peerconnection.getStats(function(stats) {
  6977. var results = stats.result();
  6978. var now = new Date();
  6979. for (var i = 0; i < results.length; ++i) {
  6980. results[i].names().forEach(function (name) {
  6981. var id = results[i].id + '-' + name;
  6982. if (!self.stats[id]) {
  6983. self.stats[id] = {
  6984. startTime: now,
  6985. endTime: now,
  6986. values: [],
  6987. times: []
  6988. };
  6989. }
  6990. self.stats[id].values.push(results[i].stat(name));
  6991. self.stats[id].times.push(now.getTime());
  6992. if (self.stats[id].values.length > self.maxstats) {
  6993. self.stats[id].values.shift();
  6994. self.stats[id].times.shift();
  6995. }
  6996. self.stats[id].endTime = now;
  6997. });
  6998. }
  6999. });
  7000. }, 1000);
  7001. }
  7002. }
  7003. /**
  7004. * Returns a string representation of a SessionDescription object.
  7005. */
  7006. var dumpSDP = function(description) {
  7007. if (typeof description === 'undefined' || description == null) {
  7008. return '';
  7009. }
  7010. return 'type: ' + description.type + '\r\n' + description.sdp;
  7011. };
  7012. /**
  7013. * Takes a SessionDescription object and returns a "normalized" version.
  7014. * Currently it only takes care of ordering the a=ssrc lines.
  7015. */
  7016. var normalizePlanB = function(desc) {
  7017. if (typeof desc !== 'object' || desc === null ||
  7018. typeof desc.sdp !== 'string') {
  7019. console.warn('An empty description was passed as an argument.');
  7020. return desc;
  7021. }
  7022. var transform = require('sdp-transform');
  7023. var session = transform.parse(desc.sdp);
  7024. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  7025. Array.isArray(session.media)) {
  7026. session.media.forEach(function (mLine) {
  7027. // Chrome appears to be picky about the order in which a=ssrc lines
  7028. // are listed in an m-line when rtx is enabled (and thus there are
  7029. // a=ssrc-group lines with FID semantics). Specifically if we have
  7030. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  7031. // the "a=ssrc:S1" lines, SRD fails.
  7032. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  7033. // first.
  7034. var firstSsrcs = [];
  7035. var newSsrcLines = [];
  7036. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  7037. mLine.ssrcGroups.forEach(function (group) {
  7038. if (typeof group.semantics !== 'undefined' &&
  7039. group.semantics === 'FID') {
  7040. if (typeof group.ssrcs !== 'undefined') {
  7041. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  7042. }
  7043. }
  7044. });
  7045. }
  7046. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  7047. for (var i = 0; i<mLine.ssrcs.length; i++){
  7048. if (typeof mLine.ssrcs[i] === 'object'
  7049. && typeof mLine.ssrcs[i].id !== 'undefined'
  7050. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  7051. newSsrcLines.push(mLine.ssrcs[i]);
  7052. delete mLine.ssrcs[i];
  7053. }
  7054. }
  7055. for (var i = 0; i<mLine.ssrcs.length; i++){
  7056. if (typeof mLine.ssrcs[i] !== 'undefined') {
  7057. newSsrcLines.push(mLine.ssrcs[i]);
  7058. }
  7059. }
  7060. mLine.ssrcs = newSsrcLines;
  7061. }
  7062. });
  7063. }
  7064. var resStr = transform.write(session);
  7065. return new RTCSessionDescription({
  7066. type: desc.type,
  7067. sdp: resStr
  7068. });
  7069. };
  7070. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  7071. TraceablePeerConnection.prototype.__defineGetter__(
  7072. 'signalingState',
  7073. function() { return this.peerconnection.signalingState; });
  7074. TraceablePeerConnection.prototype.__defineGetter__(
  7075. 'iceConnectionState',
  7076. function() { return this.peerconnection.iceConnectionState; });
  7077. TraceablePeerConnection.prototype.__defineGetter__(
  7078. 'localDescription',
  7079. function() {
  7080. var desc = this.peerconnection.localDescription;
  7081. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  7082. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  7083. // if we're running on FF, transform to Plan B first.
  7084. if (RTCBrowserType.usesUnifiedPlan()) {
  7085. desc = this.interop.toPlanB(desc);
  7086. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  7087. }
  7088. return desc;
  7089. });
  7090. TraceablePeerConnection.prototype.__defineGetter__(
  7091. 'remoteDescription',
  7092. function() {
  7093. var desc = this.peerconnection.remoteDescription;
  7094. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  7095. // if we're running on FF, transform to Plan B first.
  7096. if (RTCBrowserType.usesUnifiedPlan()) {
  7097. desc = this.interop.toPlanB(desc);
  7098. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  7099. }
  7100. return desc;
  7101. });
  7102. }
  7103. TraceablePeerConnection.prototype.addStream = function (stream) {
  7104. this.trace('addStream', stream.id);
  7105. try
  7106. {
  7107. this.peerconnection.addStream(stream);
  7108. }
  7109. catch (e)
  7110. {
  7111. console.error(e);
  7112. }
  7113. };
  7114. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  7115. this.trace('removeStream', stream.id);
  7116. if(stopStreams) {
  7117. stream.getAudioTracks().forEach(function (track) {
  7118. // stop() not supported with IE
  7119. if (track.stop) {
  7120. track.stop();
  7121. }
  7122. });
  7123. stream.getVideoTracks().forEach(function (track) {
  7124. // stop() not supported with IE
  7125. if (track.stop) {
  7126. track.stop();
  7127. }
  7128. });
  7129. if (stream.stop) {
  7130. stream.stop();
  7131. }
  7132. }
  7133. try {
  7134. // FF doesn't support this yet.
  7135. if (this.peerconnection.removeStream)
  7136. this.peerconnection.removeStream(stream);
  7137. } catch (e) {
  7138. console.error(e);
  7139. }
  7140. };
  7141. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  7142. this.trace('createDataChannel', label, opts);
  7143. return this.peerconnection.createDataChannel(label, opts);
  7144. };
  7145. TraceablePeerConnection.prototype.setLocalDescription
  7146. = function (description, successCallback, failureCallback) {
  7147. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  7148. // if we're running on FF, transform to Plan A first.
  7149. if (RTCBrowserType.usesUnifiedPlan()) {
  7150. description = this.interop.toUnifiedPlan(description);
  7151. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  7152. }
  7153. var self = this;
  7154. this.peerconnection.setLocalDescription(description,
  7155. function () {
  7156. self.trace('setLocalDescriptionOnSuccess');
  7157. successCallback();
  7158. },
  7159. function (err) {
  7160. self.trace('setLocalDescriptionOnFailure', err);
  7161. failureCallback(err);
  7162. }
  7163. );
  7164. /*
  7165. if (this.statsinterval === null && this.maxstats > 0) {
  7166. // start gathering stats
  7167. }
  7168. */
  7169. };
  7170. TraceablePeerConnection.prototype.setRemoteDescription
  7171. = function (description, successCallback, failureCallback) {
  7172. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  7173. // TODO the focus should squeze or explode the remote simulcast
  7174. description = this.simulcast.mungeRemoteDescription(description);
  7175. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  7176. // if we're running on FF, transform to Plan A first.
  7177. if (RTCBrowserType.usesUnifiedPlan()) {
  7178. description = this.interop.toUnifiedPlan(description);
  7179. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  7180. }
  7181. if (RTCBrowserType.usesPlanB()) {
  7182. description = normalizePlanB(description);
  7183. }
  7184. var self = this;
  7185. this.peerconnection.setRemoteDescription(description,
  7186. function () {
  7187. self.trace('setRemoteDescriptionOnSuccess');
  7188. successCallback();
  7189. },
  7190. function (err) {
  7191. self.trace('setRemoteDescriptionOnFailure', err);
  7192. failureCallback(err);
  7193. }
  7194. );
  7195. /*
  7196. if (this.statsinterval === null && this.maxstats > 0) {
  7197. // start gathering stats
  7198. }
  7199. */
  7200. };
  7201. TraceablePeerConnection.prototype.close = function () {
  7202. this.trace('stop');
  7203. if (this.statsinterval !== null) {
  7204. window.clearInterval(this.statsinterval);
  7205. this.statsinterval = null;
  7206. }
  7207. this.peerconnection.close();
  7208. };
  7209. TraceablePeerConnection.prototype.createOffer
  7210. = function (successCallback, failureCallback, constraints) {
  7211. var self = this;
  7212. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  7213. this.peerconnection.createOffer(
  7214. function (offer) {
  7215. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  7216. // NOTE this is not tested because in meet the focus generates the
  7217. // offer.
  7218. // if we're running on FF, transform to Plan B first.
  7219. if (RTCBrowserType.usesUnifiedPlan()) {
  7220. offer = self.interop.toPlanB(offer);
  7221. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  7222. }
  7223. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  7224. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  7225. offer = self.simulcast.mungeLocalDescription(offer);
  7226. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  7227. }
  7228. successCallback(offer);
  7229. },
  7230. function(err) {
  7231. self.trace('createOfferOnFailure', err);
  7232. failureCallback(err);
  7233. },
  7234. constraints
  7235. );
  7236. };
  7237. TraceablePeerConnection.prototype.createAnswer
  7238. = function (successCallback, failureCallback, constraints) {
  7239. var self = this;
  7240. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  7241. this.peerconnection.createAnswer(
  7242. function (answer) {
  7243. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  7244. // if we're running on FF, transform to Plan A first.
  7245. if (RTCBrowserType.usesUnifiedPlan()) {
  7246. answer = self.interop.toPlanB(answer);
  7247. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  7248. }
  7249. // munge local video SSRC
  7250. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  7251. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  7252. answer = self.simulcast.mungeLocalDescription(answer);
  7253. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  7254. }
  7255. successCallback(answer);
  7256. },
  7257. function(err) {
  7258. self.trace('createAnswerOnFailure', err);
  7259. failureCallback(err);
  7260. },
  7261. constraints
  7262. );
  7263. };
  7264. TraceablePeerConnection.prototype.addIceCandidate
  7265. = function (candidate, successCallback, failureCallback) {
  7266. //var self = this;
  7267. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  7268. this.peerconnection.addIceCandidate(candidate);
  7269. /* maybe later
  7270. this.peerconnection.addIceCandidate(candidate,
  7271. function () {
  7272. self.trace('addIceCandidateOnSuccess');
  7273. successCallback();
  7274. },
  7275. function (err) {
  7276. self.trace('addIceCandidateOnFailure', err);
  7277. failureCallback(err);
  7278. }
  7279. );
  7280. */
  7281. };
  7282. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  7283. // TODO: Is this the correct way to handle Opera, Temasys?
  7284. if (RTCBrowserType.isFirefox()) {
  7285. // ignore for now...
  7286. if(!errback)
  7287. errback = function () {};
  7288. this.peerconnection.getStats(null, callback, errback);
  7289. } else {
  7290. this.peerconnection.getStats(callback);
  7291. }
  7292. };
  7293. module.exports = TraceablePeerConnection;
  7294. },{"../../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){
  7295. /* global $, $iq, APP, config, messageHandler,
  7296. roomName, sessionTerminated, Strophe, Util */
  7297. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7298. var Settings = require("../settings/Settings");
  7299. var AuthenticationEvents
  7300. = require("../../service/authentication/AuthenticationEvents");
  7301. function createExpBackoffTimer(step) {
  7302. var count = 1;
  7303. return function (reset) {
  7304. // Reset call
  7305. if (reset) {
  7306. count = 1;
  7307. return;
  7308. }
  7309. // Calculate next timeout
  7310. var timeout = Math.pow(2, count - 1);
  7311. count += 1;
  7312. return timeout * step;
  7313. };
  7314. }
  7315. function Moderator(roomName, xmpp, emitter) {
  7316. this.roomName = roomName;
  7317. this.xmppService = xmpp;
  7318. this.getNextTimeout = createExpBackoffTimer(1000);
  7319. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  7320. // External authentication stuff
  7321. this.externalAuthEnabled = false;
  7322. this.settings = new Settings(roomName);
  7323. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  7324. // it will be enabled automatically if focus detects the component through
  7325. // service discovery.
  7326. this.sipGatewayEnabled = this.xmppService.options.hosts.call_control !== undefined;
  7327. this.eventEmitter = emitter;
  7328. this.connection = this.xmppService.connection;
  7329. this.focusUserJid;
  7330. //FIXME:
  7331. // Message listener that talks to POPUP window
  7332. function listener(event) {
  7333. if (event.data && event.data.sessionId) {
  7334. if (event.origin !== window.location.origin) {
  7335. console.warn("Ignoring sessionId from different origin: " +
  7336. event.origin);
  7337. return;
  7338. }
  7339. localStorage.setItem('sessionId', event.data.sessionId);
  7340. // After popup is closed we will authenticate
  7341. }
  7342. }
  7343. // Register
  7344. if (window.addEventListener) {
  7345. window.addEventListener("message", listener, false);
  7346. } else {
  7347. window.attachEvent("onmessage", listener);
  7348. }
  7349. }
  7350. Moderator.prototype.isExternalAuthEnabled = function () {
  7351. return this.externalAuthEnabled;
  7352. };
  7353. Moderator.prototype.isSipGatewayEnabled = function () {
  7354. return this.sipGatewayEnabled;
  7355. };
  7356. Moderator.prototype.onMucMemberLeft = function (jid) {
  7357. console.info("Someone left is it focus ? " + jid);
  7358. var resource = Strophe.getResourceFromJid(jid);
  7359. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  7360. console.info(
  7361. "Focus has left the room - leaving conference");
  7362. //hangUp();
  7363. // We'd rather reload to have everything re-initialized
  7364. //FIXME: show some message before reload
  7365. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  7366. }
  7367. };
  7368. Moderator.prototype.setFocusUserJid = function (focusJid) {
  7369. if (!this.focusUserJid) {
  7370. this.focusUserJid = focusJid;
  7371. console.info("Focus jid set to: " + this.focusUserJid);
  7372. }
  7373. };
  7374. Moderator.prototype.getFocusUserJid = function () {
  7375. return this.focusUserJid;
  7376. };
  7377. Moderator.prototype.getFocusComponent = function () {
  7378. // Get focus component address
  7379. var focusComponent = this.xmppService.options.hosts.focus;
  7380. // If not specified use default: 'focus.domain'
  7381. if (!focusComponent) {
  7382. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  7383. }
  7384. return focusComponent;
  7385. };
  7386. Moderator.prototype.createConferenceIq = function () {
  7387. // Generate create conference IQ
  7388. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  7389. // Session Id used for authentication
  7390. var sessionId = localStorage.getItem('sessionId');
  7391. var machineUID = this.settings.getSettings().uid;
  7392. console.info(
  7393. "Session ID: " + sessionId + " machine UID: " + machineUID);
  7394. elem.c('conference', {
  7395. xmlns: 'http://jitsi.org/protocol/focus',
  7396. room: this.roomName,
  7397. 'machine-uid': machineUID
  7398. });
  7399. if (sessionId) {
  7400. elem.attrs({ 'session-id': sessionId});
  7401. }
  7402. if (this.xmppService.options.hosts.bridge !== undefined) {
  7403. elem.c(
  7404. 'property',
  7405. {name: 'bridge',value: this.xmppService.options.hosts.bridge})
  7406. .up();
  7407. }
  7408. // Tell the focus we have Jigasi configured
  7409. if (this.xmppService.options.hosts.call_control !== undefined) {
  7410. elem.c(
  7411. 'property',
  7412. {name: 'call_control',value: this.xmppService.options.hosts.call_control})
  7413. .up();
  7414. }
  7415. if (this.xmppService.options.channelLastN !== undefined) {
  7416. elem.c(
  7417. 'property',
  7418. {name: 'channelLastN',value: this.xmppService.options.channelLastN})
  7419. .up();
  7420. }
  7421. if (this.xmppService.options.adaptiveLastN !== undefined) {
  7422. elem.c(
  7423. 'property',
  7424. {name: 'adaptiveLastN',value: this.xmppService.options.adaptiveLastN})
  7425. .up();
  7426. }
  7427. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  7428. elem.c(
  7429. 'property',
  7430. {name: 'adaptiveSimulcast',value: this.xmppService.options.adaptiveSimulcast})
  7431. .up();
  7432. }
  7433. if (this.xmppService.options.openSctp !== undefined) {
  7434. elem.c(
  7435. 'property',
  7436. {name: 'openSctp',value: this.xmppService.options.openSctp})
  7437. .up();
  7438. }
  7439. if(this.xmppService.options.startAudioMuted !== undefined)
  7440. {
  7441. elem.c(
  7442. 'property',
  7443. {name: 'startAudioMuted',value: this.xmppService.options.startAudioMuted})
  7444. .up();
  7445. }
  7446. if(this.xmppService.options.startVideoMuted !== undefined)
  7447. {
  7448. elem.c(
  7449. 'property',
  7450. {name: 'startVideoMuted',value: this.xmppService.options.startVideoMuted})
  7451. .up();
  7452. }
  7453. elem.c(
  7454. 'property',
  7455. {name: 'simulcastMode',value: 'rewriting'})
  7456. .up();
  7457. elem.up();
  7458. return elem;
  7459. };
  7460. Moderator.prototype.parseSessionId = function (resultIq) {
  7461. var sessionId = $(resultIq).find('conference').attr('session-id');
  7462. if (sessionId) {
  7463. console.info('Received sessionId: ' + sessionId);
  7464. localStorage.setItem('sessionId', sessionId);
  7465. }
  7466. };
  7467. Moderator.prototype.parseConfigOptions = function (resultIq) {
  7468. this.setFocusUserJid(
  7469. $(resultIq).find('conference').attr('focusjid'));
  7470. var authenticationEnabled
  7471. = $(resultIq).find(
  7472. '>conference>property' +
  7473. '[name=\'authentication\'][value=\'true\']').length > 0;
  7474. console.info("Authentication enabled: " + authenticationEnabled);
  7475. this.externalAuthEnabled = $(resultIq).find(
  7476. '>conference>property' +
  7477. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  7478. console.info('External authentication enabled: ' + this.externalAuthEnabled);
  7479. if (!this.externalAuthEnabled) {
  7480. // We expect to receive sessionId in 'internal' authentication mode
  7481. this.parseSessionId(resultIq);
  7482. }
  7483. var authIdentity = $(resultIq).find('>conference').attr('identity');
  7484. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  7485. authenticationEnabled, authIdentity);
  7486. // Check if focus has auto-detected Jigasi component(this will be also
  7487. // included if we have passed our host from the config)
  7488. if ($(resultIq).find(
  7489. '>conference>property' +
  7490. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  7491. this.sipGatewayEnabled = true;
  7492. }
  7493. console.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  7494. };
  7495. // FIXME = we need to show the fact that we're waiting for the focus
  7496. // to the user(or that focus is not available)
  7497. Moderator.prototype.allocateConferenceFocus = function ( callback) {
  7498. // Try to use focus user JID from the config
  7499. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  7500. // Send create conference IQ
  7501. var iq = this.createConferenceIq();
  7502. var self = this;
  7503. this.connection.sendIQ(
  7504. iq,
  7505. function (result) {
  7506. // Setup config options
  7507. self.parseConfigOptions(result);
  7508. if ('true' === $(result).find('conference').attr('ready')) {
  7509. // Reset both timers
  7510. self.getNextTimeout(true);
  7511. self.getNextErrorTimeout(true);
  7512. // Exec callback
  7513. callback();
  7514. } else {
  7515. var waitMs = self.getNextTimeout();
  7516. console.info("Waiting for the focus... " + waitMs);
  7517. // Reset error timeout
  7518. self.getNextErrorTimeout(true);
  7519. window.setTimeout(
  7520. function () {
  7521. self.allocateConferenceFocus(callback);
  7522. }, waitMs);
  7523. }
  7524. },
  7525. function (error) {
  7526. // Invalid session ? remove and try again
  7527. // without session ID to get a new one
  7528. var invalidSession
  7529. = $(error).find('>error>session-invalid').length;
  7530. if (invalidSession) {
  7531. console.info("Session expired! - removing");
  7532. localStorage.removeItem("sessionId");
  7533. }
  7534. if ($(error).find('>error>graceful-shutdown').length) {
  7535. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  7536. return;
  7537. }
  7538. // Check for error returned by the reservation system
  7539. var reservationErr = $(error).find('>error>reservation-error');
  7540. if (reservationErr.length) {
  7541. // Trigger error event
  7542. var errorCode = reservationErr.attr('error-code');
  7543. var errorMsg;
  7544. if ($(error).find('>error>text')) {
  7545. errorMsg = $(error).find('>error>text').text();
  7546. }
  7547. self.eventEmitter.emit(
  7548. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  7549. return;
  7550. }
  7551. // Not authorized to create new room
  7552. if ($(error).find('>error>not-authorized').length) {
  7553. console.warn("Unauthorized to start the conference", error);
  7554. var toDomain
  7555. = Strophe.getDomainFromJid(error.getAttribute('to'));
  7556. if (toDomain !== this.xmppService.options.hosts.anonymousdomain) {
  7557. //FIXME: "is external" should come either from
  7558. // the focus or config.js
  7559. self.externalAuthEnabled = true;
  7560. }
  7561. self.eventEmitter.emit(
  7562. XMPPEvents.AUTHENTICATION_REQUIRED,
  7563. function () {
  7564. self.allocateConferenceFocus(
  7565. callback);
  7566. });
  7567. return;
  7568. }
  7569. var waitMs = self.getNextErrorTimeout();
  7570. console.error("Focus error, retry after " + waitMs, error);
  7571. // Show message
  7572. var focusComponent = self.getFocusComponent();
  7573. var retrySec = waitMs / 1000;
  7574. //FIXME: message is duplicated ?
  7575. // Do not show in case of session invalid
  7576. // which means just a retry
  7577. if (!invalidSession) {
  7578. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  7579. focusComponent, retrySec);
  7580. }
  7581. // Reset response timeout
  7582. self.getNextTimeout(true);
  7583. window.setTimeout(
  7584. function () {
  7585. self.allocateConferenceFocus(callback);
  7586. }, waitMs);
  7587. }
  7588. );
  7589. };
  7590. Moderator.prototype.getLoginUrl = function (urlCallback) {
  7591. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  7592. iq.c('login-url', {
  7593. xmlns: 'http://jitsi.org/protocol/focus',
  7594. room: this.roomName,
  7595. 'machine-uid': this.settings.getSettings().uid
  7596. });
  7597. this.connection.sendIQ(
  7598. iq,
  7599. function (result) {
  7600. var url = $(result).find('login-url').attr('url');
  7601. url = url = decodeURIComponent(url);
  7602. if (url) {
  7603. console.info("Got auth url: " + url);
  7604. urlCallback(url);
  7605. } else {
  7606. console.error(
  7607. "Failed to get auth url from the focus", result);
  7608. }
  7609. },
  7610. function (error) {
  7611. console.error("Get auth url error", error);
  7612. }
  7613. );
  7614. };
  7615. Moderator.prototype.getPopupLoginUrl = function (urlCallback) {
  7616. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  7617. iq.c('login-url', {
  7618. xmlns: 'http://jitsi.org/protocol/focus',
  7619. room: this.roomName,
  7620. 'machine-uid': this.settings.getSettings().uid,
  7621. popup: true
  7622. });
  7623. this.connection.sendIQ(
  7624. iq,
  7625. function (result) {
  7626. var url = $(result).find('login-url').attr('url');
  7627. url = url = decodeURIComponent(url);
  7628. if (url) {
  7629. console.info("Got POPUP auth url: " + url);
  7630. urlCallback(url);
  7631. } else {
  7632. console.error(
  7633. "Failed to get POPUP auth url from the focus", result);
  7634. }
  7635. },
  7636. function (error) {
  7637. console.error('Get POPUP auth url error', error);
  7638. }
  7639. );
  7640. };
  7641. Moderator.prototype.logout = function (callback) {
  7642. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  7643. var sessionId = localStorage.getItem('sessionId');
  7644. if (!sessionId) {
  7645. callback();
  7646. return;
  7647. }
  7648. iq.c('logout', {
  7649. xmlns: 'http://jitsi.org/protocol/focus',
  7650. 'session-id': sessionId
  7651. });
  7652. this.connection.sendIQ(
  7653. iq,
  7654. function (result) {
  7655. var logoutUrl = $(result).find('logout').attr('logout-url');
  7656. if (logoutUrl) {
  7657. logoutUrl = decodeURIComponent(logoutUrl);
  7658. }
  7659. console.info("Log out OK, url: " + logoutUrl, result);
  7660. localStorage.removeItem('sessionId');
  7661. callback(logoutUrl);
  7662. },
  7663. function (error) {
  7664. console.error("Logout error", error);
  7665. }
  7666. );
  7667. };
  7668. module.exports = Moderator;
  7669. },{"../../service/authentication/AuthenticationEvents":74,"../../service/xmpp/XMPPEvents":76,"../settings/Settings":18}],28:[function(require,module,exports){
  7670. /* jshint -W117 */
  7671. /* a simple MUC connection plugin
  7672. * can only handle a single MUC room
  7673. */
  7674. var ChatRoom = require("./ChatRoom");
  7675. module.exports = function(XMPP) {
  7676. Strophe.addConnectionPlugin('emuc', {
  7677. connection: null,
  7678. rooms: {},//map with the rooms
  7679. init: function (conn) {
  7680. this.connection = conn;
  7681. // add handlers (just once)
  7682. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, null, null);
  7683. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null);
  7684. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null);
  7685. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null);
  7686. },
  7687. createRoom: function (jid, password, options) {
  7688. var roomJid = Strophe.getBareJidFromJid(jid);
  7689. if (this.rooms[roomJid]) {
  7690. console.error("You are already in the room!");
  7691. return;
  7692. }
  7693. this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, options);
  7694. return this.rooms[roomJid];
  7695. },
  7696. doLeave: function (jid) {
  7697. this.rooms[jid].doLeave();
  7698. delete this.rooms[jid];
  7699. },
  7700. onPresence: function (pres) {
  7701. var from = pres.getAttribute('from');
  7702. // What is this for? A workaround for something?
  7703. if (pres.getAttribute('type')) {
  7704. return true;
  7705. }
  7706. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7707. if(!room)
  7708. return;
  7709. // Parse status.
  7710. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  7711. room.createNonAnonymousRoom();
  7712. }
  7713. room.onPresence(pres);
  7714. return true;
  7715. },
  7716. onPresenceUnavailable: function (pres) {
  7717. var from = pres.getAttribute('from');
  7718. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7719. if(!room)
  7720. return;
  7721. room.onPresenceUnavailable(pres, from);
  7722. return true;
  7723. },
  7724. onPresenceError: function (pres) {
  7725. var from = pres.getAttribute('from');
  7726. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7727. if(!room)
  7728. return;
  7729. room.onPresenceError(pres, from);
  7730. return true;
  7731. },
  7732. onMessage: function (msg) {
  7733. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  7734. var from = msg.getAttribute('from');
  7735. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7736. if(!room)
  7737. return;
  7738. room.onMessage(msg, from);
  7739. return true;
  7740. },
  7741. setJingleSession: function (from, session) {
  7742. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7743. if(!room)
  7744. return;
  7745. room.setJingleSession(session);
  7746. }
  7747. });
  7748. };
  7749. },{"./ChatRoom":19}],29:[function(require,module,exports){
  7750. /* jshint -W117 */
  7751. var JingleSession = require("./JingleSessionPC");
  7752. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7753. var RTCBrowserType = require("../RTC/RTCBrowserType");
  7754. module.exports = function(XMPP, eventEmitter) {
  7755. Strophe.addConnectionPlugin('jingle', {
  7756. connection: null,
  7757. sessions: {},
  7758. jid2session: {},
  7759. ice_config: {iceServers: []},
  7760. media_constraints: {
  7761. mandatory: {
  7762. 'OfferToReceiveAudio': true,
  7763. 'OfferToReceiveVideo': true
  7764. }
  7765. // MozDontOfferDataChannel: true when this is firefox
  7766. },
  7767. init: function (conn) {
  7768. this.connection = conn;
  7769. if (this.connection.disco) {
  7770. // http://xmpp.org/extensions/xep-0167.html#support
  7771. // http://xmpp.org/extensions/xep-0176.html#support
  7772. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  7773. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  7774. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  7775. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  7776. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  7777. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  7778. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  7779. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  7780. || RTCBrowserType.isTemasysPluginUsed()) {
  7781. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  7782. }
  7783. // this is dealt with by SDP O/A so we don't need to announce this
  7784. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  7785. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  7786. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  7787. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  7788. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  7789. }
  7790. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  7791. },
  7792. onJingle: function (iq) {
  7793. var sid = $(iq).find('jingle').attr('sid');
  7794. var action = $(iq).find('jingle').attr('action');
  7795. var fromJid = iq.getAttribute('from');
  7796. // send ack first
  7797. var ack = $iq({type: 'result',
  7798. to: fromJid,
  7799. id: iq.getAttribute('id')
  7800. });
  7801. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  7802. var sess = this.sessions[sid];
  7803. if ('session-initiate' != action) {
  7804. if (sess === null) {
  7805. ack.type = 'error';
  7806. ack.c('error', {type: 'cancel'})
  7807. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  7808. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  7809. this.connection.send(ack);
  7810. return true;
  7811. }
  7812. // local jid is not checked
  7813. if (fromJid != sess.peerjid) {
  7814. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  7815. ack.type = 'error';
  7816. ack.c('error', {type: 'cancel'})
  7817. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  7818. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  7819. this.connection.send(ack);
  7820. return true;
  7821. }
  7822. } else if (sess !== undefined) {
  7823. // existing session with same session id
  7824. // this might be out-of-order if the sess.peerjid is the same as from
  7825. ack.type = 'error';
  7826. ack.c('error', {type: 'cancel'})
  7827. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  7828. console.warn('duplicate session id', sid);
  7829. this.connection.send(ack);
  7830. return true;
  7831. }
  7832. // FIXME: check for a defined action
  7833. this.connection.send(ack);
  7834. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  7835. switch (action) {
  7836. case 'session-initiate':
  7837. var startMuted = $(iq).find('jingle>startmuted');
  7838. if (startMuted && startMuted.length > 0) {
  7839. var audioMuted = startMuted.attr("audio");
  7840. var videoMuted = startMuted.attr("video");
  7841. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  7842. audioMuted === "true", videoMuted === "true");
  7843. }
  7844. sess = new JingleSession(
  7845. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  7846. this.connection, XMPP);
  7847. // configure session
  7848. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  7849. this.connection.emuc.setJingleSession(fromBareJid, sess);
  7850. sess.media_constraints = this.media_constraints;
  7851. sess.ice_config = this.ice_config;
  7852. sess.initialize(fromJid, false);
  7853. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  7854. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  7855. sess.setOffer($(iq).find('>jingle'));
  7856. this.sessions[sess.sid] = sess;
  7857. this.jid2session[sess.peerjid] = sess;
  7858. // the callback should either
  7859. // .sendAnswer and .accept
  7860. // or .sendTerminate -- not necessarily synchronous
  7861. sess.sendAnswer();
  7862. sess.accept();
  7863. break;
  7864. case 'session-accept':
  7865. sess.setAnswer($(iq).find('>jingle'));
  7866. sess.accept();
  7867. break;
  7868. case 'session-terminate':
  7869. // If this is not the focus sending the terminate, we have
  7870. // nothing more to do here.
  7871. if (Object.keys(this.sessions).length < 1
  7872. || !(this.sessions[Object.keys(this.sessions)[0]]
  7873. instanceof JingleSession))
  7874. {
  7875. break;
  7876. }
  7877. console.log('terminating...', sess.sid);
  7878. sess.terminate();
  7879. this.terminate(sess.sid);
  7880. if ($(iq).find('>jingle>reason').length) {
  7881. $(document).trigger('callterminated.jingle', [
  7882. sess.sid,
  7883. sess.peerjid,
  7884. $(iq).find('>jingle>reason>:first')[0].tagName,
  7885. $(iq).find('>jingle>reason>text').text()
  7886. ]);
  7887. } else {
  7888. $(document).trigger('callterminated.jingle',
  7889. [sess.sid, sess.peerjid]);
  7890. }
  7891. break;
  7892. case 'transport-info':
  7893. sess.addIceCandidate($(iq).find('>jingle>content'));
  7894. break;
  7895. case 'session-info':
  7896. var affected;
  7897. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  7898. $(document).trigger('ringing.jingle', [sess.sid]);
  7899. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  7900. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  7901. $(document).trigger('mute.jingle', [sess.sid, affected]);
  7902. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  7903. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  7904. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  7905. }
  7906. break;
  7907. case 'addsource': // FIXME: proprietary, un-jingleish
  7908. case 'source-add': // FIXME: proprietary
  7909. sess.addSource($(iq).find('>jingle>content'), fromJid);
  7910. break;
  7911. case 'removesource': // FIXME: proprietary, un-jingleish
  7912. case 'source-remove': // FIXME: proprietary
  7913. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  7914. break;
  7915. default:
  7916. console.warn('jingle action not implemented', action);
  7917. break;
  7918. }
  7919. return true;
  7920. },
  7921. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  7922. if (sid === null || sid === undefined) {
  7923. for (sid in this.sessions) {
  7924. if (this.sessions[sid].state != 'ended') {
  7925. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  7926. this.sessions[sid].terminate();
  7927. }
  7928. delete this.jid2session[this.sessions[sid].peerjid];
  7929. delete this.sessions[sid];
  7930. }
  7931. } else if (this.sessions.hasOwnProperty(sid)) {
  7932. if (this.sessions[sid].state != 'ended') {
  7933. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  7934. this.sessions[sid].terminate();
  7935. }
  7936. delete this.jid2session[this.sessions[sid].peerjid];
  7937. delete this.sessions[sid];
  7938. }
  7939. },
  7940. getStunAndTurnCredentials: function () {
  7941. // get stun and turn configuration from server via xep-0215
  7942. // uses time-limited credentials as described in
  7943. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  7944. //
  7945. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  7946. // for a prosody module which implements this
  7947. //
  7948. // currently, this doesn't work with updateIce and therefore credentials with a long
  7949. // validity have to be fetched before creating the peerconnection
  7950. // TODO: implement refresh via updateIce as described in
  7951. // https://code.google.com/p/webrtc/issues/detail?id=1650
  7952. var self = this;
  7953. this.connection.sendIQ(
  7954. $iq({type: 'get', to: this.connection.domain})
  7955. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  7956. function (res) {
  7957. var iceservers = [];
  7958. $(res).find('>services>service').each(function (idx, el) {
  7959. el = $(el);
  7960. var dict = {};
  7961. var type = el.attr('type');
  7962. switch (type) {
  7963. case 'stun':
  7964. dict.url = 'stun:' + el.attr('host');
  7965. if (el.attr('port')) {
  7966. dict.url += ':' + el.attr('port');
  7967. }
  7968. iceservers.push(dict);
  7969. break;
  7970. case 'turn':
  7971. case 'turns':
  7972. dict.url = type + ':';
  7973. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  7974. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  7975. dict.url += el.attr('username') + '@';
  7976. } else {
  7977. dict.username = el.attr('username'); // only works in M28
  7978. }
  7979. }
  7980. dict.url += el.attr('host');
  7981. if (el.attr('port') && el.attr('port') != '3478') {
  7982. dict.url += ':' + el.attr('port');
  7983. }
  7984. if (el.attr('transport') && el.attr('transport') != 'udp') {
  7985. dict.url += '?transport=' + el.attr('transport');
  7986. }
  7987. if (el.attr('password')) {
  7988. dict.credential = el.attr('password');
  7989. }
  7990. iceservers.push(dict);
  7991. break;
  7992. }
  7993. });
  7994. self.ice_config.iceServers = iceservers;
  7995. },
  7996. function (err) {
  7997. console.warn('getting turn credentials failed', err);
  7998. console.warn('is mod_turncredentials or similar installed?');
  7999. }
  8000. );
  8001. // implement push?
  8002. },
  8003. /**
  8004. * Returns the data saved in 'updateLog' in a format to be logged.
  8005. */
  8006. getLog: function () {
  8007. var data = {};
  8008. var self = this;
  8009. Object.keys(this.sessions).forEach(function (sid) {
  8010. var session = self.sessions[sid];
  8011. if (session.peerconnection && session.peerconnection.updateLog) {
  8012. // FIXME: should probably be a .dump call
  8013. data["jingle_" + session.sid] = {
  8014. updateLog: session.peerconnection.updateLog,
  8015. stats: session.peerconnection.stats,
  8016. url: window.location.href
  8017. };
  8018. }
  8019. });
  8020. return data;
  8021. }
  8022. });
  8023. };
  8024. },{"../../service/xmpp/XMPPEvents":76,"../RTC/RTCBrowserType":14,"./JingleSessionPC":21}],30:[function(require,module,exports){
  8025. /* global Strophe */
  8026. module.exports = function () {
  8027. Strophe.addConnectionPlugin('logger', {
  8028. // logs raw stanzas and makes them available for download as JSON
  8029. connection: null,
  8030. log: [],
  8031. init: function (conn) {
  8032. this.connection = conn;
  8033. this.connection.rawInput = this.log_incoming.bind(this);
  8034. this.connection.rawOutput = this.log_outgoing.bind(this);
  8035. },
  8036. log_incoming: function (stanza) {
  8037. this.log.push([new Date().getTime(), 'incoming', stanza]);
  8038. },
  8039. log_outgoing: function (stanza) {
  8040. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  8041. }
  8042. });
  8043. };
  8044. },{}],31:[function(require,module,exports){
  8045. /* jshint -W117 */
  8046. module.exports = function() {
  8047. Strophe.addConnectionPlugin('rayo',
  8048. {
  8049. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  8050. connection: null,
  8051. init: function (conn) {
  8052. this.connection = conn;
  8053. if (this.connection.disco) {
  8054. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  8055. }
  8056. this.connection.addHandler(
  8057. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  8058. },
  8059. onRayo: function (iq) {
  8060. console.info("Rayo IQ", iq);
  8061. },
  8062. dial: function (to, from, roomName, roomPass) {
  8063. var self = this;
  8064. var req = $iq(
  8065. {
  8066. type: 'set',
  8067. to: this.connection.emuc.focusMucJid
  8068. }
  8069. );
  8070. req.c('dial',
  8071. {
  8072. xmlns: this.RAYO_XMLNS,
  8073. to: to,
  8074. from: from
  8075. });
  8076. req.c('header',
  8077. {
  8078. name: 'JvbRoomName',
  8079. value: roomName
  8080. }).up();
  8081. if (roomPass !== null && roomPass.length) {
  8082. req.c('header',
  8083. {
  8084. name: 'JvbRoomPassword',
  8085. value: roomPass
  8086. }).up();
  8087. }
  8088. this.connection.sendIQ(
  8089. req,
  8090. function (result) {
  8091. console.info('Dial result ', result);
  8092. var resource = $(result).find('ref').attr('uri');
  8093. this.call_resource = resource.substr('xmpp:'.length);
  8094. console.info(
  8095. "Received call resource: " + this.call_resource);
  8096. },
  8097. function (error) {
  8098. console.info('Dial error ', error);
  8099. }
  8100. );
  8101. },
  8102. hang_up: function () {
  8103. if (!this.call_resource) {
  8104. console.warn("No call in progress");
  8105. return;
  8106. }
  8107. var self = this;
  8108. var req = $iq(
  8109. {
  8110. type: 'set',
  8111. to: this.call_resource
  8112. }
  8113. );
  8114. req.c('hangup',
  8115. {
  8116. xmlns: this.RAYO_XMLNS
  8117. });
  8118. this.connection.sendIQ(
  8119. req,
  8120. function (result) {
  8121. console.info('Hangup result ', result);
  8122. self.call_resource = null;
  8123. },
  8124. function (error) {
  8125. console.info('Hangup error ', error);
  8126. self.call_resource = null;
  8127. }
  8128. );
  8129. }
  8130. }
  8131. );
  8132. };
  8133. },{}],32:[function(require,module,exports){
  8134. /**
  8135. * Strophe logger implementation. Logs from level WARN and above.
  8136. */
  8137. module.exports = function () {
  8138. Strophe.log = function (level, msg) {
  8139. switch (level) {
  8140. case Strophe.LogLevel.WARN:
  8141. console.warn("Strophe: " + msg);
  8142. break;
  8143. case Strophe.LogLevel.ERROR:
  8144. case Strophe.LogLevel.FATAL:
  8145. console.error("Strophe: " + msg);
  8146. break;
  8147. }
  8148. };
  8149. Strophe.getStatusString = function (status) {
  8150. switch (status) {
  8151. case Strophe.Status.ERROR:
  8152. return "ERROR";
  8153. case Strophe.Status.CONNECTING:
  8154. return "CONNECTING";
  8155. case Strophe.Status.CONNFAIL:
  8156. return "CONNFAIL";
  8157. case Strophe.Status.AUTHENTICATING:
  8158. return "AUTHENTICATING";
  8159. case Strophe.Status.AUTHFAIL:
  8160. return "AUTHFAIL";
  8161. case Strophe.Status.CONNECTED:
  8162. return "CONNECTED";
  8163. case Strophe.Status.DISCONNECTED:
  8164. return "DISCONNECTED";
  8165. case Strophe.Status.DISCONNECTING:
  8166. return "DISCONNECTING";
  8167. case Strophe.Status.ATTACHED:
  8168. return "ATTACHED";
  8169. default:
  8170. return "unknown";
  8171. }
  8172. };
  8173. };
  8174. },{}],33:[function(require,module,exports){
  8175. /* global $, APP, config, Strophe*/
  8176. var EventEmitter = require("events");
  8177. var Pako = require("pako");
  8178. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  8179. var RTCEvents = require("../../service/RTC/RTCEvents");
  8180. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8181. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  8182. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  8183. var RTC = require("../RTC/RTC");
  8184. var authenticatedUser = false;
  8185. function createConnection(bosh) {
  8186. bosh = bosh || '/http-bind';
  8187. return new Strophe.Connection(bosh);
  8188. };
  8189. //!!!!!!!!!! FIXME: ...
  8190. function initStrophePlugins(XMPP)
  8191. {
  8192. require("./strophe.emuc")(XMPP);
  8193. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  8194. // require("./strophe.moderate")(XMPP, eventEmitter);
  8195. require("./strophe.util")();
  8196. require("./strophe.rayo")();
  8197. require("./strophe.logger")();
  8198. }
  8199. //!!!!!!!!!! FIXME: ...
  8200. ///**
  8201. // * If given <tt>localStream</tt> is video one this method will advertise it's
  8202. // * video type in MUC presence.
  8203. // * @param localStream new or modified <tt>LocalStream</tt>.
  8204. // */
  8205. //function broadcastLocalVideoType(localStream) {
  8206. // if (localStream.videoType)
  8207. // XMPP.addToPresence('videoType', localStream.videoType);
  8208. //}
  8209. //
  8210. //function registerListeners() {
  8211. // RTC.addStreamListener(
  8212. // broadcastLocalVideoType,
  8213. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  8214. // );
  8215. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  8216. // XMPP.addToPresence("devices", devices);
  8217. // });
  8218. //}
  8219. function XMPP(options) {
  8220. this.eventEmitter = new EventEmitter();
  8221. this.connection = null;
  8222. this.disconnectInProgress = false;
  8223. this.forceMuted = false;
  8224. this.options = options;
  8225. initStrophePlugins(this);
  8226. // registerListeners();
  8227. this.connection = createConnection(options.bosh);
  8228. }
  8229. XMPP.prototype.getConnection = function(){ return connection; };
  8230. XMPP.prototype._connect = function (jid, password) {
  8231. var self = this;
  8232. // connection.connect() starts the connection process.
  8233. //
  8234. // As the connection process proceeds, the user supplied callback will
  8235. // be triggered multiple times with status updates. The callback should
  8236. // take two arguments - the status code and the error condition.
  8237. //
  8238. // The status code will be one of the values in the Strophe.Status
  8239. // constants. The error condition will be one of the conditions defined
  8240. // in RFC 3920 or the condition ‘strophe-parsererror’.
  8241. //
  8242. // The Parameters wait, hold and route are optional and only relevant
  8243. // for BOSH connections. Please see XEP 124 for a more detailed
  8244. // explanation of the optional parameters.
  8245. //
  8246. // Connection status constants for use by the connection handler
  8247. // callback.
  8248. //
  8249. // Status.ERROR - An error has occurred (websockets specific)
  8250. // Status.CONNECTING - The connection is currently being made
  8251. // Status.CONNFAIL - The connection attempt failed
  8252. // Status.AUTHENTICATING - The connection is authenticating
  8253. // Status.AUTHFAIL - The authentication attempt failed
  8254. // Status.CONNECTED - The connection has succeeded
  8255. // Status.DISCONNECTED - The connection has been terminated
  8256. // Status.DISCONNECTING - The connection is currently being terminated
  8257. // Status.ATTACHED - The connection has been attached
  8258. var anonymousConnectionFailed = false;
  8259. var connectionFailed = false;
  8260. var lastErrorMsg;
  8261. this.connection.connect(jid, password, function (status, msg) {
  8262. console.log('Strophe status changed to',
  8263. Strophe.getStatusString(status), msg);
  8264. if (status === Strophe.Status.CONNECTED) {
  8265. if (self.options.useStunTurn) {
  8266. self.connection.jingle.getStunAndTurnCredentials();
  8267. }
  8268. console.info("My Jabber ID: " + self.connection.jid);
  8269. if (password)
  8270. authenticatedUser = true;
  8271. if (self.connection && self.connection.connected &&
  8272. Strophe.getResourceFromJid(self.connection.jid)) {
  8273. // .connected is true while connecting?
  8274. // self.connection.send($pres());
  8275. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  8276. Strophe.getResourceFromJid(self.connection.jid));
  8277. }
  8278. } else if (status === Strophe.Status.CONNFAIL) {
  8279. if (msg === 'x-strophe-bad-non-anon-jid') {
  8280. anonymousConnectionFailed = true;
  8281. }
  8282. else
  8283. {
  8284. connectionFailed = true;
  8285. }
  8286. lastErrorMsg = msg;
  8287. } else if (status === Strophe.Status.DISCONNECTED) {
  8288. self.disconnectInProgress = false;
  8289. if (anonymousConnectionFailed) {
  8290. // prompt user for username and password
  8291. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  8292. JitsiConnectionErrors.PASSWORD_REQUIRED);
  8293. } else if(connectionFailed) {
  8294. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  8295. JitsiConnectionErrors.OTHER_ERROR,
  8296. msg ? msg : lastErrorMsg);
  8297. } else {
  8298. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  8299. msg ? msg : lastErrorMsg);
  8300. }
  8301. } else if (status === Strophe.Status.AUTHFAIL) {
  8302. // wrong password or username, prompt user
  8303. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  8304. JitsiConnectionErrors.PASSWORD_REQUIRED);
  8305. }
  8306. });
  8307. }
  8308. XMPP.prototype.connect = function (jid, password) {
  8309. if(!jid) {
  8310. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  8311. // Force authenticated domain if room is appended with '?login=true'
  8312. if (this.options.hosts.anonymousdomain &&
  8313. window.location.search.indexOf("login=true") !== -1) {
  8314. configDomain = this.options.hosts.domain;
  8315. }
  8316. jid = configDomain || window.location.hostname;
  8317. }
  8318. return this._connect(jid, password);
  8319. };
  8320. XMPP.prototype.createRoom = function (roomName, options, useNicks, nick) {
  8321. var roomjid = roomName + '@' + this.options.hosts.muc;
  8322. if (useNicks) {
  8323. if (nick) {
  8324. roomjid += '/' + nick;
  8325. } else {
  8326. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  8327. }
  8328. } else {
  8329. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  8330. if(!authenticatedUser)
  8331. tmpJid = tmpJid.substr(0, 8);
  8332. roomjid += '/' + tmpJid;
  8333. }
  8334. return this.connection.emuc.createRoom(roomjid, null, options);
  8335. }
  8336. XMPP.prototype.addListener = function(type, listener) {
  8337. this.eventEmitter.on(type, listener);
  8338. };
  8339. XMPP.prototype.removeListener = function (type, listener) {
  8340. this.eventEmitter.removeListener(type, listener);
  8341. };
  8342. //FIXME: this should work with the room
  8343. XMPP.prototype.leaveRoom = function (jid) {
  8344. var handler = this.connection.jingle.jid2session[jid];
  8345. if (handler && handler.peerconnection) {
  8346. // FIXME: probably removing streams is not required and close() should
  8347. // be enough
  8348. if (RTC.localAudio) {
  8349. handler.peerconnection.removeStream(
  8350. RTC.localAudio.getOriginalStream(), true);
  8351. }
  8352. if (RTC.localVideo) {
  8353. handler.peerconnection.removeStream(
  8354. RTC.localVideo.getOriginalStream(), true);
  8355. }
  8356. handler.peerconnection.close();
  8357. }
  8358. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  8359. this.connection.emuc.doLeave(jid);
  8360. };
  8361. /**
  8362. * Sends 'data' as a log message to the focus. Returns true iff a message
  8363. * was sent.
  8364. * @param data
  8365. * @returns {boolean} true iff a message was sent.
  8366. */
  8367. XMPP.prototype.sendLogs = function (data) {
  8368. if(!this.connection.emuc.focusMucJid)
  8369. return false;
  8370. var deflate = true;
  8371. var content = JSON.stringify(data);
  8372. if (deflate) {
  8373. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  8374. }
  8375. content = Base64.encode(content);
  8376. // XEP-0337-ish
  8377. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  8378. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  8379. id: 'PeerConnectionStats'});
  8380. message.c('message').t(content).up();
  8381. if (deflate) {
  8382. message.c('tag', {name: "deflated", value: "true"}).up();
  8383. }
  8384. message.up();
  8385. this.connection.send(message);
  8386. return true;
  8387. };
  8388. // Gets the logs from strophe.jingle.
  8389. XMPP.prototype.getJingleLog = function () {
  8390. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  8391. };
  8392. // Gets the logs from strophe.
  8393. XMPP.prototype.getXmppLog = function () {
  8394. return this.connection.logger ? this.connection.logger.log : null;
  8395. };
  8396. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  8397. this.connection.rayo.dial(to, from, roomName,roomPass);
  8398. };
  8399. XMPP.prototype.setMute = function (jid, mute) {
  8400. this.connection.moderate.setMute(jid, mute);
  8401. };
  8402. XMPP.prototype.eject = function (jid) {
  8403. this.connection.moderate.eject(jid);
  8404. };
  8405. XMPP.prototype.getJidFromSSRC = function (ssrc) {
  8406. if (!this.isConferenceInProgress())
  8407. return null;
  8408. return this.connection.jingle.activecall.getSsrcOwner(ssrc);
  8409. };
  8410. XMPP.prototype.getSessions = function () {
  8411. return this.connection.jingle.sessions;
  8412. };
  8413. XMPP.prototype.disconnect = function () {
  8414. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  8415. {
  8416. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  8417. return;
  8418. }
  8419. this.disconnectInProgress = true;
  8420. this.connection.disconnect();
  8421. };
  8422. module.exports = XMPP;
  8423. },{"../../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){
  8424. (function (process){
  8425. /*!
  8426. * async
  8427. * https://github.com/caolan/async
  8428. *
  8429. * Copyright 2010-2014 Caolan McMahon
  8430. * Released under the MIT license
  8431. */
  8432. /*jshint onevar: false, indent:4 */
  8433. /*global setImmediate: false, setTimeout: false, console: false */
  8434. (function () {
  8435. var async = {};
  8436. // global on the server, window in the browser
  8437. var root, previous_async;
  8438. root = this;
  8439. if (root != null) {
  8440. previous_async = root.async;
  8441. }
  8442. async.noConflict = function () {
  8443. root.async = previous_async;
  8444. return async;
  8445. };
  8446. function only_once(fn) {
  8447. var called = false;
  8448. return function() {
  8449. if (called) throw new Error("Callback was already called.");
  8450. called = true;
  8451. fn.apply(root, arguments);
  8452. }
  8453. }
  8454. //// cross-browser compatiblity functions ////
  8455. var _toString = Object.prototype.toString;
  8456. var _isArray = Array.isArray || function (obj) {
  8457. return _toString.call(obj) === '[object Array]';
  8458. };
  8459. var _each = function (arr, iterator) {
  8460. if (arr.forEach) {
  8461. return arr.forEach(iterator);
  8462. }
  8463. for (var i = 0; i < arr.length; i += 1) {
  8464. iterator(arr[i], i, arr);
  8465. }
  8466. };
  8467. var _map = function (arr, iterator) {
  8468. if (arr.map) {
  8469. return arr.map(iterator);
  8470. }
  8471. var results = [];
  8472. _each(arr, function (x, i, a) {
  8473. results.push(iterator(x, i, a));
  8474. });
  8475. return results;
  8476. };
  8477. var _reduce = function (arr, iterator, memo) {
  8478. if (arr.reduce) {
  8479. return arr.reduce(iterator, memo);
  8480. }
  8481. _each(arr, function (x, i, a) {
  8482. memo = iterator(memo, x, i, a);
  8483. });
  8484. return memo;
  8485. };
  8486. var _keys = function (obj) {
  8487. if (Object.keys) {
  8488. return Object.keys(obj);
  8489. }
  8490. var keys = [];
  8491. for (var k in obj) {
  8492. if (obj.hasOwnProperty(k)) {
  8493. keys.push(k);
  8494. }
  8495. }
  8496. return keys;
  8497. };
  8498. //// exported async module functions ////
  8499. //// nextTick implementation with browser-compatible fallback ////
  8500. if (typeof process === 'undefined' || !(process.nextTick)) {
  8501. if (typeof setImmediate === 'function') {
  8502. async.nextTick = function (fn) {
  8503. // not a direct alias for IE10 compatibility
  8504. setImmediate(fn);
  8505. };
  8506. async.setImmediate = async.nextTick;
  8507. }
  8508. else {
  8509. async.nextTick = function (fn) {
  8510. setTimeout(fn, 0);
  8511. };
  8512. async.setImmediate = async.nextTick;
  8513. }
  8514. }
  8515. else {
  8516. async.nextTick = process.nextTick;
  8517. if (typeof setImmediate !== 'undefined') {
  8518. async.setImmediate = function (fn) {
  8519. // not a direct alias for IE10 compatibility
  8520. setImmediate(fn);
  8521. };
  8522. }
  8523. else {
  8524. async.setImmediate = async.nextTick;
  8525. }
  8526. }
  8527. async.each = function (arr, iterator, callback) {
  8528. callback = callback || function () {};
  8529. if (!arr.length) {
  8530. return callback();
  8531. }
  8532. var completed = 0;
  8533. _each(arr, function (x) {
  8534. iterator(x, only_once(done) );
  8535. });
  8536. function done(err) {
  8537. if (err) {
  8538. callback(err);
  8539. callback = function () {};
  8540. }
  8541. else {
  8542. completed += 1;
  8543. if (completed >= arr.length) {
  8544. callback();
  8545. }
  8546. }
  8547. }
  8548. };
  8549. async.forEach = async.each;
  8550. async.eachSeries = function (arr, iterator, callback) {
  8551. callback = callback || function () {};
  8552. if (!arr.length) {
  8553. return callback();
  8554. }
  8555. var completed = 0;
  8556. var iterate = function () {
  8557. iterator(arr[completed], function (err) {
  8558. if (err) {
  8559. callback(err);
  8560. callback = function () {};
  8561. }
  8562. else {
  8563. completed += 1;
  8564. if (completed >= arr.length) {
  8565. callback();
  8566. }
  8567. else {
  8568. iterate();
  8569. }
  8570. }
  8571. });
  8572. };
  8573. iterate();
  8574. };
  8575. async.forEachSeries = async.eachSeries;
  8576. async.eachLimit = function (arr, limit, iterator, callback) {
  8577. var fn = _eachLimit(limit);
  8578. fn.apply(null, [arr, iterator, callback]);
  8579. };
  8580. async.forEachLimit = async.eachLimit;
  8581. var _eachLimit = function (limit) {
  8582. return function (arr, iterator, callback) {
  8583. callback = callback || function () {};
  8584. if (!arr.length || limit <= 0) {
  8585. return callback();
  8586. }
  8587. var completed = 0;
  8588. var started = 0;
  8589. var running = 0;
  8590. (function replenish () {
  8591. if (completed >= arr.length) {
  8592. return callback();
  8593. }
  8594. while (running < limit && started < arr.length) {
  8595. started += 1;
  8596. running += 1;
  8597. iterator(arr[started - 1], function (err) {
  8598. if (err) {
  8599. callback(err);
  8600. callback = function () {};
  8601. }
  8602. else {
  8603. completed += 1;
  8604. running -= 1;
  8605. if (completed >= arr.length) {
  8606. callback();
  8607. }
  8608. else {
  8609. replenish();
  8610. }
  8611. }
  8612. });
  8613. }
  8614. })();
  8615. };
  8616. };
  8617. var doParallel = function (fn) {
  8618. return function () {
  8619. var args = Array.prototype.slice.call(arguments);
  8620. return fn.apply(null, [async.each].concat(args));
  8621. };
  8622. };
  8623. var doParallelLimit = function(limit, fn) {
  8624. return function () {
  8625. var args = Array.prototype.slice.call(arguments);
  8626. return fn.apply(null, [_eachLimit(limit)].concat(args));
  8627. };
  8628. };
  8629. var doSeries = function (fn) {
  8630. return function () {
  8631. var args = Array.prototype.slice.call(arguments);
  8632. return fn.apply(null, [async.eachSeries].concat(args));
  8633. };
  8634. };
  8635. var _asyncMap = function (eachfn, arr, iterator, callback) {
  8636. arr = _map(arr, function (x, i) {
  8637. return {index: i, value: x};
  8638. });
  8639. if (!callback) {
  8640. eachfn(arr, function (x, callback) {
  8641. iterator(x.value, function (err) {
  8642. callback(err);
  8643. });
  8644. });
  8645. } else {
  8646. var results = [];
  8647. eachfn(arr, function (x, callback) {
  8648. iterator(x.value, function (err, v) {
  8649. results[x.index] = v;
  8650. callback(err);
  8651. });
  8652. }, function (err) {
  8653. callback(err, results);
  8654. });
  8655. }
  8656. };
  8657. async.map = doParallel(_asyncMap);
  8658. async.mapSeries = doSeries(_asyncMap);
  8659. async.mapLimit = function (arr, limit, iterator, callback) {
  8660. return _mapLimit(limit)(arr, iterator, callback);
  8661. };
  8662. var _mapLimit = function(limit) {
  8663. return doParallelLimit(limit, _asyncMap);
  8664. };
  8665. // reduce only has a series version, as doing reduce in parallel won't
  8666. // work in many situations.
  8667. async.reduce = function (arr, memo, iterator, callback) {
  8668. async.eachSeries(arr, function (x, callback) {
  8669. iterator(memo, x, function (err, v) {
  8670. memo = v;
  8671. callback(err);
  8672. });
  8673. }, function (err) {
  8674. callback(err, memo);
  8675. });
  8676. };
  8677. // inject alias
  8678. async.inject = async.reduce;
  8679. // foldl alias
  8680. async.foldl = async.reduce;
  8681. async.reduceRight = function (arr, memo, iterator, callback) {
  8682. var reversed = _map(arr, function (x) {
  8683. return x;
  8684. }).reverse();
  8685. async.reduce(reversed, memo, iterator, callback);
  8686. };
  8687. // foldr alias
  8688. async.foldr = async.reduceRight;
  8689. var _filter = function (eachfn, arr, iterator, callback) {
  8690. var results = [];
  8691. arr = _map(arr, function (x, i) {
  8692. return {index: i, value: x};
  8693. });
  8694. eachfn(arr, function (x, callback) {
  8695. iterator(x.value, function (v) {
  8696. if (v) {
  8697. results.push(x);
  8698. }
  8699. callback();
  8700. });
  8701. }, function (err) {
  8702. callback(_map(results.sort(function (a, b) {
  8703. return a.index - b.index;
  8704. }), function (x) {
  8705. return x.value;
  8706. }));
  8707. });
  8708. };
  8709. async.filter = doParallel(_filter);
  8710. async.filterSeries = doSeries(_filter);
  8711. // select alias
  8712. async.select = async.filter;
  8713. async.selectSeries = async.filterSeries;
  8714. var _reject = function (eachfn, arr, iterator, callback) {
  8715. var results = [];
  8716. arr = _map(arr, function (x, i) {
  8717. return {index: i, value: x};
  8718. });
  8719. eachfn(arr, function (x, callback) {
  8720. iterator(x.value, function (v) {
  8721. if (!v) {
  8722. results.push(x);
  8723. }
  8724. callback();
  8725. });
  8726. }, function (err) {
  8727. callback(_map(results.sort(function (a, b) {
  8728. return a.index - b.index;
  8729. }), function (x) {
  8730. return x.value;
  8731. }));
  8732. });
  8733. };
  8734. async.reject = doParallel(_reject);
  8735. async.rejectSeries = doSeries(_reject);
  8736. var _detect = function (eachfn, arr, iterator, main_callback) {
  8737. eachfn(arr, function (x, callback) {
  8738. iterator(x, function (result) {
  8739. if (result) {
  8740. main_callback(x);
  8741. main_callback = function () {};
  8742. }
  8743. else {
  8744. callback();
  8745. }
  8746. });
  8747. }, function (err) {
  8748. main_callback();
  8749. });
  8750. };
  8751. async.detect = doParallel(_detect);
  8752. async.detectSeries = doSeries(_detect);
  8753. async.some = function (arr, iterator, main_callback) {
  8754. async.each(arr, function (x, callback) {
  8755. iterator(x, function (v) {
  8756. if (v) {
  8757. main_callback(true);
  8758. main_callback = function () {};
  8759. }
  8760. callback();
  8761. });
  8762. }, function (err) {
  8763. main_callback(false);
  8764. });
  8765. };
  8766. // any alias
  8767. async.any = async.some;
  8768. async.every = function (arr, iterator, main_callback) {
  8769. async.each(arr, function (x, callback) {
  8770. iterator(x, function (v) {
  8771. if (!v) {
  8772. main_callback(false);
  8773. main_callback = function () {};
  8774. }
  8775. callback();
  8776. });
  8777. }, function (err) {
  8778. main_callback(true);
  8779. });
  8780. };
  8781. // all alias
  8782. async.all = async.every;
  8783. async.sortBy = function (arr, iterator, callback) {
  8784. async.map(arr, function (x, callback) {
  8785. iterator(x, function (err, criteria) {
  8786. if (err) {
  8787. callback(err);
  8788. }
  8789. else {
  8790. callback(null, {value: x, criteria: criteria});
  8791. }
  8792. });
  8793. }, function (err, results) {
  8794. if (err) {
  8795. return callback(err);
  8796. }
  8797. else {
  8798. var fn = function (left, right) {
  8799. var a = left.criteria, b = right.criteria;
  8800. return a < b ? -1 : a > b ? 1 : 0;
  8801. };
  8802. callback(null, _map(results.sort(fn), function (x) {
  8803. return x.value;
  8804. }));
  8805. }
  8806. });
  8807. };
  8808. async.auto = function (tasks, callback) {
  8809. callback = callback || function () {};
  8810. var keys = _keys(tasks);
  8811. var remainingTasks = keys.length
  8812. if (!remainingTasks) {
  8813. return callback();
  8814. }
  8815. var results = {};
  8816. var listeners = [];
  8817. var addListener = function (fn) {
  8818. listeners.unshift(fn);
  8819. };
  8820. var removeListener = function (fn) {
  8821. for (var i = 0; i < listeners.length; i += 1) {
  8822. if (listeners[i] === fn) {
  8823. listeners.splice(i, 1);
  8824. return;
  8825. }
  8826. }
  8827. };
  8828. var taskComplete = function () {
  8829. remainingTasks--
  8830. _each(listeners.slice(0), function (fn) {
  8831. fn();
  8832. });
  8833. };
  8834. addListener(function () {
  8835. if (!remainingTasks) {
  8836. var theCallback = callback;
  8837. // prevent final callback from calling itself if it errors
  8838. callback = function () {};
  8839. theCallback(null, results);
  8840. }
  8841. });
  8842. _each(keys, function (k) {
  8843. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  8844. var taskCallback = function (err) {
  8845. var args = Array.prototype.slice.call(arguments, 1);
  8846. if (args.length <= 1) {
  8847. args = args[0];
  8848. }
  8849. if (err) {
  8850. var safeResults = {};
  8851. _each(_keys(results), function(rkey) {
  8852. safeResults[rkey] = results[rkey];
  8853. });
  8854. safeResults[k] = args;
  8855. callback(err, safeResults);
  8856. // stop subsequent errors hitting callback multiple times
  8857. callback = function () {};
  8858. }
  8859. else {
  8860. results[k] = args;
  8861. async.setImmediate(taskComplete);
  8862. }
  8863. };
  8864. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  8865. var ready = function () {
  8866. return _reduce(requires, function (a, x) {
  8867. return (a && results.hasOwnProperty(x));
  8868. }, true) && !results.hasOwnProperty(k);
  8869. };
  8870. if (ready()) {
  8871. task[task.length - 1](taskCallback, results);
  8872. }
  8873. else {
  8874. var listener = function () {
  8875. if (ready()) {
  8876. removeListener(listener);
  8877. task[task.length - 1](taskCallback, results);
  8878. }
  8879. };
  8880. addListener(listener);
  8881. }
  8882. });
  8883. };
  8884. async.retry = function(times, task, callback) {
  8885. var DEFAULT_TIMES = 5;
  8886. var attempts = [];
  8887. // Use defaults if times not passed
  8888. if (typeof times === 'function') {
  8889. callback = task;
  8890. task = times;
  8891. times = DEFAULT_TIMES;
  8892. }
  8893. // Make sure times is a number
  8894. times = parseInt(times, 10) || DEFAULT_TIMES;
  8895. var wrappedTask = function(wrappedCallback, wrappedResults) {
  8896. var retryAttempt = function(task, finalAttempt) {
  8897. return function(seriesCallback) {
  8898. task(function(err, result){
  8899. seriesCallback(!err || finalAttempt, {err: err, result: result});
  8900. }, wrappedResults);
  8901. };
  8902. };
  8903. while (times) {
  8904. attempts.push(retryAttempt(task, !(times-=1)));
  8905. }
  8906. async.series(attempts, function(done, data){
  8907. data = data[data.length - 1];
  8908. (wrappedCallback || callback)(data.err, data.result);
  8909. });
  8910. }
  8911. // If a callback is passed, run this as a controll flow
  8912. return callback ? wrappedTask() : wrappedTask
  8913. };
  8914. async.waterfall = function (tasks, callback) {
  8915. callback = callback || function () {};
  8916. if (!_isArray(tasks)) {
  8917. var err = new Error('First argument to waterfall must be an array of functions');
  8918. return callback(err);
  8919. }
  8920. if (!tasks.length) {
  8921. return callback();
  8922. }
  8923. var wrapIterator = function (iterator) {
  8924. return function (err) {
  8925. if (err) {
  8926. callback.apply(null, arguments);
  8927. callback = function () {};
  8928. }
  8929. else {
  8930. var args = Array.prototype.slice.call(arguments, 1);
  8931. var next = iterator.next();
  8932. if (next) {
  8933. args.push(wrapIterator(next));
  8934. }
  8935. else {
  8936. args.push(callback);
  8937. }
  8938. async.setImmediate(function () {
  8939. iterator.apply(null, args);
  8940. });
  8941. }
  8942. };
  8943. };
  8944. wrapIterator(async.iterator(tasks))();
  8945. };
  8946. var _parallel = function(eachfn, tasks, callback) {
  8947. callback = callback || function () {};
  8948. if (_isArray(tasks)) {
  8949. eachfn.map(tasks, function (fn, callback) {
  8950. if (fn) {
  8951. fn(function (err) {
  8952. var args = Array.prototype.slice.call(arguments, 1);
  8953. if (args.length <= 1) {
  8954. args = args[0];
  8955. }
  8956. callback.call(null, err, args);
  8957. });
  8958. }
  8959. }, callback);
  8960. }
  8961. else {
  8962. var results = {};
  8963. eachfn.each(_keys(tasks), function (k, callback) {
  8964. tasks[k](function (err) {
  8965. var args = Array.prototype.slice.call(arguments, 1);
  8966. if (args.length <= 1) {
  8967. args = args[0];
  8968. }
  8969. results[k] = args;
  8970. callback(err);
  8971. });
  8972. }, function (err) {
  8973. callback(err, results);
  8974. });
  8975. }
  8976. };
  8977. async.parallel = function (tasks, callback) {
  8978. _parallel({ map: async.map, each: async.each }, tasks, callback);
  8979. };
  8980. async.parallelLimit = function(tasks, limit, callback) {
  8981. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  8982. };
  8983. async.series = function (tasks, callback) {
  8984. callback = callback || function () {};
  8985. if (_isArray(tasks)) {
  8986. async.mapSeries(tasks, function (fn, callback) {
  8987. if (fn) {
  8988. fn(function (err) {
  8989. var args = Array.prototype.slice.call(arguments, 1);
  8990. if (args.length <= 1) {
  8991. args = args[0];
  8992. }
  8993. callback.call(null, err, args);
  8994. });
  8995. }
  8996. }, callback);
  8997. }
  8998. else {
  8999. var results = {};
  9000. async.eachSeries(_keys(tasks), function (k, callback) {
  9001. tasks[k](function (err) {
  9002. var args = Array.prototype.slice.call(arguments, 1);
  9003. if (args.length <= 1) {
  9004. args = args[0];
  9005. }
  9006. results[k] = args;
  9007. callback(err);
  9008. });
  9009. }, function (err) {
  9010. callback(err, results);
  9011. });
  9012. }
  9013. };
  9014. async.iterator = function (tasks) {
  9015. var makeCallback = function (index) {
  9016. var fn = function () {
  9017. if (tasks.length) {
  9018. tasks[index].apply(null, arguments);
  9019. }
  9020. return fn.next();
  9021. };
  9022. fn.next = function () {
  9023. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  9024. };
  9025. return fn;
  9026. };
  9027. return makeCallback(0);
  9028. };
  9029. async.apply = function (fn) {
  9030. var args = Array.prototype.slice.call(arguments, 1);
  9031. return function () {
  9032. return fn.apply(
  9033. null, args.concat(Array.prototype.slice.call(arguments))
  9034. );
  9035. };
  9036. };
  9037. var _concat = function (eachfn, arr, fn, callback) {
  9038. var r = [];
  9039. eachfn(arr, function (x, cb) {
  9040. fn(x, function (err, y) {
  9041. r = r.concat(y || []);
  9042. cb(err);
  9043. });
  9044. }, function (err) {
  9045. callback(err, r);
  9046. });
  9047. };
  9048. async.concat = doParallel(_concat);
  9049. async.concatSeries = doSeries(_concat);
  9050. async.whilst = function (test, iterator, callback) {
  9051. if (test()) {
  9052. iterator(function (err) {
  9053. if (err) {
  9054. return callback(err);
  9055. }
  9056. async.whilst(test, iterator, callback);
  9057. });
  9058. }
  9059. else {
  9060. callback();
  9061. }
  9062. };
  9063. async.doWhilst = function (iterator, test, callback) {
  9064. iterator(function (err) {
  9065. if (err) {
  9066. return callback(err);
  9067. }
  9068. var args = Array.prototype.slice.call(arguments, 1);
  9069. if (test.apply(null, args)) {
  9070. async.doWhilst(iterator, test, callback);
  9071. }
  9072. else {
  9073. callback();
  9074. }
  9075. });
  9076. };
  9077. async.until = function (test, iterator, callback) {
  9078. if (!test()) {
  9079. iterator(function (err) {
  9080. if (err) {
  9081. return callback(err);
  9082. }
  9083. async.until(test, iterator, callback);
  9084. });
  9085. }
  9086. else {
  9087. callback();
  9088. }
  9089. };
  9090. async.doUntil = function (iterator, test, callback) {
  9091. iterator(function (err) {
  9092. if (err) {
  9093. return callback(err);
  9094. }
  9095. var args = Array.prototype.slice.call(arguments, 1);
  9096. if (!test.apply(null, args)) {
  9097. async.doUntil(iterator, test, callback);
  9098. }
  9099. else {
  9100. callback();
  9101. }
  9102. });
  9103. };
  9104. async.queue = function (worker, concurrency) {
  9105. if (concurrency === undefined) {
  9106. concurrency = 1;
  9107. }
  9108. function _insert(q, data, pos, callback) {
  9109. if (!q.started){
  9110. q.started = true;
  9111. }
  9112. if (!_isArray(data)) {
  9113. data = [data];
  9114. }
  9115. if(data.length == 0) {
  9116. // call drain immediately if there are no tasks
  9117. return async.setImmediate(function() {
  9118. if (q.drain) {
  9119. q.drain();
  9120. }
  9121. });
  9122. }
  9123. _each(data, function(task) {
  9124. var item = {
  9125. data: task,
  9126. callback: typeof callback === 'function' ? callback : null
  9127. };
  9128. if (pos) {
  9129. q.tasks.unshift(item);
  9130. } else {
  9131. q.tasks.push(item);
  9132. }
  9133. if (q.saturated && q.tasks.length === q.concurrency) {
  9134. q.saturated();
  9135. }
  9136. async.setImmediate(q.process);
  9137. });
  9138. }
  9139. var workers = 0;
  9140. var q = {
  9141. tasks: [],
  9142. concurrency: concurrency,
  9143. saturated: null,
  9144. empty: null,
  9145. drain: null,
  9146. started: false,
  9147. paused: false,
  9148. push: function (data, callback) {
  9149. _insert(q, data, false, callback);
  9150. },
  9151. kill: function () {
  9152. q.drain = null;
  9153. q.tasks = [];
  9154. },
  9155. unshift: function (data, callback) {
  9156. _insert(q, data, true, callback);
  9157. },
  9158. process: function () {
  9159. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  9160. var task = q.tasks.shift();
  9161. if (q.empty && q.tasks.length === 0) {
  9162. q.empty();
  9163. }
  9164. workers += 1;
  9165. var next = function () {
  9166. workers -= 1;
  9167. if (task.callback) {
  9168. task.callback.apply(task, arguments);
  9169. }
  9170. if (q.drain && q.tasks.length + workers === 0) {
  9171. q.drain();
  9172. }
  9173. q.process();
  9174. };
  9175. var cb = only_once(next);
  9176. worker(task.data, cb);
  9177. }
  9178. },
  9179. length: function () {
  9180. return q.tasks.length;
  9181. },
  9182. running: function () {
  9183. return workers;
  9184. },
  9185. idle: function() {
  9186. return q.tasks.length + workers === 0;
  9187. },
  9188. pause: function () {
  9189. if (q.paused === true) { return; }
  9190. q.paused = true;
  9191. q.process();
  9192. },
  9193. resume: function () {
  9194. if (q.paused === false) { return; }
  9195. q.paused = false;
  9196. q.process();
  9197. }
  9198. };
  9199. return q;
  9200. };
  9201. async.priorityQueue = function (worker, concurrency) {
  9202. function _compareTasks(a, b){
  9203. return a.priority - b.priority;
  9204. };
  9205. function _binarySearch(sequence, item, compare) {
  9206. var beg = -1,
  9207. end = sequence.length - 1;
  9208. while (beg < end) {
  9209. var mid = beg + ((end - beg + 1) >>> 1);
  9210. if (compare(item, sequence[mid]) >= 0) {
  9211. beg = mid;
  9212. } else {
  9213. end = mid - 1;
  9214. }
  9215. }
  9216. return beg;
  9217. }
  9218. function _insert(q, data, priority, callback) {
  9219. if (!q.started){
  9220. q.started = true;
  9221. }
  9222. if (!_isArray(data)) {
  9223. data = [data];
  9224. }
  9225. if(data.length == 0) {
  9226. // call drain immediately if there are no tasks
  9227. return async.setImmediate(function() {
  9228. if (q.drain) {
  9229. q.drain();
  9230. }
  9231. });
  9232. }
  9233. _each(data, function(task) {
  9234. var item = {
  9235. data: task,
  9236. priority: priority,
  9237. callback: typeof callback === 'function' ? callback : null
  9238. };
  9239. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  9240. if (q.saturated && q.tasks.length === q.concurrency) {
  9241. q.saturated();
  9242. }
  9243. async.setImmediate(q.process);
  9244. });
  9245. }
  9246. // Start with a normal queue
  9247. var q = async.queue(worker, concurrency);
  9248. // Override push to accept second parameter representing priority
  9249. q.push = function (data, priority, callback) {
  9250. _insert(q, data, priority, callback);
  9251. };
  9252. // Remove unshift function
  9253. delete q.unshift;
  9254. return q;
  9255. };
  9256. async.cargo = function (worker, payload) {
  9257. var working = false,
  9258. tasks = [];
  9259. var cargo = {
  9260. tasks: tasks,
  9261. payload: payload,
  9262. saturated: null,
  9263. empty: null,
  9264. drain: null,
  9265. drained: true,
  9266. push: function (data, callback) {
  9267. if (!_isArray(data)) {
  9268. data = [data];
  9269. }
  9270. _each(data, function(task) {
  9271. tasks.push({
  9272. data: task,
  9273. callback: typeof callback === 'function' ? callback : null
  9274. });
  9275. cargo.drained = false;
  9276. if (cargo.saturated && tasks.length === payload) {
  9277. cargo.saturated();
  9278. }
  9279. });
  9280. async.setImmediate(cargo.process);
  9281. },
  9282. process: function process() {
  9283. if (working) return;
  9284. if (tasks.length === 0) {
  9285. if(cargo.drain && !cargo.drained) cargo.drain();
  9286. cargo.drained = true;
  9287. return;
  9288. }
  9289. var ts = typeof payload === 'number'
  9290. ? tasks.splice(0, payload)
  9291. : tasks.splice(0, tasks.length);
  9292. var ds = _map(ts, function (task) {
  9293. return task.data;
  9294. });
  9295. if(cargo.empty) cargo.empty();
  9296. working = true;
  9297. worker(ds, function () {
  9298. working = false;
  9299. var args = arguments;
  9300. _each(ts, function (data) {
  9301. if (data.callback) {
  9302. data.callback.apply(null, args);
  9303. }
  9304. });
  9305. process();
  9306. });
  9307. },
  9308. length: function () {
  9309. return tasks.length;
  9310. },
  9311. running: function () {
  9312. return working;
  9313. }
  9314. };
  9315. return cargo;
  9316. };
  9317. var _console_fn = function (name) {
  9318. return function (fn) {
  9319. var args = Array.prototype.slice.call(arguments, 1);
  9320. fn.apply(null, args.concat([function (err) {
  9321. var args = Array.prototype.slice.call(arguments, 1);
  9322. if (typeof console !== 'undefined') {
  9323. if (err) {
  9324. if (console.error) {
  9325. console.error(err);
  9326. }
  9327. }
  9328. else if (console[name]) {
  9329. _each(args, function (x) {
  9330. console[name](x);
  9331. });
  9332. }
  9333. }
  9334. }]));
  9335. };
  9336. };
  9337. async.log = _console_fn('log');
  9338. async.dir = _console_fn('dir');
  9339. /*async.info = _console_fn('info');
  9340. async.warn = _console_fn('warn');
  9341. async.error = _console_fn('error');*/
  9342. async.memoize = function (fn, hasher) {
  9343. var memo = {};
  9344. var queues = {};
  9345. hasher = hasher || function (x) {
  9346. return x;
  9347. };
  9348. var memoized = function () {
  9349. var args = Array.prototype.slice.call(arguments);
  9350. var callback = args.pop();
  9351. var key = hasher.apply(null, args);
  9352. if (key in memo) {
  9353. async.nextTick(function () {
  9354. callback.apply(null, memo[key]);
  9355. });
  9356. }
  9357. else if (key in queues) {
  9358. queues[key].push(callback);
  9359. }
  9360. else {
  9361. queues[key] = [callback];
  9362. fn.apply(null, args.concat([function () {
  9363. memo[key] = arguments;
  9364. var q = queues[key];
  9365. delete queues[key];
  9366. for (var i = 0, l = q.length; i < l; i++) {
  9367. q[i].apply(null, arguments);
  9368. }
  9369. }]));
  9370. }
  9371. };
  9372. memoized.memo = memo;
  9373. memoized.unmemoized = fn;
  9374. return memoized;
  9375. };
  9376. async.unmemoize = function (fn) {
  9377. return function () {
  9378. return (fn.unmemoized || fn).apply(null, arguments);
  9379. };
  9380. };
  9381. async.times = function (count, iterator, callback) {
  9382. var counter = [];
  9383. for (var i = 0; i < count; i++) {
  9384. counter.push(i);
  9385. }
  9386. return async.map(counter, iterator, callback);
  9387. };
  9388. async.timesSeries = function (count, iterator, callback) {
  9389. var counter = [];
  9390. for (var i = 0; i < count; i++) {
  9391. counter.push(i);
  9392. }
  9393. return async.mapSeries(counter, iterator, callback);
  9394. };
  9395. async.seq = function (/* functions... */) {
  9396. var fns = arguments;
  9397. return function () {
  9398. var that = this;
  9399. var args = Array.prototype.slice.call(arguments);
  9400. var callback = args.pop();
  9401. async.reduce(fns, args, function (newargs, fn, cb) {
  9402. fn.apply(that, newargs.concat([function () {
  9403. var err = arguments[0];
  9404. var nextargs = Array.prototype.slice.call(arguments, 1);
  9405. cb(err, nextargs);
  9406. }]))
  9407. },
  9408. function (err, results) {
  9409. callback.apply(that, [err].concat(results));
  9410. });
  9411. };
  9412. };
  9413. async.compose = function (/* functions... */) {
  9414. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  9415. };
  9416. var _applyEach = function (eachfn, fns /*args...*/) {
  9417. var go = function () {
  9418. var that = this;
  9419. var args = Array.prototype.slice.call(arguments);
  9420. var callback = args.pop();
  9421. return eachfn(fns, function (fn, cb) {
  9422. fn.apply(that, args.concat([cb]));
  9423. },
  9424. callback);
  9425. };
  9426. if (arguments.length > 2) {
  9427. var args = Array.prototype.slice.call(arguments, 2);
  9428. return go.apply(this, args);
  9429. }
  9430. else {
  9431. return go;
  9432. }
  9433. };
  9434. async.applyEach = doParallel(_applyEach);
  9435. async.applyEachSeries = doSeries(_applyEach);
  9436. async.forever = function (fn, callback) {
  9437. function next(err) {
  9438. if (err) {
  9439. if (callback) {
  9440. return callback(err);
  9441. }
  9442. throw err;
  9443. }
  9444. fn(next);
  9445. }
  9446. next();
  9447. };
  9448. // Node.js
  9449. if (typeof module !== 'undefined' && module.exports) {
  9450. module.exports = async;
  9451. }
  9452. // AMD / RequireJS
  9453. else if (typeof define !== 'undefined' && define.amd) {
  9454. define([], function () {
  9455. return async;
  9456. });
  9457. }
  9458. // included directly via <script> tag
  9459. else {
  9460. root.async = async;
  9461. }
  9462. }());
  9463. }).call(this,require('_process'))
  9464. },{"_process":78}],35:[function(require,module,exports){
  9465. (function (process,global){
  9466. /*!
  9467. * @overview es6-promise - a tiny implementation of Promises/A+.
  9468. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  9469. * @license Licensed under MIT license
  9470. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  9471. * @version 3.0.2
  9472. */
  9473. (function() {
  9474. "use strict";
  9475. function lib$es6$promise$utils$$objectOrFunction(x) {
  9476. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  9477. }
  9478. function lib$es6$promise$utils$$isFunction(x) {
  9479. return typeof x === 'function';
  9480. }
  9481. function lib$es6$promise$utils$$isMaybeThenable(x) {
  9482. return typeof x === 'object' && x !== null;
  9483. }
  9484. var lib$es6$promise$utils$$_isArray;
  9485. if (!Array.isArray) {
  9486. lib$es6$promise$utils$$_isArray = function (x) {
  9487. return Object.prototype.toString.call(x) === '[object Array]';
  9488. };
  9489. } else {
  9490. lib$es6$promise$utils$$_isArray = Array.isArray;
  9491. }
  9492. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  9493. var lib$es6$promise$asap$$len = 0;
  9494. var lib$es6$promise$asap$$toString = {}.toString;
  9495. var lib$es6$promise$asap$$vertxNext;
  9496. var lib$es6$promise$asap$$customSchedulerFn;
  9497. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  9498. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  9499. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  9500. lib$es6$promise$asap$$len += 2;
  9501. if (lib$es6$promise$asap$$len === 2) {
  9502. // If len is 2, that means that we need to schedule an async flush.
  9503. // If additional callbacks are queued before the queue is flushed, they
  9504. // will be processed by this flush that we are scheduling.
  9505. if (lib$es6$promise$asap$$customSchedulerFn) {
  9506. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  9507. } else {
  9508. lib$es6$promise$asap$$scheduleFlush();
  9509. }
  9510. }
  9511. }
  9512. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  9513. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  9514. }
  9515. function lib$es6$promise$asap$$setAsap(asapFn) {
  9516. lib$es6$promise$asap$$asap = asapFn;
  9517. }
  9518. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  9519. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  9520. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  9521. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  9522. // test for web worker but not in IE10
  9523. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  9524. typeof importScripts !== 'undefined' &&
  9525. typeof MessageChannel !== 'undefined';
  9526. // node
  9527. function lib$es6$promise$asap$$useNextTick() {
  9528. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  9529. // see https://github.com/cujojs/when/issues/410 for details
  9530. return function() {
  9531. process.nextTick(lib$es6$promise$asap$$flush);
  9532. };
  9533. }
  9534. // vertx
  9535. function lib$es6$promise$asap$$useVertxTimer() {
  9536. return function() {
  9537. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  9538. };
  9539. }
  9540. function lib$es6$promise$asap$$useMutationObserver() {
  9541. var iterations = 0;
  9542. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  9543. var node = document.createTextNode('');
  9544. observer.observe(node, { characterData: true });
  9545. return function() {
  9546. node.data = (iterations = ++iterations % 2);
  9547. };
  9548. }
  9549. // web worker
  9550. function lib$es6$promise$asap$$useMessageChannel() {
  9551. var channel = new MessageChannel();
  9552. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  9553. return function () {
  9554. channel.port2.postMessage(0);
  9555. };
  9556. }
  9557. function lib$es6$promise$asap$$useSetTimeout() {
  9558. return function() {
  9559. setTimeout(lib$es6$promise$asap$$flush, 1);
  9560. };
  9561. }
  9562. var lib$es6$promise$asap$$queue = new Array(1000);
  9563. function lib$es6$promise$asap$$flush() {
  9564. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  9565. var callback = lib$es6$promise$asap$$queue[i];
  9566. var arg = lib$es6$promise$asap$$queue[i+1];
  9567. callback(arg);
  9568. lib$es6$promise$asap$$queue[i] = undefined;
  9569. lib$es6$promise$asap$$queue[i+1] = undefined;
  9570. }
  9571. lib$es6$promise$asap$$len = 0;
  9572. }
  9573. function lib$es6$promise$asap$$attemptVertx() {
  9574. try {
  9575. var r = require;
  9576. var vertx = r('vertx');
  9577. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  9578. return lib$es6$promise$asap$$useVertxTimer();
  9579. } catch(e) {
  9580. return lib$es6$promise$asap$$useSetTimeout();
  9581. }
  9582. }
  9583. var lib$es6$promise$asap$$scheduleFlush;
  9584. // Decide what async method to use to triggering processing of queued callbacks:
  9585. if (lib$es6$promise$asap$$isNode) {
  9586. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  9587. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  9588. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  9589. } else if (lib$es6$promise$asap$$isWorker) {
  9590. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  9591. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  9592. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  9593. } else {
  9594. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  9595. }
  9596. function lib$es6$promise$$internal$$noop() {}
  9597. var lib$es6$promise$$internal$$PENDING = void 0;
  9598. var lib$es6$promise$$internal$$FULFILLED = 1;
  9599. var lib$es6$promise$$internal$$REJECTED = 2;
  9600. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  9601. function lib$es6$promise$$internal$$selfFulfillment() {
  9602. return new TypeError("You cannot resolve a promise with itself");
  9603. }
  9604. function lib$es6$promise$$internal$$cannotReturnOwn() {
  9605. return new TypeError('A promises callback cannot return that same promise.');
  9606. }
  9607. function lib$es6$promise$$internal$$getThen(promise) {
  9608. try {
  9609. return promise.then;
  9610. } catch(error) {
  9611. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  9612. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  9613. }
  9614. }
  9615. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  9616. try {
  9617. then.call(value, fulfillmentHandler, rejectionHandler);
  9618. } catch(e) {
  9619. return e;
  9620. }
  9621. }
  9622. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  9623. lib$es6$promise$asap$$asap(function(promise) {
  9624. var sealed = false;
  9625. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  9626. if (sealed) { return; }
  9627. sealed = true;
  9628. if (thenable !== value) {
  9629. lib$es6$promise$$internal$$resolve(promise, value);
  9630. } else {
  9631. lib$es6$promise$$internal$$fulfill(promise, value);
  9632. }
  9633. }, function(reason) {
  9634. if (sealed) { return; }
  9635. sealed = true;
  9636. lib$es6$promise$$internal$$reject(promise, reason);
  9637. }, 'Settle: ' + (promise._label || ' unknown promise'));
  9638. if (!sealed && error) {
  9639. sealed = true;
  9640. lib$es6$promise$$internal$$reject(promise, error);
  9641. }
  9642. }, promise);
  9643. }
  9644. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  9645. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  9646. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  9647. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  9648. lib$es6$promise$$internal$$reject(promise, thenable._result);
  9649. } else {
  9650. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  9651. lib$es6$promise$$internal$$resolve(promise, value);
  9652. }, function(reason) {
  9653. lib$es6$promise$$internal$$reject(promise, reason);
  9654. });
  9655. }
  9656. }
  9657. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  9658. if (maybeThenable.constructor === promise.constructor) {
  9659. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  9660. } else {
  9661. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  9662. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  9663. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  9664. } else if (then === undefined) {
  9665. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  9666. } else if (lib$es6$promise$utils$$isFunction(then)) {
  9667. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  9668. } else {
  9669. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  9670. }
  9671. }
  9672. }
  9673. function lib$es6$promise$$internal$$resolve(promise, value) {
  9674. if (promise === value) {
  9675. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  9676. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  9677. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  9678. } else {
  9679. lib$es6$promise$$internal$$fulfill(promise, value);
  9680. }
  9681. }
  9682. function lib$es6$promise$$internal$$publishRejection(promise) {
  9683. if (promise._onerror) {
  9684. promise._onerror(promise._result);
  9685. }
  9686. lib$es6$promise$$internal$$publish(promise);
  9687. }
  9688. function lib$es6$promise$$internal$$fulfill(promise, value) {
  9689. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  9690. promise._result = value;
  9691. promise._state = lib$es6$promise$$internal$$FULFILLED;
  9692. if (promise._subscribers.length !== 0) {
  9693. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  9694. }
  9695. }
  9696. function lib$es6$promise$$internal$$reject(promise, reason) {
  9697. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  9698. promise._state = lib$es6$promise$$internal$$REJECTED;
  9699. promise._result = reason;
  9700. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  9701. }
  9702. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  9703. var subscribers = parent._subscribers;
  9704. var length = subscribers.length;
  9705. parent._onerror = null;
  9706. subscribers[length] = child;
  9707. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  9708. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  9709. if (length === 0 && parent._state) {
  9710. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  9711. }
  9712. }
  9713. function lib$es6$promise$$internal$$publish(promise) {
  9714. var subscribers = promise._subscribers;
  9715. var settled = promise._state;
  9716. if (subscribers.length === 0) { return; }
  9717. var child, callback, detail = promise._result;
  9718. for (var i = 0; i < subscribers.length; i += 3) {
  9719. child = subscribers[i];
  9720. callback = subscribers[i + settled];
  9721. if (child) {
  9722. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  9723. } else {
  9724. callback(detail);
  9725. }
  9726. }
  9727. promise._subscribers.length = 0;
  9728. }
  9729. function lib$es6$promise$$internal$$ErrorObject() {
  9730. this.error = null;
  9731. }
  9732. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  9733. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  9734. try {
  9735. return callback(detail);
  9736. } catch(e) {
  9737. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  9738. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  9739. }
  9740. }
  9741. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  9742. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  9743. value, error, succeeded, failed;
  9744. if (hasCallback) {
  9745. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  9746. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  9747. failed = true;
  9748. error = value.error;
  9749. value = null;
  9750. } else {
  9751. succeeded = true;
  9752. }
  9753. if (promise === value) {
  9754. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  9755. return;
  9756. }
  9757. } else {
  9758. value = detail;
  9759. succeeded = true;
  9760. }
  9761. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  9762. // noop
  9763. } else if (hasCallback && succeeded) {
  9764. lib$es6$promise$$internal$$resolve(promise, value);
  9765. } else if (failed) {
  9766. lib$es6$promise$$internal$$reject(promise, error);
  9767. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  9768. lib$es6$promise$$internal$$fulfill(promise, value);
  9769. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  9770. lib$es6$promise$$internal$$reject(promise, value);
  9771. }
  9772. }
  9773. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  9774. try {
  9775. resolver(function resolvePromise(value){
  9776. lib$es6$promise$$internal$$resolve(promise, value);
  9777. }, function rejectPromise(reason) {
  9778. lib$es6$promise$$internal$$reject(promise, reason);
  9779. });
  9780. } catch(e) {
  9781. lib$es6$promise$$internal$$reject(promise, e);
  9782. }
  9783. }
  9784. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  9785. var enumerator = this;
  9786. enumerator._instanceConstructor = Constructor;
  9787. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  9788. if (enumerator._validateInput(input)) {
  9789. enumerator._input = input;
  9790. enumerator.length = input.length;
  9791. enumerator._remaining = input.length;
  9792. enumerator._init();
  9793. if (enumerator.length === 0) {
  9794. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  9795. } else {
  9796. enumerator.length = enumerator.length || 0;
  9797. enumerator._enumerate();
  9798. if (enumerator._remaining === 0) {
  9799. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  9800. }
  9801. }
  9802. } else {
  9803. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  9804. }
  9805. }
  9806. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  9807. return lib$es6$promise$utils$$isArray(input);
  9808. };
  9809. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  9810. return new Error('Array Methods must be provided an Array');
  9811. };
  9812. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  9813. this._result = new Array(this.length);
  9814. };
  9815. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  9816. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  9817. var enumerator = this;
  9818. var length = enumerator.length;
  9819. var promise = enumerator.promise;
  9820. var input = enumerator._input;
  9821. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  9822. enumerator._eachEntry(input[i], i);
  9823. }
  9824. };
  9825. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  9826. var enumerator = this;
  9827. var c = enumerator._instanceConstructor;
  9828. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  9829. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  9830. entry._onerror = null;
  9831. enumerator._settledAt(entry._state, i, entry._result);
  9832. } else {
  9833. enumerator._willSettleAt(c.resolve(entry), i);
  9834. }
  9835. } else {
  9836. enumerator._remaining--;
  9837. enumerator._result[i] = entry;
  9838. }
  9839. };
  9840. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  9841. var enumerator = this;
  9842. var promise = enumerator.promise;
  9843. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  9844. enumerator._remaining--;
  9845. if (state === lib$es6$promise$$internal$$REJECTED) {
  9846. lib$es6$promise$$internal$$reject(promise, value);
  9847. } else {
  9848. enumerator._result[i] = value;
  9849. }
  9850. }
  9851. if (enumerator._remaining === 0) {
  9852. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  9853. }
  9854. };
  9855. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  9856. var enumerator = this;
  9857. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  9858. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  9859. }, function(reason) {
  9860. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  9861. });
  9862. };
  9863. function lib$es6$promise$promise$all$$all(entries) {
  9864. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  9865. }
  9866. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  9867. function lib$es6$promise$promise$race$$race(entries) {
  9868. /*jshint validthis:true */
  9869. var Constructor = this;
  9870. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  9871. if (!lib$es6$promise$utils$$isArray(entries)) {
  9872. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  9873. return promise;
  9874. }
  9875. var length = entries.length;
  9876. function onFulfillment(value) {
  9877. lib$es6$promise$$internal$$resolve(promise, value);
  9878. }
  9879. function onRejection(reason) {
  9880. lib$es6$promise$$internal$$reject(promise, reason);
  9881. }
  9882. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  9883. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  9884. }
  9885. return promise;
  9886. }
  9887. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  9888. function lib$es6$promise$promise$resolve$$resolve(object) {
  9889. /*jshint validthis:true */
  9890. var Constructor = this;
  9891. if (object && typeof object === 'object' && object.constructor === Constructor) {
  9892. return object;
  9893. }
  9894. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  9895. lib$es6$promise$$internal$$resolve(promise, object);
  9896. return promise;
  9897. }
  9898. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  9899. function lib$es6$promise$promise$reject$$reject(reason) {
  9900. /*jshint validthis:true */
  9901. var Constructor = this;
  9902. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  9903. lib$es6$promise$$internal$$reject(promise, reason);
  9904. return promise;
  9905. }
  9906. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  9907. var lib$es6$promise$promise$$counter = 0;
  9908. function lib$es6$promise$promise$$needsResolver() {
  9909. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  9910. }
  9911. function lib$es6$promise$promise$$needsNew() {
  9912. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  9913. }
  9914. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  9915. /**
  9916. Promise objects represent the eventual result of an asynchronous operation. The
  9917. primary way of interacting with a promise is through its `then` method, which
  9918. registers callbacks to receive either a promise's eventual value or the reason
  9919. why the promise cannot be fulfilled.
  9920. Terminology
  9921. -----------
  9922. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  9923. - `thenable` is an object or function that defines a `then` method.
  9924. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  9925. - `exception` is a value that is thrown using the throw statement.
  9926. - `reason` is a value that indicates why a promise was rejected.
  9927. - `settled` the final resting state of a promise, fulfilled or rejected.
  9928. A promise can be in one of three states: pending, fulfilled, or rejected.
  9929. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  9930. state. Promises that are rejected have a rejection reason and are in the
  9931. rejected state. A fulfillment value is never a thenable.
  9932. Promises can also be said to *resolve* a value. If this value is also a
  9933. promise, then the original promise's settled state will match the value's
  9934. settled state. So a promise that *resolves* a promise that rejects will
  9935. itself reject, and a promise that *resolves* a promise that fulfills will
  9936. itself fulfill.
  9937. Basic Usage:
  9938. ------------
  9939. ```js
  9940. var promise = new Promise(function(resolve, reject) {
  9941. // on success
  9942. resolve(value);
  9943. // on failure
  9944. reject(reason);
  9945. });
  9946. promise.then(function(value) {
  9947. // on fulfillment
  9948. }, function(reason) {
  9949. // on rejection
  9950. });
  9951. ```
  9952. Advanced Usage:
  9953. ---------------
  9954. Promises shine when abstracting away asynchronous interactions such as
  9955. `XMLHttpRequest`s.
  9956. ```js
  9957. function getJSON(url) {
  9958. return new Promise(function(resolve, reject){
  9959. var xhr = new XMLHttpRequest();
  9960. xhr.open('GET', url);
  9961. xhr.onreadystatechange = handler;
  9962. xhr.responseType = 'json';
  9963. xhr.setRequestHeader('Accept', 'application/json');
  9964. xhr.send();
  9965. function handler() {
  9966. if (this.readyState === this.DONE) {
  9967. if (this.status === 200) {
  9968. resolve(this.response);
  9969. } else {
  9970. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  9971. }
  9972. }
  9973. };
  9974. });
  9975. }
  9976. getJSON('/posts.json').then(function(json) {
  9977. // on fulfillment
  9978. }, function(reason) {
  9979. // on rejection
  9980. });
  9981. ```
  9982. Unlike callbacks, promises are great composable primitives.
  9983. ```js
  9984. Promise.all([
  9985. getJSON('/posts'),
  9986. getJSON('/comments')
  9987. ]).then(function(values){
  9988. values[0] // => postsJSON
  9989. values[1] // => commentsJSON
  9990. return values;
  9991. });
  9992. ```
  9993. @class Promise
  9994. @param {function} resolver
  9995. Useful for tooling.
  9996. @constructor
  9997. */
  9998. function lib$es6$promise$promise$$Promise(resolver) {
  9999. this._id = lib$es6$promise$promise$$counter++;
  10000. this._state = undefined;
  10001. this._result = undefined;
  10002. this._subscribers = [];
  10003. if (lib$es6$promise$$internal$$noop !== resolver) {
  10004. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  10005. lib$es6$promise$promise$$needsResolver();
  10006. }
  10007. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  10008. lib$es6$promise$promise$$needsNew();
  10009. }
  10010. lib$es6$promise$$internal$$initializePromise(this, resolver);
  10011. }
  10012. }
  10013. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  10014. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  10015. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  10016. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  10017. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  10018. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  10019. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  10020. lib$es6$promise$promise$$Promise.prototype = {
  10021. constructor: lib$es6$promise$promise$$Promise,
  10022. /**
  10023. The primary way of interacting with a promise is through its `then` method,
  10024. which registers callbacks to receive either a promise's eventual value or the
  10025. reason why the promise cannot be fulfilled.
  10026. ```js
  10027. findUser().then(function(user){
  10028. // user is available
  10029. }, function(reason){
  10030. // user is unavailable, and you are given the reason why
  10031. });
  10032. ```
  10033. Chaining
  10034. --------
  10035. The return value of `then` is itself a promise. This second, 'downstream'
  10036. promise is resolved with the return value of the first promise's fulfillment
  10037. or rejection handler, or rejected if the handler throws an exception.
  10038. ```js
  10039. findUser().then(function (user) {
  10040. return user.name;
  10041. }, function (reason) {
  10042. return 'default name';
  10043. }).then(function (userName) {
  10044. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  10045. // will be `'default name'`
  10046. });
  10047. findUser().then(function (user) {
  10048. throw new Error('Found user, but still unhappy');
  10049. }, function (reason) {
  10050. throw new Error('`findUser` rejected and we're unhappy');
  10051. }).then(function (value) {
  10052. // never reached
  10053. }, function (reason) {
  10054. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  10055. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  10056. });
  10057. ```
  10058. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  10059. ```js
  10060. findUser().then(function (user) {
  10061. throw new PedagogicalException('Upstream error');
  10062. }).then(function (value) {
  10063. // never reached
  10064. }).then(function (value) {
  10065. // never reached
  10066. }, function (reason) {
  10067. // The `PedgagocialException` is propagated all the way down to here
  10068. });
  10069. ```
  10070. Assimilation
  10071. ------------
  10072. Sometimes the value you want to propagate to a downstream promise can only be
  10073. retrieved asynchronously. This can be achieved by returning a promise in the
  10074. fulfillment or rejection handler. The downstream promise will then be pending
  10075. until the returned promise is settled. This is called *assimilation*.
  10076. ```js
  10077. findUser().then(function (user) {
  10078. return findCommentsByAuthor(user);
  10079. }).then(function (comments) {
  10080. // The user's comments are now available
  10081. });
  10082. ```
  10083. If the assimliated promise rejects, then the downstream promise will also reject.
  10084. ```js
  10085. findUser().then(function (user) {
  10086. return findCommentsByAuthor(user);
  10087. }).then(function (comments) {
  10088. // If `findCommentsByAuthor` fulfills, we'll have the value here
  10089. }, function (reason) {
  10090. // If `findCommentsByAuthor` rejects, we'll have the reason here
  10091. });
  10092. ```
  10093. Simple Example
  10094. --------------
  10095. Synchronous Example
  10096. ```javascript
  10097. var result;
  10098. try {
  10099. result = findResult();
  10100. // success
  10101. } catch(reason) {
  10102. // failure
  10103. }
  10104. ```
  10105. Errback Example
  10106. ```js
  10107. findResult(function(result, err){
  10108. if (err) {
  10109. // failure
  10110. } else {
  10111. // success
  10112. }
  10113. });
  10114. ```
  10115. Promise Example;
  10116. ```javascript
  10117. findResult().then(function(result){
  10118. // success
  10119. }, function(reason){
  10120. // failure
  10121. });
  10122. ```
  10123. Advanced Example
  10124. --------------
  10125. Synchronous Example
  10126. ```javascript
  10127. var author, books;
  10128. try {
  10129. author = findAuthor();
  10130. books = findBooksByAuthor(author);
  10131. // success
  10132. } catch(reason) {
  10133. // failure
  10134. }
  10135. ```
  10136. Errback Example
  10137. ```js
  10138. function foundBooks(books) {
  10139. }
  10140. function failure(reason) {
  10141. }
  10142. findAuthor(function(author, err){
  10143. if (err) {
  10144. failure(err);
  10145. // failure
  10146. } else {
  10147. try {
  10148. findBoooksByAuthor(author, function(books, err) {
  10149. if (err) {
  10150. failure(err);
  10151. } else {
  10152. try {
  10153. foundBooks(books);
  10154. } catch(reason) {
  10155. failure(reason);
  10156. }
  10157. }
  10158. });
  10159. } catch(error) {
  10160. failure(err);
  10161. }
  10162. // success
  10163. }
  10164. });
  10165. ```
  10166. Promise Example;
  10167. ```javascript
  10168. findAuthor().
  10169. then(findBooksByAuthor).
  10170. then(function(books){
  10171. // found books
  10172. }).catch(function(reason){
  10173. // something went wrong
  10174. });
  10175. ```
  10176. @method then
  10177. @param {Function} onFulfilled
  10178. @param {Function} onRejected
  10179. Useful for tooling.
  10180. @return {Promise}
  10181. */
  10182. then: function(onFulfillment, onRejection) {
  10183. var parent = this;
  10184. var state = parent._state;
  10185. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  10186. return this;
  10187. }
  10188. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  10189. var result = parent._result;
  10190. if (state) {
  10191. var callback = arguments[state - 1];
  10192. lib$es6$promise$asap$$asap(function(){
  10193. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  10194. });
  10195. } else {
  10196. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  10197. }
  10198. return child;
  10199. },
  10200. /**
  10201. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  10202. as the catch block of a try/catch statement.
  10203. ```js
  10204. function findAuthor(){
  10205. throw new Error('couldn't find that author');
  10206. }
  10207. // synchronous
  10208. try {
  10209. findAuthor();
  10210. } catch(reason) {
  10211. // something went wrong
  10212. }
  10213. // async with promises
  10214. findAuthor().catch(function(reason){
  10215. // something went wrong
  10216. });
  10217. ```
  10218. @method catch
  10219. @param {Function} onRejection
  10220. Useful for tooling.
  10221. @return {Promise}
  10222. */
  10223. 'catch': function(onRejection) {
  10224. return this.then(null, onRejection);
  10225. }
  10226. };
  10227. function lib$es6$promise$polyfill$$polyfill() {
  10228. var local;
  10229. if (typeof global !== 'undefined') {
  10230. local = global;
  10231. } else if (typeof self !== 'undefined') {
  10232. local = self;
  10233. } else {
  10234. try {
  10235. local = Function('return this')();
  10236. } catch (e) {
  10237. throw new Error('polyfill failed because global object is unavailable in this environment');
  10238. }
  10239. }
  10240. var P = local.Promise;
  10241. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  10242. return;
  10243. }
  10244. local.Promise = lib$es6$promise$promise$$default;
  10245. }
  10246. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  10247. var lib$es6$promise$umd$$ES6Promise = {
  10248. 'Promise': lib$es6$promise$promise$$default,
  10249. 'polyfill': lib$es6$promise$polyfill$$default
  10250. };
  10251. /* global define:true module:true window: true */
  10252. if (typeof define === 'function' && define['amd']) {
  10253. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  10254. } else if (typeof module !== 'undefined' && module['exports']) {
  10255. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  10256. } else if (typeof this !== 'undefined') {
  10257. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  10258. }
  10259. lib$es6$promise$polyfill$$default();
  10260. }).call(this);
  10261. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  10262. },{"_process":78}],36:[function(require,module,exports){
  10263. // Top level file is just a mixin of submodules & constants
  10264. 'use strict';
  10265. var assign = require('./lib/utils/common').assign;
  10266. var deflate = require('./lib/deflate');
  10267. var inflate = require('./lib/inflate');
  10268. var constants = require('./lib/zlib/constants');
  10269. var pako = {};
  10270. assign(pako, deflate, inflate, constants);
  10271. module.exports = pako;
  10272. },{"./lib/deflate":37,"./lib/inflate":38,"./lib/utils/common":39,"./lib/zlib/constants":42}],37:[function(require,module,exports){
  10273. 'use strict';
  10274. var zlib_deflate = require('./zlib/deflate.js');
  10275. var utils = require('./utils/common');
  10276. var strings = require('./utils/strings');
  10277. var msg = require('./zlib/messages');
  10278. var zstream = require('./zlib/zstream');
  10279. var toString = Object.prototype.toString;
  10280. /* Public constants ==========================================================*/
  10281. /* ===========================================================================*/
  10282. var Z_NO_FLUSH = 0;
  10283. var Z_FINISH = 4;
  10284. var Z_OK = 0;
  10285. var Z_STREAM_END = 1;
  10286. var Z_SYNC_FLUSH = 2;
  10287. var Z_DEFAULT_COMPRESSION = -1;
  10288. var Z_DEFAULT_STRATEGY = 0;
  10289. var Z_DEFLATED = 8;
  10290. /* ===========================================================================*/
  10291. /**
  10292. * class Deflate
  10293. *
  10294. * Generic JS-style wrapper for zlib calls. If you don't need
  10295. * streaming behaviour - use more simple functions: [[deflate]],
  10296. * [[deflateRaw]] and [[gzip]].
  10297. **/
  10298. /* internal
  10299. * Deflate.chunks -> Array
  10300. *
  10301. * Chunks of output data, if [[Deflate#onData]] not overriden.
  10302. **/
  10303. /**
  10304. * Deflate.result -> Uint8Array|Array
  10305. *
  10306. * Compressed result, generated by default [[Deflate#onData]]
  10307. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  10308. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  10309. * push a chunk with explicit flush (call [[Deflate#push]] with
  10310. * `Z_SYNC_FLUSH` param).
  10311. **/
  10312. /**
  10313. * Deflate.err -> Number
  10314. *
  10315. * Error code after deflate finished. 0 (Z_OK) on success.
  10316. * You will not need it in real life, because deflate errors
  10317. * are possible only on wrong options or bad `onData` / `onEnd`
  10318. * custom handlers.
  10319. **/
  10320. /**
  10321. * Deflate.msg -> String
  10322. *
  10323. * Error message, if [[Deflate.err]] != 0
  10324. **/
  10325. /**
  10326. * new Deflate(options)
  10327. * - options (Object): zlib deflate options.
  10328. *
  10329. * Creates new deflator instance with specified params. Throws exception
  10330. * on bad params. Supported options:
  10331. *
  10332. * - `level`
  10333. * - `windowBits`
  10334. * - `memLevel`
  10335. * - `strategy`
  10336. *
  10337. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  10338. * for more information on these.
  10339. *
  10340. * Additional options, for internal needs:
  10341. *
  10342. * - `chunkSize` - size of generated data chunks (16K by default)
  10343. * - `raw` (Boolean) - do raw deflate
  10344. * - `gzip` (Boolean) - create gzip wrapper
  10345. * - `to` (String) - if equal to 'string', then result will be "binary string"
  10346. * (each char code [0..255])
  10347. * - `header` (Object) - custom header for gzip
  10348. * - `text` (Boolean) - true if compressed data believed to be text
  10349. * - `time` (Number) - modification time, unix timestamp
  10350. * - `os` (Number) - operation system code
  10351. * - `extra` (Array) - array of bytes with extra data (max 65536)
  10352. * - `name` (String) - file name (binary string)
  10353. * - `comment` (String) - comment (binary string)
  10354. * - `hcrc` (Boolean) - true if header crc should be added
  10355. *
  10356. * ##### Example:
  10357. *
  10358. * ```javascript
  10359. * var pako = require('pako')
  10360. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  10361. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  10362. *
  10363. * var deflate = new pako.Deflate({ level: 3});
  10364. *
  10365. * deflate.push(chunk1, false);
  10366. * deflate.push(chunk2, true); // true -> last chunk
  10367. *
  10368. * if (deflate.err) { throw new Error(deflate.err); }
  10369. *
  10370. * console.log(deflate.result);
  10371. * ```
  10372. **/
  10373. var Deflate = function(options) {
  10374. this.options = utils.assign({
  10375. level: Z_DEFAULT_COMPRESSION,
  10376. method: Z_DEFLATED,
  10377. chunkSize: 16384,
  10378. windowBits: 15,
  10379. memLevel: 8,
  10380. strategy: Z_DEFAULT_STRATEGY,
  10381. to: ''
  10382. }, options || {});
  10383. var opt = this.options;
  10384. if (opt.raw && (opt.windowBits > 0)) {
  10385. opt.windowBits = -opt.windowBits;
  10386. }
  10387. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  10388. opt.windowBits += 16;
  10389. }
  10390. this.err = 0; // error code, if happens (0 = Z_OK)
  10391. this.msg = ''; // error message
  10392. this.ended = false; // used to avoid multiple onEnd() calls
  10393. this.chunks = []; // chunks of compressed data
  10394. this.strm = new zstream();
  10395. this.strm.avail_out = 0;
  10396. var status = zlib_deflate.deflateInit2(
  10397. this.strm,
  10398. opt.level,
  10399. opt.method,
  10400. opt.windowBits,
  10401. opt.memLevel,
  10402. opt.strategy
  10403. );
  10404. if (status !== Z_OK) {
  10405. throw new Error(msg[status]);
  10406. }
  10407. if (opt.header) {
  10408. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  10409. }
  10410. };
  10411. /**
  10412. * Deflate#push(data[, mode]) -> Boolean
  10413. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  10414. * converted to utf8 byte sequence.
  10415. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  10416. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  10417. *
  10418. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  10419. * new compressed chunks. Returns `true` on success. The last data block must have
  10420. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  10421. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  10422. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  10423. *
  10424. * On fail call [[Deflate#onEnd]] with error code and return false.
  10425. *
  10426. * We strongly recommend to use `Uint8Array` on input for best speed (output
  10427. * array format is detected automatically). Also, don't skip last param and always
  10428. * use the same type in your code (boolean or number). That will improve JS speed.
  10429. *
  10430. * For regular `Array`-s make sure all elements are [0..255].
  10431. *
  10432. * ##### Example
  10433. *
  10434. * ```javascript
  10435. * push(chunk, false); // push one of data chunks
  10436. * ...
  10437. * push(chunk, true); // push last chunk
  10438. * ```
  10439. **/
  10440. Deflate.prototype.push = function(data, mode) {
  10441. var strm = this.strm;
  10442. var chunkSize = this.options.chunkSize;
  10443. var status, _mode;
  10444. if (this.ended) { return false; }
  10445. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  10446. // Convert data if needed
  10447. if (typeof data === 'string') {
  10448. // If we need to compress text, change encoding to utf8.
  10449. strm.input = strings.string2buf(data);
  10450. } else if (toString.call(data) === '[object ArrayBuffer]') {
  10451. strm.input = new Uint8Array(data);
  10452. } else {
  10453. strm.input = data;
  10454. }
  10455. strm.next_in = 0;
  10456. strm.avail_in = strm.input.length;
  10457. do {
  10458. if (strm.avail_out === 0) {
  10459. strm.output = new utils.Buf8(chunkSize);
  10460. strm.next_out = 0;
  10461. strm.avail_out = chunkSize;
  10462. }
  10463. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  10464. if (status !== Z_STREAM_END && status !== Z_OK) {
  10465. this.onEnd(status);
  10466. this.ended = true;
  10467. return false;
  10468. }
  10469. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  10470. if (this.options.to === 'string') {
  10471. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  10472. } else {
  10473. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  10474. }
  10475. }
  10476. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  10477. // Finalize on the last chunk.
  10478. if (_mode === Z_FINISH) {
  10479. status = zlib_deflate.deflateEnd(this.strm);
  10480. this.onEnd(status);
  10481. this.ended = true;
  10482. return status === Z_OK;
  10483. }
  10484. // callback interim results if Z_SYNC_FLUSH.
  10485. if (_mode === Z_SYNC_FLUSH) {
  10486. this.onEnd(Z_OK);
  10487. strm.avail_out = 0;
  10488. return true;
  10489. }
  10490. return true;
  10491. };
  10492. /**
  10493. * Deflate#onData(chunk) -> Void
  10494. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  10495. * on js engine support. When string output requested, each chunk
  10496. * will be string.
  10497. *
  10498. * By default, stores data blocks in `chunks[]` property and glue
  10499. * those in `onEnd`. Override this handler, if you need another behaviour.
  10500. **/
  10501. Deflate.prototype.onData = function(chunk) {
  10502. this.chunks.push(chunk);
  10503. };
  10504. /**
  10505. * Deflate#onEnd(status) -> Void
  10506. * - status (Number): deflate status. 0 (Z_OK) on success,
  10507. * other if not.
  10508. *
  10509. * Called once after you tell deflate that the input stream is
  10510. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  10511. * or if an error happened. By default - join collected chunks,
  10512. * free memory and fill `results` / `err` properties.
  10513. **/
  10514. Deflate.prototype.onEnd = function(status) {
  10515. // On success - join
  10516. if (status === Z_OK) {
  10517. if (this.options.to === 'string') {
  10518. this.result = this.chunks.join('');
  10519. } else {
  10520. this.result = utils.flattenChunks(this.chunks);
  10521. }
  10522. }
  10523. this.chunks = [];
  10524. this.err = status;
  10525. this.msg = this.strm.msg;
  10526. };
  10527. /**
  10528. * deflate(data[, options]) -> Uint8Array|Array|String
  10529. * - data (Uint8Array|Array|String): input data to compress.
  10530. * - options (Object): zlib deflate options.
  10531. *
  10532. * Compress `data` with deflate alrorythm and `options`.
  10533. *
  10534. * Supported options are:
  10535. *
  10536. * - level
  10537. * - windowBits
  10538. * - memLevel
  10539. * - strategy
  10540. *
  10541. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  10542. * for more information on these.
  10543. *
  10544. * Sugar (options):
  10545. *
  10546. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  10547. * negative windowBits implicitly.
  10548. * - `to` (String) - if equal to 'string', then result will be "binary string"
  10549. * (each char code [0..255])
  10550. *
  10551. * ##### Example:
  10552. *
  10553. * ```javascript
  10554. * var pako = require('pako')
  10555. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  10556. *
  10557. * console.log(pako.deflate(data));
  10558. * ```
  10559. **/
  10560. function deflate(input, options) {
  10561. var deflator = new Deflate(options);
  10562. deflator.push(input, true);
  10563. // That will never happens, if you don't cheat with options :)
  10564. if (deflator.err) { throw deflator.msg; }
  10565. return deflator.result;
  10566. }
  10567. /**
  10568. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  10569. * - data (Uint8Array|Array|String): input data to compress.
  10570. * - options (Object): zlib deflate options.
  10571. *
  10572. * The same as [[deflate]], but creates raw data, without wrapper
  10573. * (header and adler32 crc).
  10574. **/
  10575. function deflateRaw(input, options) {
  10576. options = options || {};
  10577. options.raw = true;
  10578. return deflate(input, options);
  10579. }
  10580. /**
  10581. * gzip(data[, options]) -> Uint8Array|Array|String
  10582. * - data (Uint8Array|Array|String): input data to compress.
  10583. * - options (Object): zlib deflate options.
  10584. *
  10585. * The same as [[deflate]], but create gzip wrapper instead of
  10586. * deflate one.
  10587. **/
  10588. function gzip(input, options) {
  10589. options = options || {};
  10590. options.gzip = true;
  10591. return deflate(input, options);
  10592. }
  10593. exports.Deflate = Deflate;
  10594. exports.deflate = deflate;
  10595. exports.deflateRaw = deflateRaw;
  10596. exports.gzip = gzip;
  10597. },{"./utils/common":39,"./utils/strings":40,"./zlib/deflate.js":44,"./zlib/messages":49,"./zlib/zstream":51}],38:[function(require,module,exports){
  10598. 'use strict';
  10599. var zlib_inflate = require('./zlib/inflate.js');
  10600. var utils = require('./utils/common');
  10601. var strings = require('./utils/strings');
  10602. var c = require('./zlib/constants');
  10603. var msg = require('./zlib/messages');
  10604. var zstream = require('./zlib/zstream');
  10605. var gzheader = require('./zlib/gzheader');
  10606. var toString = Object.prototype.toString;
  10607. /**
  10608. * class Inflate
  10609. *
  10610. * Generic JS-style wrapper for zlib calls. If you don't need
  10611. * streaming behaviour - use more simple functions: [[inflate]]
  10612. * and [[inflateRaw]].
  10613. **/
  10614. /* internal
  10615. * inflate.chunks -> Array
  10616. *
  10617. * Chunks of output data, if [[Inflate#onData]] not overriden.
  10618. **/
  10619. /**
  10620. * Inflate.result -> Uint8Array|Array|String
  10621. *
  10622. * Uncompressed result, generated by default [[Inflate#onData]]
  10623. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  10624. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  10625. * push a chunk with explicit flush (call [[Inflate#push]] with
  10626. * `Z_SYNC_FLUSH` param).
  10627. **/
  10628. /**
  10629. * Inflate.err -> Number
  10630. *
  10631. * Error code after inflate finished. 0 (Z_OK) on success.
  10632. * Should be checked if broken data possible.
  10633. **/
  10634. /**
  10635. * Inflate.msg -> String
  10636. *
  10637. * Error message, if [[Inflate.err]] != 0
  10638. **/
  10639. /**
  10640. * new Inflate(options)
  10641. * - options (Object): zlib inflate options.
  10642. *
  10643. * Creates new inflator instance with specified params. Throws exception
  10644. * on bad params. Supported options:
  10645. *
  10646. * - `windowBits`
  10647. *
  10648. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  10649. * for more information on these.
  10650. *
  10651. * Additional options, for internal needs:
  10652. *
  10653. * - `chunkSize` - size of generated data chunks (16K by default)
  10654. * - `raw` (Boolean) - do raw inflate
  10655. * - `to` (String) - if equal to 'string', then result will be converted
  10656. * from utf8 to utf16 (javascript) string. When string output requested,
  10657. * chunk length can differ from `chunkSize`, depending on content.
  10658. *
  10659. * By default, when no options set, autodetect deflate/gzip data format via
  10660. * wrapper header.
  10661. *
  10662. * ##### Example:
  10663. *
  10664. * ```javascript
  10665. * var pako = require('pako')
  10666. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  10667. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  10668. *
  10669. * var inflate = new pako.Inflate({ level: 3});
  10670. *
  10671. * inflate.push(chunk1, false);
  10672. * inflate.push(chunk2, true); // true -> last chunk
  10673. *
  10674. * if (inflate.err) { throw new Error(inflate.err); }
  10675. *
  10676. * console.log(inflate.result);
  10677. * ```
  10678. **/
  10679. var Inflate = function(options) {
  10680. this.options = utils.assign({
  10681. chunkSize: 16384,
  10682. windowBits: 0,
  10683. to: ''
  10684. }, options || {});
  10685. var opt = this.options;
  10686. // Force window size for `raw` data, if not set directly,
  10687. // because we have no header for autodetect.
  10688. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  10689. opt.windowBits = -opt.windowBits;
  10690. if (opt.windowBits === 0) { opt.windowBits = -15; }
  10691. }
  10692. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  10693. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  10694. !(options && options.windowBits)) {
  10695. opt.windowBits += 32;
  10696. }
  10697. // Gzip header has no info about windows size, we can do autodetect only
  10698. // for deflate. So, if window size not set, force it to max when gzip possible
  10699. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  10700. // bit 3 (16) -> gzipped data
  10701. // bit 4 (32) -> autodetect gzip/deflate
  10702. if ((opt.windowBits & 15) === 0) {
  10703. opt.windowBits |= 15;
  10704. }
  10705. }
  10706. this.err = 0; // error code, if happens (0 = Z_OK)
  10707. this.msg = ''; // error message
  10708. this.ended = false; // used to avoid multiple onEnd() calls
  10709. this.chunks = []; // chunks of compressed data
  10710. this.strm = new zstream();
  10711. this.strm.avail_out = 0;
  10712. var status = zlib_inflate.inflateInit2(
  10713. this.strm,
  10714. opt.windowBits
  10715. );
  10716. if (status !== c.Z_OK) {
  10717. throw new Error(msg[status]);
  10718. }
  10719. this.header = new gzheader();
  10720. zlib_inflate.inflateGetHeader(this.strm, this.header);
  10721. };
  10722. /**
  10723. * Inflate#push(data[, mode]) -> Boolean
  10724. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  10725. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  10726. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  10727. *
  10728. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  10729. * new output chunks. Returns `true` on success. The last data block must have
  10730. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  10731. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  10732. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  10733. *
  10734. * On fail call [[Inflate#onEnd]] with error code and return false.
  10735. *
  10736. * We strongly recommend to use `Uint8Array` on input for best speed (output
  10737. * format is detected automatically). Also, don't skip last param and always
  10738. * use the same type in your code (boolean or number). That will improve JS speed.
  10739. *
  10740. * For regular `Array`-s make sure all elements are [0..255].
  10741. *
  10742. * ##### Example
  10743. *
  10744. * ```javascript
  10745. * push(chunk, false); // push one of data chunks
  10746. * ...
  10747. * push(chunk, true); // push last chunk
  10748. * ```
  10749. **/
  10750. Inflate.prototype.push = function(data, mode) {
  10751. var strm = this.strm;
  10752. var chunkSize = this.options.chunkSize;
  10753. var status, _mode;
  10754. var next_out_utf8, tail, utf8str;
  10755. if (this.ended) { return false; }
  10756. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  10757. // Convert data if needed
  10758. if (typeof data === 'string') {
  10759. // Only binary strings can be decompressed on practice
  10760. strm.input = strings.binstring2buf(data);
  10761. } else if (toString.call(data) === '[object ArrayBuffer]') {
  10762. strm.input = new Uint8Array(data);
  10763. } else {
  10764. strm.input = data;
  10765. }
  10766. strm.next_in = 0;
  10767. strm.avail_in = strm.input.length;
  10768. do {
  10769. if (strm.avail_out === 0) {
  10770. strm.output = new utils.Buf8(chunkSize);
  10771. strm.next_out = 0;
  10772. strm.avail_out = chunkSize;
  10773. }
  10774. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  10775. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  10776. this.onEnd(status);
  10777. this.ended = true;
  10778. return false;
  10779. }
  10780. if (strm.next_out) {
  10781. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  10782. if (this.options.to === 'string') {
  10783. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  10784. tail = strm.next_out - next_out_utf8;
  10785. utf8str = strings.buf2string(strm.output, next_out_utf8);
  10786. // move tail
  10787. strm.next_out = tail;
  10788. strm.avail_out = chunkSize - tail;
  10789. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  10790. this.onData(utf8str);
  10791. } else {
  10792. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  10793. }
  10794. }
  10795. }
  10796. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  10797. if (status === c.Z_STREAM_END) {
  10798. _mode = c.Z_FINISH;
  10799. }
  10800. // Finalize on the last chunk.
  10801. if (_mode === c.Z_FINISH) {
  10802. status = zlib_inflate.inflateEnd(this.strm);
  10803. this.onEnd(status);
  10804. this.ended = true;
  10805. return status === c.Z_OK;
  10806. }
  10807. // callback interim results if Z_SYNC_FLUSH.
  10808. if (_mode === c.Z_SYNC_FLUSH) {
  10809. this.onEnd(c.Z_OK);
  10810. strm.avail_out = 0;
  10811. return true;
  10812. }
  10813. return true;
  10814. };
  10815. /**
  10816. * Inflate#onData(chunk) -> Void
  10817. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  10818. * on js engine support. When string output requested, each chunk
  10819. * will be string.
  10820. *
  10821. * By default, stores data blocks in `chunks[]` property and glue
  10822. * those in `onEnd`. Override this handler, if you need another behaviour.
  10823. **/
  10824. Inflate.prototype.onData = function(chunk) {
  10825. this.chunks.push(chunk);
  10826. };
  10827. /**
  10828. * Inflate#onEnd(status) -> Void
  10829. * - status (Number): inflate status. 0 (Z_OK) on success,
  10830. * other if not.
  10831. *
  10832. * Called either after you tell inflate that the input stream is
  10833. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  10834. * or if an error happened. By default - join collected chunks,
  10835. * free memory and fill `results` / `err` properties.
  10836. **/
  10837. Inflate.prototype.onEnd = function(status) {
  10838. // On success - join
  10839. if (status === c.Z_OK) {
  10840. if (this.options.to === 'string') {
  10841. // Glue & convert here, until we teach pako to send
  10842. // utf8 alligned strings to onData
  10843. this.result = this.chunks.join('');
  10844. } else {
  10845. this.result = utils.flattenChunks(this.chunks);
  10846. }
  10847. }
  10848. this.chunks = [];
  10849. this.err = status;
  10850. this.msg = this.strm.msg;
  10851. };
  10852. /**
  10853. * inflate(data[, options]) -> Uint8Array|Array|String
  10854. * - data (Uint8Array|Array|String): input data to decompress.
  10855. * - options (Object): zlib inflate options.
  10856. *
  10857. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  10858. * format via wrapper header by default. That's why we don't provide
  10859. * separate `ungzip` method.
  10860. *
  10861. * Supported options are:
  10862. *
  10863. * - windowBits
  10864. *
  10865. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  10866. * for more information.
  10867. *
  10868. * Sugar (options):
  10869. *
  10870. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  10871. * negative windowBits implicitly.
  10872. * - `to` (String) - if equal to 'string', then result will be converted
  10873. * from utf8 to utf16 (javascript) string. When string output requested,
  10874. * chunk length can differ from `chunkSize`, depending on content.
  10875. *
  10876. *
  10877. * ##### Example:
  10878. *
  10879. * ```javascript
  10880. * var pako = require('pako')
  10881. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  10882. * , output;
  10883. *
  10884. * try {
  10885. * output = pako.inflate(input);
  10886. * } catch (err)
  10887. * console.log(err);
  10888. * }
  10889. * ```
  10890. **/
  10891. function inflate(input, options) {
  10892. var inflator = new Inflate(options);
  10893. inflator.push(input, true);
  10894. // That will never happens, if you don't cheat with options :)
  10895. if (inflator.err) { throw inflator.msg; }
  10896. return inflator.result;
  10897. }
  10898. /**
  10899. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  10900. * - data (Uint8Array|Array|String): input data to decompress.
  10901. * - options (Object): zlib inflate options.
  10902. *
  10903. * The same as [[inflate]], but creates raw data, without wrapper
  10904. * (header and adler32 crc).
  10905. **/
  10906. function inflateRaw(input, options) {
  10907. options = options || {};
  10908. options.raw = true;
  10909. return inflate(input, options);
  10910. }
  10911. /**
  10912. * ungzip(data[, options]) -> Uint8Array|Array|String
  10913. * - data (Uint8Array|Array|String): input data to decompress.
  10914. * - options (Object): zlib inflate options.
  10915. *
  10916. * Just shortcut to [[inflate]], because it autodetects format
  10917. * by header.content. Done for convenience.
  10918. **/
  10919. exports.Inflate = Inflate;
  10920. exports.inflate = inflate;
  10921. exports.inflateRaw = inflateRaw;
  10922. exports.ungzip = inflate;
  10923. },{"./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){
  10924. 'use strict';
  10925. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  10926. (typeof Uint16Array !== 'undefined') &&
  10927. (typeof Int32Array !== 'undefined');
  10928. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  10929. var sources = Array.prototype.slice.call(arguments, 1);
  10930. while (sources.length) {
  10931. var source = sources.shift();
  10932. if (!source) { continue; }
  10933. if (typeof source !== 'object') {
  10934. throw new TypeError(source + 'must be non-object');
  10935. }
  10936. for (var p in source) {
  10937. if (source.hasOwnProperty(p)) {
  10938. obj[p] = source[p];
  10939. }
  10940. }
  10941. }
  10942. return obj;
  10943. };
  10944. // reduce buffer size, avoiding mem copy
  10945. exports.shrinkBuf = function (buf, size) {
  10946. if (buf.length === size) { return buf; }
  10947. if (buf.subarray) { return buf.subarray(0, size); }
  10948. buf.length = size;
  10949. return buf;
  10950. };
  10951. var fnTyped = {
  10952. arraySet: function (dest, src, src_offs, len, dest_offs) {
  10953. if (src.subarray && dest.subarray) {
  10954. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  10955. return;
  10956. }
  10957. // Fallback to ordinary array
  10958. for (var i=0; i<len; i++) {
  10959. dest[dest_offs + i] = src[src_offs + i];
  10960. }
  10961. },
  10962. // Join array of chunks to single array.
  10963. flattenChunks: function(chunks) {
  10964. var i, l, len, pos, chunk, result;
  10965. // calculate data length
  10966. len = 0;
  10967. for (i=0, l=chunks.length; i<l; i++) {
  10968. len += chunks[i].length;
  10969. }
  10970. // join chunks
  10971. result = new Uint8Array(len);
  10972. pos = 0;
  10973. for (i=0, l=chunks.length; i<l; i++) {
  10974. chunk = chunks[i];
  10975. result.set(chunk, pos);
  10976. pos += chunk.length;
  10977. }
  10978. return result;
  10979. }
  10980. };
  10981. var fnUntyped = {
  10982. arraySet: function (dest, src, src_offs, len, dest_offs) {
  10983. for (var i=0; i<len; i++) {
  10984. dest[dest_offs + i] = src[src_offs + i];
  10985. }
  10986. },
  10987. // Join array of chunks to single array.
  10988. flattenChunks: function(chunks) {
  10989. return [].concat.apply([], chunks);
  10990. }
  10991. };
  10992. // Enable/Disable typed arrays use, for testing
  10993. //
  10994. exports.setTyped = function (on) {
  10995. if (on) {
  10996. exports.Buf8 = Uint8Array;
  10997. exports.Buf16 = Uint16Array;
  10998. exports.Buf32 = Int32Array;
  10999. exports.assign(exports, fnTyped);
  11000. } else {
  11001. exports.Buf8 = Array;
  11002. exports.Buf16 = Array;
  11003. exports.Buf32 = Array;
  11004. exports.assign(exports, fnUntyped);
  11005. }
  11006. };
  11007. exports.setTyped(TYPED_OK);
  11008. },{}],40:[function(require,module,exports){
  11009. // String encode/decode helpers
  11010. 'use strict';
  11011. var utils = require('./common');
  11012. // Quick check if we can use fast array to bin string conversion
  11013. //
  11014. // - apply(Array) can fail on Android 2.2
  11015. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  11016. //
  11017. var STR_APPLY_OK = true;
  11018. var STR_APPLY_UIA_OK = true;
  11019. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  11020. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  11021. // Table with utf8 lengths (calculated by first byte of sequence)
  11022. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  11023. // because max possible codepoint is 0x10ffff
  11024. var _utf8len = new utils.Buf8(256);
  11025. for (var q=0; q<256; q++) {
  11026. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  11027. }
  11028. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  11029. // convert string to array (typed, when possible)
  11030. exports.string2buf = function (str) {
  11031. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  11032. // count binary size
  11033. for (m_pos = 0; m_pos < str_len; m_pos++) {
  11034. c = str.charCodeAt(m_pos);
  11035. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  11036. c2 = str.charCodeAt(m_pos+1);
  11037. if ((c2 & 0xfc00) === 0xdc00) {
  11038. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  11039. m_pos++;
  11040. }
  11041. }
  11042. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  11043. }
  11044. // allocate buffer
  11045. buf = new utils.Buf8(buf_len);
  11046. // convert
  11047. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  11048. c = str.charCodeAt(m_pos);
  11049. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  11050. c2 = str.charCodeAt(m_pos+1);
  11051. if ((c2 & 0xfc00) === 0xdc00) {
  11052. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  11053. m_pos++;
  11054. }
  11055. }
  11056. if (c < 0x80) {
  11057. /* one byte */
  11058. buf[i++] = c;
  11059. } else if (c < 0x800) {
  11060. /* two bytes */
  11061. buf[i++] = 0xC0 | (c >>> 6);
  11062. buf[i++] = 0x80 | (c & 0x3f);
  11063. } else if (c < 0x10000) {
  11064. /* three bytes */
  11065. buf[i++] = 0xE0 | (c >>> 12);
  11066. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  11067. buf[i++] = 0x80 | (c & 0x3f);
  11068. } else {
  11069. /* four bytes */
  11070. buf[i++] = 0xf0 | (c >>> 18);
  11071. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  11072. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  11073. buf[i++] = 0x80 | (c & 0x3f);
  11074. }
  11075. }
  11076. return buf;
  11077. };
  11078. // Helper (used in 2 places)
  11079. function buf2binstring(buf, len) {
  11080. // use fallback for big arrays to avoid stack overflow
  11081. if (len < 65537) {
  11082. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  11083. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  11084. }
  11085. }
  11086. var result = '';
  11087. for (var i=0; i < len; i++) {
  11088. result += String.fromCharCode(buf[i]);
  11089. }
  11090. return result;
  11091. }
  11092. // Convert byte array to binary string
  11093. exports.buf2binstring = function(buf) {
  11094. return buf2binstring(buf, buf.length);
  11095. };
  11096. // Convert binary string (typed, when possible)
  11097. exports.binstring2buf = function(str) {
  11098. var buf = new utils.Buf8(str.length);
  11099. for (var i=0, len=buf.length; i < len; i++) {
  11100. buf[i] = str.charCodeAt(i);
  11101. }
  11102. return buf;
  11103. };
  11104. // convert array to string
  11105. exports.buf2string = function (buf, max) {
  11106. var i, out, c, c_len;
  11107. var len = max || buf.length;
  11108. // Reserve max possible length (2 words per char)
  11109. // NB: by unknown reasons, Array is significantly faster for
  11110. // String.fromCharCode.apply than Uint16Array.
  11111. var utf16buf = new Array(len*2);
  11112. for (out=0, i=0; i<len;) {
  11113. c = buf[i++];
  11114. // quick process ascii
  11115. if (c < 0x80) { utf16buf[out++] = c; continue; }
  11116. c_len = _utf8len[c];
  11117. // skip 5 & 6 byte codes
  11118. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  11119. // apply mask on first byte
  11120. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  11121. // join the rest
  11122. while (c_len > 1 && i < len) {
  11123. c = (c << 6) | (buf[i++] & 0x3f);
  11124. c_len--;
  11125. }
  11126. // terminated by end of string?
  11127. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  11128. if (c < 0x10000) {
  11129. utf16buf[out++] = c;
  11130. } else {
  11131. c -= 0x10000;
  11132. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  11133. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  11134. }
  11135. }
  11136. return buf2binstring(utf16buf, out);
  11137. };
  11138. // Calculate max possible position in utf8 buffer,
  11139. // that will not break sequence. If that's not possible
  11140. // - (very small limits) return max size as is.
  11141. //
  11142. // buf[] - utf8 bytes array
  11143. // max - length limit (mandatory);
  11144. exports.utf8border = function(buf, max) {
  11145. var pos;
  11146. max = max || buf.length;
  11147. if (max > buf.length) { max = buf.length; }
  11148. // go back from last position, until start of sequence found
  11149. pos = max-1;
  11150. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  11151. // Fuckup - very small and broken sequence,
  11152. // return max, because we should return something anyway.
  11153. if (pos < 0) { return max; }
  11154. // If we came to start of buffer - that means vuffer is too small,
  11155. // return max too.
  11156. if (pos === 0) { return max; }
  11157. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  11158. };
  11159. },{"./common":39}],41:[function(require,module,exports){
  11160. 'use strict';
  11161. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  11162. // It doesn't worth to make additional optimizationa as in original.
  11163. // Small size is preferable.
  11164. function adler32(adler, buf, len, pos) {
  11165. var s1 = (adler & 0xffff) |0,
  11166. s2 = ((adler >>> 16) & 0xffff) |0,
  11167. n = 0;
  11168. while (len !== 0) {
  11169. // Set limit ~ twice less than 5552, to keep
  11170. // s2 in 31-bits, because we force signed ints.
  11171. // in other case %= will fail.
  11172. n = len > 2000 ? 2000 : len;
  11173. len -= n;
  11174. do {
  11175. s1 = (s1 + buf[pos++]) |0;
  11176. s2 = (s2 + s1) |0;
  11177. } while (--n);
  11178. s1 %= 65521;
  11179. s2 %= 65521;
  11180. }
  11181. return (s1 | (s2 << 16)) |0;
  11182. }
  11183. module.exports = adler32;
  11184. },{}],42:[function(require,module,exports){
  11185. module.exports = {
  11186. /* Allowed flush values; see deflate() and inflate() below for details */
  11187. Z_NO_FLUSH: 0,
  11188. Z_PARTIAL_FLUSH: 1,
  11189. Z_SYNC_FLUSH: 2,
  11190. Z_FULL_FLUSH: 3,
  11191. Z_FINISH: 4,
  11192. Z_BLOCK: 5,
  11193. Z_TREES: 6,
  11194. /* Return codes for the compression/decompression functions. Negative values
  11195. * are errors, positive values are used for special but normal events.
  11196. */
  11197. Z_OK: 0,
  11198. Z_STREAM_END: 1,
  11199. Z_NEED_DICT: 2,
  11200. Z_ERRNO: -1,
  11201. Z_STREAM_ERROR: -2,
  11202. Z_DATA_ERROR: -3,
  11203. //Z_MEM_ERROR: -4,
  11204. Z_BUF_ERROR: -5,
  11205. //Z_VERSION_ERROR: -6,
  11206. /* compression levels */
  11207. Z_NO_COMPRESSION: 0,
  11208. Z_BEST_SPEED: 1,
  11209. Z_BEST_COMPRESSION: 9,
  11210. Z_DEFAULT_COMPRESSION: -1,
  11211. Z_FILTERED: 1,
  11212. Z_HUFFMAN_ONLY: 2,
  11213. Z_RLE: 3,
  11214. Z_FIXED: 4,
  11215. Z_DEFAULT_STRATEGY: 0,
  11216. /* Possible values of the data_type field (though see inflate()) */
  11217. Z_BINARY: 0,
  11218. Z_TEXT: 1,
  11219. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  11220. Z_UNKNOWN: 2,
  11221. /* The deflate compression method */
  11222. Z_DEFLATED: 8
  11223. //Z_NULL: null // Use -1 or null inline, depending on var type
  11224. };
  11225. },{}],43:[function(require,module,exports){
  11226. 'use strict';
  11227. // Note: we can't get significant speed boost here.
  11228. // So write code to minimize size - no pregenerated tables
  11229. // and array tools dependencies.
  11230. // Use ordinary array, since untyped makes no boost here
  11231. function makeTable() {
  11232. var c, table = [];
  11233. for (var n =0; n < 256; n++) {
  11234. c = n;
  11235. for (var k =0; k < 8; k++) {
  11236. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  11237. }
  11238. table[n] = c;
  11239. }
  11240. return table;
  11241. }
  11242. // Create table on load. Just 255 signed longs. Not a problem.
  11243. var crcTable = makeTable();
  11244. function crc32(crc, buf, len, pos) {
  11245. var t = crcTable,
  11246. end = pos + len;
  11247. crc = crc ^ (-1);
  11248. for (var i = pos; i < end; i++) {
  11249. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  11250. }
  11251. return (crc ^ (-1)); // >>> 0;
  11252. }
  11253. module.exports = crc32;
  11254. },{}],44:[function(require,module,exports){
  11255. 'use strict';
  11256. var utils = require('../utils/common');
  11257. var trees = require('./trees');
  11258. var adler32 = require('./adler32');
  11259. var crc32 = require('./crc32');
  11260. var msg = require('./messages');
  11261. /* Public constants ==========================================================*/
  11262. /* ===========================================================================*/
  11263. /* Allowed flush values; see deflate() and inflate() below for details */
  11264. var Z_NO_FLUSH = 0;
  11265. var Z_PARTIAL_FLUSH = 1;
  11266. //var Z_SYNC_FLUSH = 2;
  11267. var Z_FULL_FLUSH = 3;
  11268. var Z_FINISH = 4;
  11269. var Z_BLOCK = 5;
  11270. //var Z_TREES = 6;
  11271. /* Return codes for the compression/decompression functions. Negative values
  11272. * are errors, positive values are used for special but normal events.
  11273. */
  11274. var Z_OK = 0;
  11275. var Z_STREAM_END = 1;
  11276. //var Z_NEED_DICT = 2;
  11277. //var Z_ERRNO = -1;
  11278. var Z_STREAM_ERROR = -2;
  11279. var Z_DATA_ERROR = -3;
  11280. //var Z_MEM_ERROR = -4;
  11281. var Z_BUF_ERROR = -5;
  11282. //var Z_VERSION_ERROR = -6;
  11283. /* compression levels */
  11284. //var Z_NO_COMPRESSION = 0;
  11285. //var Z_BEST_SPEED = 1;
  11286. //var Z_BEST_COMPRESSION = 9;
  11287. var Z_DEFAULT_COMPRESSION = -1;
  11288. var Z_FILTERED = 1;
  11289. var Z_HUFFMAN_ONLY = 2;
  11290. var Z_RLE = 3;
  11291. var Z_FIXED = 4;
  11292. var Z_DEFAULT_STRATEGY = 0;
  11293. /* Possible values of the data_type field (though see inflate()) */
  11294. //var Z_BINARY = 0;
  11295. //var Z_TEXT = 1;
  11296. //var Z_ASCII = 1; // = Z_TEXT
  11297. var Z_UNKNOWN = 2;
  11298. /* The deflate compression method */
  11299. var Z_DEFLATED = 8;
  11300. /*============================================================================*/
  11301. var MAX_MEM_LEVEL = 9;
  11302. /* Maximum value for memLevel in deflateInit2 */
  11303. var MAX_WBITS = 15;
  11304. /* 32K LZ77 window */
  11305. var DEF_MEM_LEVEL = 8;
  11306. var LENGTH_CODES = 29;
  11307. /* number of length codes, not counting the special END_BLOCK code */
  11308. var LITERALS = 256;
  11309. /* number of literal bytes 0..255 */
  11310. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  11311. /* number of Literal or Length codes, including the END_BLOCK code */
  11312. var D_CODES = 30;
  11313. /* number of distance codes */
  11314. var BL_CODES = 19;
  11315. /* number of codes used to transfer the bit lengths */
  11316. var HEAP_SIZE = 2*L_CODES + 1;
  11317. /* maximum heap size */
  11318. var MAX_BITS = 15;
  11319. /* All codes must not exceed MAX_BITS bits */
  11320. var MIN_MATCH = 3;
  11321. var MAX_MATCH = 258;
  11322. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  11323. var PRESET_DICT = 0x20;
  11324. var INIT_STATE = 42;
  11325. var EXTRA_STATE = 69;
  11326. var NAME_STATE = 73;
  11327. var COMMENT_STATE = 91;
  11328. var HCRC_STATE = 103;
  11329. var BUSY_STATE = 113;
  11330. var FINISH_STATE = 666;
  11331. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  11332. var BS_BLOCK_DONE = 2; /* block flush performed */
  11333. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  11334. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  11335. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  11336. function err(strm, errorCode) {
  11337. strm.msg = msg[errorCode];
  11338. return errorCode;
  11339. }
  11340. function rank(f) {
  11341. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  11342. }
  11343. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  11344. /* =========================================================================
  11345. * Flush as much pending output as possible. All deflate() output goes
  11346. * through this function so some applications may wish to modify it
  11347. * to avoid allocating a large strm->output buffer and copying into it.
  11348. * (See also read_buf()).
  11349. */
  11350. function flush_pending(strm) {
  11351. var s = strm.state;
  11352. //_tr_flush_bits(s);
  11353. var len = s.pending;
  11354. if (len > strm.avail_out) {
  11355. len = strm.avail_out;
  11356. }
  11357. if (len === 0) { return; }
  11358. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  11359. strm.next_out += len;
  11360. s.pending_out += len;
  11361. strm.total_out += len;
  11362. strm.avail_out -= len;
  11363. s.pending -= len;
  11364. if (s.pending === 0) {
  11365. s.pending_out = 0;
  11366. }
  11367. }
  11368. function flush_block_only (s, last) {
  11369. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  11370. s.block_start = s.strstart;
  11371. flush_pending(s.strm);
  11372. }
  11373. function put_byte(s, b) {
  11374. s.pending_buf[s.pending++] = b;
  11375. }
  11376. /* =========================================================================
  11377. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  11378. * IN assertion: the stream state is correct and there is enough room in
  11379. * pending_buf.
  11380. */
  11381. function putShortMSB(s, b) {
  11382. // put_byte(s, (Byte)(b >> 8));
  11383. // put_byte(s, (Byte)(b & 0xff));
  11384. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  11385. s.pending_buf[s.pending++] = b & 0xff;
  11386. }
  11387. /* ===========================================================================
  11388. * Read a new buffer from the current input stream, update the adler32
  11389. * and total number of bytes read. All deflate() input goes through
  11390. * this function so some applications may wish to modify it to avoid
  11391. * allocating a large strm->input buffer and copying from it.
  11392. * (See also flush_pending()).
  11393. */
  11394. function read_buf(strm, buf, start, size) {
  11395. var len = strm.avail_in;
  11396. if (len > size) { len = size; }
  11397. if (len === 0) { return 0; }
  11398. strm.avail_in -= len;
  11399. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  11400. if (strm.state.wrap === 1) {
  11401. strm.adler = adler32(strm.adler, buf, len, start);
  11402. }
  11403. else if (strm.state.wrap === 2) {
  11404. strm.adler = crc32(strm.adler, buf, len, start);
  11405. }
  11406. strm.next_in += len;
  11407. strm.total_in += len;
  11408. return len;
  11409. }
  11410. /* ===========================================================================
  11411. * Set match_start to the longest match starting at the given string and
  11412. * return its length. Matches shorter or equal to prev_length are discarded,
  11413. * in which case the result is equal to prev_length and match_start is
  11414. * garbage.
  11415. * IN assertions: cur_match is the head of the hash chain for the current
  11416. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  11417. * OUT assertion: the match length is not greater than s->lookahead.
  11418. */
  11419. function longest_match(s, cur_match) {
  11420. var chain_length = s.max_chain_length; /* max hash chain length */
  11421. var scan = s.strstart; /* current string */
  11422. var match; /* matched string */
  11423. var len; /* length of current match */
  11424. var best_len = s.prev_length; /* best match length so far */
  11425. var nice_match = s.nice_match; /* stop if match long enough */
  11426. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  11427. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  11428. var _win = s.window; // shortcut
  11429. var wmask = s.w_mask;
  11430. var prev = s.prev;
  11431. /* Stop when cur_match becomes <= limit. To simplify the code,
  11432. * we prevent matches with the string of window index 0.
  11433. */
  11434. var strend = s.strstart + MAX_MATCH;
  11435. var scan_end1 = _win[scan + best_len - 1];
  11436. var scan_end = _win[scan + best_len];
  11437. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  11438. * It is easy to get rid of this optimization if necessary.
  11439. */
  11440. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  11441. /* Do not waste too much time if we already have a good match: */
  11442. if (s.prev_length >= s.good_match) {
  11443. chain_length >>= 2;
  11444. }
  11445. /* Do not look for matches beyond the end of the input. This is necessary
  11446. * to make deflate deterministic.
  11447. */
  11448. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  11449. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  11450. do {
  11451. // Assert(cur_match < s->strstart, "no future");
  11452. match = cur_match;
  11453. /* Skip to next match if the match length cannot increase
  11454. * or if the match length is less than 2. Note that the checks below
  11455. * for insufficient lookahead only occur occasionally for performance
  11456. * reasons. Therefore uninitialized memory will be accessed, and
  11457. * conditional jumps will be made that depend on those values.
  11458. * However the length of the match is limited to the lookahead, so
  11459. * the output of deflate is not affected by the uninitialized values.
  11460. */
  11461. if (_win[match + best_len] !== scan_end ||
  11462. _win[match + best_len - 1] !== scan_end1 ||
  11463. _win[match] !== _win[scan] ||
  11464. _win[++match] !== _win[scan + 1]) {
  11465. continue;
  11466. }
  11467. /* The check at best_len-1 can be removed because it will be made
  11468. * again later. (This heuristic is not always a win.)
  11469. * It is not necessary to compare scan[2] and match[2] since they
  11470. * are always equal when the other bytes match, given that
  11471. * the hash keys are equal and that HASH_BITS >= 8.
  11472. */
  11473. scan += 2;
  11474. match++;
  11475. // Assert(*scan == *match, "match[2]?");
  11476. /* We check for insufficient lookahead only every 8th comparison;
  11477. * the 256th check will be made at strstart+258.
  11478. */
  11479. do {
  11480. /*jshint noempty:false*/
  11481. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  11482. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  11483. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  11484. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  11485. scan < strend);
  11486. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  11487. len = MAX_MATCH - (strend - scan);
  11488. scan = strend - MAX_MATCH;
  11489. if (len > best_len) {
  11490. s.match_start = cur_match;
  11491. best_len = len;
  11492. if (len >= nice_match) {
  11493. break;
  11494. }
  11495. scan_end1 = _win[scan + best_len - 1];
  11496. scan_end = _win[scan + best_len];
  11497. }
  11498. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  11499. if (best_len <= s.lookahead) {
  11500. return best_len;
  11501. }
  11502. return s.lookahead;
  11503. }
  11504. /* ===========================================================================
  11505. * Fill the window when the lookahead becomes insufficient.
  11506. * Updates strstart and lookahead.
  11507. *
  11508. * IN assertion: lookahead < MIN_LOOKAHEAD
  11509. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  11510. * At least one byte has been read, or avail_in == 0; reads are
  11511. * performed for at least two bytes (required for the zip translate_eol
  11512. * option -- not supported here).
  11513. */
  11514. function fill_window(s) {
  11515. var _w_size = s.w_size;
  11516. var p, n, m, more, str;
  11517. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  11518. do {
  11519. more = s.window_size - s.lookahead - s.strstart;
  11520. // JS ints have 32 bit, block below not needed
  11521. /* Deal with !@#$% 64K limit: */
  11522. //if (sizeof(int) <= 2) {
  11523. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  11524. // more = wsize;
  11525. //
  11526. // } else if (more == (unsigned)(-1)) {
  11527. // /* Very unlikely, but possible on 16 bit machine if
  11528. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  11529. // */
  11530. // more--;
  11531. // }
  11532. //}
  11533. /* If the window is almost full and there is insufficient lookahead,
  11534. * move the upper half to the lower one to make room in the upper half.
  11535. */
  11536. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  11537. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  11538. s.match_start -= _w_size;
  11539. s.strstart -= _w_size;
  11540. /* we now have strstart >= MAX_DIST */
  11541. s.block_start -= _w_size;
  11542. /* Slide the hash table (could be avoided with 32 bit values
  11543. at the expense of memory usage). We slide even when level == 0
  11544. to keep the hash table consistent if we switch back to level > 0
  11545. later. (Using level 0 permanently is not an optimal usage of
  11546. zlib, so we don't care about this pathological case.)
  11547. */
  11548. n = s.hash_size;
  11549. p = n;
  11550. do {
  11551. m = s.head[--p];
  11552. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  11553. } while (--n);
  11554. n = _w_size;
  11555. p = n;
  11556. do {
  11557. m = s.prev[--p];
  11558. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  11559. /* If n is not on any hash chain, prev[n] is garbage but
  11560. * its value will never be used.
  11561. */
  11562. } while (--n);
  11563. more += _w_size;
  11564. }
  11565. if (s.strm.avail_in === 0) {
  11566. break;
  11567. }
  11568. /* If there was no sliding:
  11569. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  11570. * more == window_size - lookahead - strstart
  11571. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  11572. * => more >= window_size - 2*WSIZE + 2
  11573. * In the BIG_MEM or MMAP case (not yet supported),
  11574. * window_size == input_size + MIN_LOOKAHEAD &&
  11575. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  11576. * Otherwise, window_size == 2*WSIZE so more >= 2.
  11577. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  11578. */
  11579. //Assert(more >= 2, "more < 2");
  11580. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  11581. s.lookahead += n;
  11582. /* Initialize the hash value now that we have some input: */
  11583. if (s.lookahead + s.insert >= MIN_MATCH) {
  11584. str = s.strstart - s.insert;
  11585. s.ins_h = s.window[str];
  11586. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  11587. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  11588. //#if MIN_MATCH != 3
  11589. // Call update_hash() MIN_MATCH-3 more times
  11590. //#endif
  11591. while (s.insert) {
  11592. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  11593. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  11594. s.prev[str & s.w_mask] = s.head[s.ins_h];
  11595. s.head[s.ins_h] = str;
  11596. str++;
  11597. s.insert--;
  11598. if (s.lookahead + s.insert < MIN_MATCH) {
  11599. break;
  11600. }
  11601. }
  11602. }
  11603. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  11604. * but this is not important since only literal bytes will be emitted.
  11605. */
  11606. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  11607. /* If the WIN_INIT bytes after the end of the current data have never been
  11608. * written, then zero those bytes in order to avoid memory check reports of
  11609. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  11610. * the longest match routines. Update the high water mark for the next
  11611. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  11612. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  11613. */
  11614. // if (s.high_water < s.window_size) {
  11615. // var curr = s.strstart + s.lookahead;
  11616. // var init = 0;
  11617. //
  11618. // if (s.high_water < curr) {
  11619. // /* Previous high water mark below current data -- zero WIN_INIT
  11620. // * bytes or up to end of window, whichever is less.
  11621. // */
  11622. // init = s.window_size - curr;
  11623. // if (init > WIN_INIT)
  11624. // init = WIN_INIT;
  11625. // zmemzero(s->window + curr, (unsigned)init);
  11626. // s->high_water = curr + init;
  11627. // }
  11628. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  11629. // /* High water mark at or above current data, but below current data
  11630. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  11631. // * to end of window, whichever is less.
  11632. // */
  11633. // init = (ulg)curr + WIN_INIT - s->high_water;
  11634. // if (init > s->window_size - s->high_water)
  11635. // init = s->window_size - s->high_water;
  11636. // zmemzero(s->window + s->high_water, (unsigned)init);
  11637. // s->high_water += init;
  11638. // }
  11639. // }
  11640. //
  11641. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  11642. // "not enough room for search");
  11643. }
  11644. /* ===========================================================================
  11645. * Copy without compression as much as possible from the input stream, return
  11646. * the current block state.
  11647. * This function does not insert new strings in the dictionary since
  11648. * uncompressible data is probably not useful. This function is used
  11649. * only for the level=0 compression option.
  11650. * NOTE: this function should be optimized to avoid extra copying from
  11651. * window to pending_buf.
  11652. */
  11653. function deflate_stored(s, flush) {
  11654. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  11655. * to pending_buf_size, and each stored block has a 5 byte header:
  11656. */
  11657. var max_block_size = 0xffff;
  11658. if (max_block_size > s.pending_buf_size - 5) {
  11659. max_block_size = s.pending_buf_size - 5;
  11660. }
  11661. /* Copy as much as possible from input to output: */
  11662. for (;;) {
  11663. /* Fill the window as much as possible: */
  11664. if (s.lookahead <= 1) {
  11665. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  11666. // s->block_start >= (long)s->w_size, "slide too late");
  11667. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  11668. // s.block_start >= s.w_size)) {
  11669. // throw new Error("slide too late");
  11670. // }
  11671. fill_window(s);
  11672. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  11673. return BS_NEED_MORE;
  11674. }
  11675. if (s.lookahead === 0) {
  11676. break;
  11677. }
  11678. /* flush the current block */
  11679. }
  11680. //Assert(s->block_start >= 0L, "block gone");
  11681. // if (s.block_start < 0) throw new Error("block gone");
  11682. s.strstart += s.lookahead;
  11683. s.lookahead = 0;
  11684. /* Emit a stored block if pending_buf will be full: */
  11685. var max_start = s.block_start + max_block_size;
  11686. if (s.strstart === 0 || s.strstart >= max_start) {
  11687. /* strstart == 0 is possible when wraparound on 16-bit machine */
  11688. s.lookahead = s.strstart - max_start;
  11689. s.strstart = max_start;
  11690. /*** FLUSH_BLOCK(s, 0); ***/
  11691. flush_block_only(s, false);
  11692. if (s.strm.avail_out === 0) {
  11693. return BS_NEED_MORE;
  11694. }
  11695. /***/
  11696. }
  11697. /* Flush if we may have to slide, otherwise block_start may become
  11698. * negative and the data will be gone:
  11699. */
  11700. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  11701. /*** FLUSH_BLOCK(s, 0); ***/
  11702. flush_block_only(s, false);
  11703. if (s.strm.avail_out === 0) {
  11704. return BS_NEED_MORE;
  11705. }
  11706. /***/
  11707. }
  11708. }
  11709. s.insert = 0;
  11710. if (flush === Z_FINISH) {
  11711. /*** FLUSH_BLOCK(s, 1); ***/
  11712. flush_block_only(s, true);
  11713. if (s.strm.avail_out === 0) {
  11714. return BS_FINISH_STARTED;
  11715. }
  11716. /***/
  11717. return BS_FINISH_DONE;
  11718. }
  11719. if (s.strstart > s.block_start) {
  11720. /*** FLUSH_BLOCK(s, 0); ***/
  11721. flush_block_only(s, false);
  11722. if (s.strm.avail_out === 0) {
  11723. return BS_NEED_MORE;
  11724. }
  11725. /***/
  11726. }
  11727. return BS_NEED_MORE;
  11728. }
  11729. /* ===========================================================================
  11730. * Compress as much as possible from the input stream, return the current
  11731. * block state.
  11732. * This function does not perform lazy evaluation of matches and inserts
  11733. * new strings in the dictionary only for unmatched strings or for short
  11734. * matches. It is used only for the fast compression options.
  11735. */
  11736. function deflate_fast(s, flush) {
  11737. var hash_head; /* head of the hash chain */
  11738. var bflush; /* set if current block must be flushed */
  11739. for (;;) {
  11740. /* Make sure that we always have enough lookahead, except
  11741. * at the end of the input file. We need MAX_MATCH bytes
  11742. * for the next match, plus MIN_MATCH bytes to insert the
  11743. * string following the next match.
  11744. */
  11745. if (s.lookahead < MIN_LOOKAHEAD) {
  11746. fill_window(s);
  11747. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  11748. return BS_NEED_MORE;
  11749. }
  11750. if (s.lookahead === 0) {
  11751. break; /* flush the current block */
  11752. }
  11753. }
  11754. /* Insert the string window[strstart .. strstart+2] in the
  11755. * dictionary, and set hash_head to the head of the hash chain:
  11756. */
  11757. hash_head = 0/*NIL*/;
  11758. if (s.lookahead >= MIN_MATCH) {
  11759. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  11760. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  11761. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  11762. s.head[s.ins_h] = s.strstart;
  11763. /***/
  11764. }
  11765. /* Find the longest match, discarding those <= prev_length.
  11766. * At this point we have always match_length < MIN_MATCH
  11767. */
  11768. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  11769. /* To simplify the code, we prevent matches with the string
  11770. * of window index 0 (in particular we have to avoid a match
  11771. * of the string with itself at the start of the input file).
  11772. */
  11773. s.match_length = longest_match(s, hash_head);
  11774. /* longest_match() sets match_start */
  11775. }
  11776. if (s.match_length >= MIN_MATCH) {
  11777. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  11778. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  11779. s.match_length - MIN_MATCH, bflush); ***/
  11780. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  11781. s.lookahead -= s.match_length;
  11782. /* Insert new strings in the hash table only if the match length
  11783. * is not too large. This saves time but degrades compression.
  11784. */
  11785. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  11786. s.match_length--; /* string at strstart already in table */
  11787. do {
  11788. s.strstart++;
  11789. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  11790. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  11791. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  11792. s.head[s.ins_h] = s.strstart;
  11793. /***/
  11794. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  11795. * always MIN_MATCH bytes ahead.
  11796. */
  11797. } while (--s.match_length !== 0);
  11798. s.strstart++;
  11799. } else
  11800. {
  11801. s.strstart += s.match_length;
  11802. s.match_length = 0;
  11803. s.ins_h = s.window[s.strstart];
  11804. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  11805. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  11806. //#if MIN_MATCH != 3
  11807. // Call UPDATE_HASH() MIN_MATCH-3 more times
  11808. //#endif
  11809. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  11810. * matter since it will be recomputed at next deflate call.
  11811. */
  11812. }
  11813. } else {
  11814. /* No match, output a literal byte */
  11815. //Tracevv((stderr,"%c", s.window[s.strstart]));
  11816. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  11817. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  11818. s.lookahead--;
  11819. s.strstart++;
  11820. }
  11821. if (bflush) {
  11822. /*** FLUSH_BLOCK(s, 0); ***/
  11823. flush_block_only(s, false);
  11824. if (s.strm.avail_out === 0) {
  11825. return BS_NEED_MORE;
  11826. }
  11827. /***/
  11828. }
  11829. }
  11830. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  11831. if (flush === Z_FINISH) {
  11832. /*** FLUSH_BLOCK(s, 1); ***/
  11833. flush_block_only(s, true);
  11834. if (s.strm.avail_out === 0) {
  11835. return BS_FINISH_STARTED;
  11836. }
  11837. /***/
  11838. return BS_FINISH_DONE;
  11839. }
  11840. if (s.last_lit) {
  11841. /*** FLUSH_BLOCK(s, 0); ***/
  11842. flush_block_only(s, false);
  11843. if (s.strm.avail_out === 0) {
  11844. return BS_NEED_MORE;
  11845. }
  11846. /***/
  11847. }
  11848. return BS_BLOCK_DONE;
  11849. }
  11850. /* ===========================================================================
  11851. * Same as above, but achieves better compression. We use a lazy
  11852. * evaluation for matches: a match is finally adopted only if there is
  11853. * no better match at the next window position.
  11854. */
  11855. function deflate_slow(s, flush) {
  11856. var hash_head; /* head of hash chain */
  11857. var bflush; /* set if current block must be flushed */
  11858. var max_insert;
  11859. /* Process the input block. */
  11860. for (;;) {
  11861. /* Make sure that we always have enough lookahead, except
  11862. * at the end of the input file. We need MAX_MATCH bytes
  11863. * for the next match, plus MIN_MATCH bytes to insert the
  11864. * string following the next match.
  11865. */
  11866. if (s.lookahead < MIN_LOOKAHEAD) {
  11867. fill_window(s);
  11868. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  11869. return BS_NEED_MORE;
  11870. }
  11871. if (s.lookahead === 0) { break; } /* flush the current block */
  11872. }
  11873. /* Insert the string window[strstart .. strstart+2] in the
  11874. * dictionary, and set hash_head to the head of the hash chain:
  11875. */
  11876. hash_head = 0/*NIL*/;
  11877. if (s.lookahead >= MIN_MATCH) {
  11878. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  11879. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  11880. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  11881. s.head[s.ins_h] = s.strstart;
  11882. /***/
  11883. }
  11884. /* Find the longest match, discarding those <= prev_length.
  11885. */
  11886. s.prev_length = s.match_length;
  11887. s.prev_match = s.match_start;
  11888. s.match_length = MIN_MATCH-1;
  11889. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  11890. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  11891. /* To simplify the code, we prevent matches with the string
  11892. * of window index 0 (in particular we have to avoid a match
  11893. * of the string with itself at the start of the input file).
  11894. */
  11895. s.match_length = longest_match(s, hash_head);
  11896. /* longest_match() sets match_start */
  11897. if (s.match_length <= 5 &&
  11898. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  11899. /* If prev_match is also MIN_MATCH, match_start is garbage
  11900. * but we will ignore the current match anyway.
  11901. */
  11902. s.match_length = MIN_MATCH-1;
  11903. }
  11904. }
  11905. /* If there was a match at the previous step and the current
  11906. * match is not better, output the previous match:
  11907. */
  11908. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  11909. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  11910. /* Do not insert strings in hash table beyond this. */
  11911. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  11912. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  11913. s.prev_length - MIN_MATCH, bflush);***/
  11914. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  11915. /* Insert in hash table all strings up to the end of the match.
  11916. * strstart-1 and strstart are already inserted. If there is not
  11917. * enough lookahead, the last two strings are not inserted in
  11918. * the hash table.
  11919. */
  11920. s.lookahead -= s.prev_length-1;
  11921. s.prev_length -= 2;
  11922. do {
  11923. if (++s.strstart <= max_insert) {
  11924. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  11925. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  11926. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  11927. s.head[s.ins_h] = s.strstart;
  11928. /***/
  11929. }
  11930. } while (--s.prev_length !== 0);
  11931. s.match_available = 0;
  11932. s.match_length = MIN_MATCH-1;
  11933. s.strstart++;
  11934. if (bflush) {
  11935. /*** FLUSH_BLOCK(s, 0); ***/
  11936. flush_block_only(s, false);
  11937. if (s.strm.avail_out === 0) {
  11938. return BS_NEED_MORE;
  11939. }
  11940. /***/
  11941. }
  11942. } else if (s.match_available) {
  11943. /* If there was no match at the previous position, output a
  11944. * single literal. If there was a match but the current match
  11945. * is longer, truncate the previous match to a single literal.
  11946. */
  11947. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  11948. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  11949. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  11950. if (bflush) {
  11951. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  11952. flush_block_only(s, false);
  11953. /***/
  11954. }
  11955. s.strstart++;
  11956. s.lookahead--;
  11957. if (s.strm.avail_out === 0) {
  11958. return BS_NEED_MORE;
  11959. }
  11960. } else {
  11961. /* There is no previous match to compare with, wait for
  11962. * the next step to decide.
  11963. */
  11964. s.match_available = 1;
  11965. s.strstart++;
  11966. s.lookahead--;
  11967. }
  11968. }
  11969. //Assert (flush != Z_NO_FLUSH, "no flush?");
  11970. if (s.match_available) {
  11971. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  11972. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  11973. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  11974. s.match_available = 0;
  11975. }
  11976. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  11977. if (flush === Z_FINISH) {
  11978. /*** FLUSH_BLOCK(s, 1); ***/
  11979. flush_block_only(s, true);
  11980. if (s.strm.avail_out === 0) {
  11981. return BS_FINISH_STARTED;
  11982. }
  11983. /***/
  11984. return BS_FINISH_DONE;
  11985. }
  11986. if (s.last_lit) {
  11987. /*** FLUSH_BLOCK(s, 0); ***/
  11988. flush_block_only(s, false);
  11989. if (s.strm.avail_out === 0) {
  11990. return BS_NEED_MORE;
  11991. }
  11992. /***/
  11993. }
  11994. return BS_BLOCK_DONE;
  11995. }
  11996. /* ===========================================================================
  11997. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  11998. * one. Do not maintain a hash table. (It will be regenerated if this run of
  11999. * deflate switches away from Z_RLE.)
  12000. */
  12001. function deflate_rle(s, flush) {
  12002. var bflush; /* set if current block must be flushed */
  12003. var prev; /* byte at distance one to match */
  12004. var scan, strend; /* scan goes up to strend for length of run */
  12005. var _win = s.window;
  12006. for (;;) {
  12007. /* Make sure that we always have enough lookahead, except
  12008. * at the end of the input file. We need MAX_MATCH bytes
  12009. * for the longest run, plus one for the unrolled loop.
  12010. */
  12011. if (s.lookahead <= MAX_MATCH) {
  12012. fill_window(s);
  12013. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  12014. return BS_NEED_MORE;
  12015. }
  12016. if (s.lookahead === 0) { break; } /* flush the current block */
  12017. }
  12018. /* See how many times the previous byte repeats */
  12019. s.match_length = 0;
  12020. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  12021. scan = s.strstart - 1;
  12022. prev = _win[scan];
  12023. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  12024. strend = s.strstart + MAX_MATCH;
  12025. do {
  12026. /*jshint noempty:false*/
  12027. } while (prev === _win[++scan] && prev === _win[++scan] &&
  12028. prev === _win[++scan] && prev === _win[++scan] &&
  12029. prev === _win[++scan] && prev === _win[++scan] &&
  12030. prev === _win[++scan] && prev === _win[++scan] &&
  12031. scan < strend);
  12032. s.match_length = MAX_MATCH - (strend - scan);
  12033. if (s.match_length > s.lookahead) {
  12034. s.match_length = s.lookahead;
  12035. }
  12036. }
  12037. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  12038. }
  12039. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  12040. if (s.match_length >= MIN_MATCH) {
  12041. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  12042. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  12043. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  12044. s.lookahead -= s.match_length;
  12045. s.strstart += s.match_length;
  12046. s.match_length = 0;
  12047. } else {
  12048. /* No match, output a literal byte */
  12049. //Tracevv((stderr,"%c", s->window[s->strstart]));
  12050. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  12051. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  12052. s.lookahead--;
  12053. s.strstart++;
  12054. }
  12055. if (bflush) {
  12056. /*** FLUSH_BLOCK(s, 0); ***/
  12057. flush_block_only(s, false);
  12058. if (s.strm.avail_out === 0) {
  12059. return BS_NEED_MORE;
  12060. }
  12061. /***/
  12062. }
  12063. }
  12064. s.insert = 0;
  12065. if (flush === Z_FINISH) {
  12066. /*** FLUSH_BLOCK(s, 1); ***/
  12067. flush_block_only(s, true);
  12068. if (s.strm.avail_out === 0) {
  12069. return BS_FINISH_STARTED;
  12070. }
  12071. /***/
  12072. return BS_FINISH_DONE;
  12073. }
  12074. if (s.last_lit) {
  12075. /*** FLUSH_BLOCK(s, 0); ***/
  12076. flush_block_only(s, false);
  12077. if (s.strm.avail_out === 0) {
  12078. return BS_NEED_MORE;
  12079. }
  12080. /***/
  12081. }
  12082. return BS_BLOCK_DONE;
  12083. }
  12084. /* ===========================================================================
  12085. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  12086. * (It will be regenerated if this run of deflate switches away from Huffman.)
  12087. */
  12088. function deflate_huff(s, flush) {
  12089. var bflush; /* set if current block must be flushed */
  12090. for (;;) {
  12091. /* Make sure that we have a literal to write. */
  12092. if (s.lookahead === 0) {
  12093. fill_window(s);
  12094. if (s.lookahead === 0) {
  12095. if (flush === Z_NO_FLUSH) {
  12096. return BS_NEED_MORE;
  12097. }
  12098. break; /* flush the current block */
  12099. }
  12100. }
  12101. /* Output a literal byte */
  12102. s.match_length = 0;
  12103. //Tracevv((stderr,"%c", s->window[s->strstart]));
  12104. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  12105. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  12106. s.lookahead--;
  12107. s.strstart++;
  12108. if (bflush) {
  12109. /*** FLUSH_BLOCK(s, 0); ***/
  12110. flush_block_only(s, false);
  12111. if (s.strm.avail_out === 0) {
  12112. return BS_NEED_MORE;
  12113. }
  12114. /***/
  12115. }
  12116. }
  12117. s.insert = 0;
  12118. if (flush === Z_FINISH) {
  12119. /*** FLUSH_BLOCK(s, 1); ***/
  12120. flush_block_only(s, true);
  12121. if (s.strm.avail_out === 0) {
  12122. return BS_FINISH_STARTED;
  12123. }
  12124. /***/
  12125. return BS_FINISH_DONE;
  12126. }
  12127. if (s.last_lit) {
  12128. /*** FLUSH_BLOCK(s, 0); ***/
  12129. flush_block_only(s, false);
  12130. if (s.strm.avail_out === 0) {
  12131. return BS_NEED_MORE;
  12132. }
  12133. /***/
  12134. }
  12135. return BS_BLOCK_DONE;
  12136. }
  12137. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  12138. * the desired pack level (0..9). The values given below have been tuned to
  12139. * exclude worst case performance for pathological files. Better values may be
  12140. * found for specific files.
  12141. */
  12142. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  12143. this.good_length = good_length;
  12144. this.max_lazy = max_lazy;
  12145. this.nice_length = nice_length;
  12146. this.max_chain = max_chain;
  12147. this.func = func;
  12148. };
  12149. var configuration_table;
  12150. configuration_table = [
  12151. /* good lazy nice chain */
  12152. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  12153. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  12154. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  12155. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  12156. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  12157. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  12158. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  12159. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  12160. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  12161. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  12162. ];
  12163. /* ===========================================================================
  12164. * Initialize the "longest match" routines for a new zlib stream
  12165. */
  12166. function lm_init(s) {
  12167. s.window_size = 2 * s.w_size;
  12168. /*** CLEAR_HASH(s); ***/
  12169. zero(s.head); // Fill with NIL (= 0);
  12170. /* Set the default configuration parameters:
  12171. */
  12172. s.max_lazy_match = configuration_table[s.level].max_lazy;
  12173. s.good_match = configuration_table[s.level].good_length;
  12174. s.nice_match = configuration_table[s.level].nice_length;
  12175. s.max_chain_length = configuration_table[s.level].max_chain;
  12176. s.strstart = 0;
  12177. s.block_start = 0;
  12178. s.lookahead = 0;
  12179. s.insert = 0;
  12180. s.match_length = s.prev_length = MIN_MATCH - 1;
  12181. s.match_available = 0;
  12182. s.ins_h = 0;
  12183. }
  12184. function DeflateState() {
  12185. this.strm = null; /* pointer back to this zlib stream */
  12186. this.status = 0; /* as the name implies */
  12187. this.pending_buf = null; /* output still pending */
  12188. this.pending_buf_size = 0; /* size of pending_buf */
  12189. this.pending_out = 0; /* next pending byte to output to the stream */
  12190. this.pending = 0; /* nb of bytes in the pending buffer */
  12191. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  12192. this.gzhead = null; /* gzip header information to write */
  12193. this.gzindex = 0; /* where in extra, name, or comment */
  12194. this.method = Z_DEFLATED; /* can only be DEFLATED */
  12195. this.last_flush = -1; /* value of flush param for previous deflate call */
  12196. this.w_size = 0; /* LZ77 window size (32K by default) */
  12197. this.w_bits = 0; /* log2(w_size) (8..16) */
  12198. this.w_mask = 0; /* w_size - 1 */
  12199. this.window = null;
  12200. /* Sliding window. Input bytes are read into the second half of the window,
  12201. * and move to the first half later to keep a dictionary of at least wSize
  12202. * bytes. With this organization, matches are limited to a distance of
  12203. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  12204. * performed with a length multiple of the block size.
  12205. */
  12206. this.window_size = 0;
  12207. /* Actual size of window: 2*wSize, except when the user input buffer
  12208. * is directly used as sliding window.
  12209. */
  12210. this.prev = null;
  12211. /* Link to older string with same hash index. To limit the size of this
  12212. * array to 64K, this link is maintained only for the last 32K strings.
  12213. * An index in this array is thus a window index modulo 32K.
  12214. */
  12215. this.head = null; /* Heads of the hash chains or NIL. */
  12216. this.ins_h = 0; /* hash index of string to be inserted */
  12217. this.hash_size = 0; /* number of elements in hash table */
  12218. this.hash_bits = 0; /* log2(hash_size) */
  12219. this.hash_mask = 0; /* hash_size-1 */
  12220. this.hash_shift = 0;
  12221. /* Number of bits by which ins_h must be shifted at each input
  12222. * step. It must be such that after MIN_MATCH steps, the oldest
  12223. * byte no longer takes part in the hash key, that is:
  12224. * hash_shift * MIN_MATCH >= hash_bits
  12225. */
  12226. this.block_start = 0;
  12227. /* Window position at the beginning of the current output block. Gets
  12228. * negative when the window is moved backwards.
  12229. */
  12230. this.match_length = 0; /* length of best match */
  12231. this.prev_match = 0; /* previous match */
  12232. this.match_available = 0; /* set if previous match exists */
  12233. this.strstart = 0; /* start of string to insert */
  12234. this.match_start = 0; /* start of matching string */
  12235. this.lookahead = 0; /* number of valid bytes ahead in window */
  12236. this.prev_length = 0;
  12237. /* Length of the best match at previous step. Matches not greater than this
  12238. * are discarded. This is used in the lazy match evaluation.
  12239. */
  12240. this.max_chain_length = 0;
  12241. /* To speed up deflation, hash chains are never searched beyond this
  12242. * length. A higher limit improves compression ratio but degrades the
  12243. * speed.
  12244. */
  12245. this.max_lazy_match = 0;
  12246. /* Attempt to find a better match only when the current match is strictly
  12247. * smaller than this value. This mechanism is used only for compression
  12248. * levels >= 4.
  12249. */
  12250. // That's alias to max_lazy_match, don't use directly
  12251. //this.max_insert_length = 0;
  12252. /* Insert new strings in the hash table only if the match length is not
  12253. * greater than this length. This saves time but degrades compression.
  12254. * max_insert_length is used only for compression levels <= 3.
  12255. */
  12256. this.level = 0; /* compression level (1..9) */
  12257. this.strategy = 0; /* favor or force Huffman coding*/
  12258. this.good_match = 0;
  12259. /* Use a faster search when the previous match is longer than this */
  12260. this.nice_match = 0; /* Stop searching when current match exceeds this */
  12261. /* used by trees.c: */
  12262. /* Didn't use ct_data typedef below to suppress compiler warning */
  12263. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  12264. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  12265. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  12266. // Use flat array of DOUBLE size, with interleaved fata,
  12267. // because JS does not support effective
  12268. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  12269. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  12270. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  12271. zero(this.dyn_ltree);
  12272. zero(this.dyn_dtree);
  12273. zero(this.bl_tree);
  12274. this.l_desc = null; /* desc. for literal tree */
  12275. this.d_desc = null; /* desc. for distance tree */
  12276. this.bl_desc = null; /* desc. for bit length tree */
  12277. //ush bl_count[MAX_BITS+1];
  12278. this.bl_count = new utils.Buf16(MAX_BITS+1);
  12279. /* number of codes at each bit length for an optimal tree */
  12280. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  12281. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  12282. zero(this.heap);
  12283. this.heap_len = 0; /* number of elements in the heap */
  12284. this.heap_max = 0; /* element of largest frequency */
  12285. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  12286. * The same heap array is used to build all trees.
  12287. */
  12288. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  12289. zero(this.depth);
  12290. /* Depth of each subtree used as tie breaker for trees of equal frequency
  12291. */
  12292. this.l_buf = 0; /* buffer index for literals or lengths */
  12293. this.lit_bufsize = 0;
  12294. /* Size of match buffer for literals/lengths. There are 4 reasons for
  12295. * limiting lit_bufsize to 64K:
  12296. * - frequencies can be kept in 16 bit counters
  12297. * - if compression is not successful for the first block, all input
  12298. * data is still in the window so we can still emit a stored block even
  12299. * when input comes from standard input. (This can also be done for
  12300. * all blocks if lit_bufsize is not greater than 32K.)
  12301. * - if compression is not successful for a file smaller than 64K, we can
  12302. * even emit a stored file instead of a stored block (saving 5 bytes).
  12303. * This is applicable only for zip (not gzip or zlib).
  12304. * - creating new Huffman trees less frequently may not provide fast
  12305. * adaptation to changes in the input data statistics. (Take for
  12306. * example a binary file with poorly compressible code followed by
  12307. * a highly compressible string table.) Smaller buffer sizes give
  12308. * fast adaptation but have of course the overhead of transmitting
  12309. * trees more frequently.
  12310. * - I can't count above 4
  12311. */
  12312. this.last_lit = 0; /* running index in l_buf */
  12313. this.d_buf = 0;
  12314. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  12315. * the same number of elements. To use different lengths, an extra flag
  12316. * array would be necessary.
  12317. */
  12318. this.opt_len = 0; /* bit length of current block with optimal trees */
  12319. this.static_len = 0; /* bit length of current block with static trees */
  12320. this.matches = 0; /* number of string matches in current block */
  12321. this.insert = 0; /* bytes at end of window left to insert */
  12322. this.bi_buf = 0;
  12323. /* Output buffer. bits are inserted starting at the bottom (least
  12324. * significant bits).
  12325. */
  12326. this.bi_valid = 0;
  12327. /* Number of valid bits in bi_buf. All bits above the last valid bit
  12328. * are always zero.
  12329. */
  12330. // Used for window memory init. We safely ignore it for JS. That makes
  12331. // sense only for pointers and memory check tools.
  12332. //this.high_water = 0;
  12333. /* High water mark offset in window for initialized bytes -- bytes above
  12334. * this are set to zero in order to avoid memory check warnings when
  12335. * longest match routines access bytes past the input. This is then
  12336. * updated to the new high water mark.
  12337. */
  12338. }
  12339. function deflateResetKeep(strm) {
  12340. var s;
  12341. if (!strm || !strm.state) {
  12342. return err(strm, Z_STREAM_ERROR);
  12343. }
  12344. strm.total_in = strm.total_out = 0;
  12345. strm.data_type = Z_UNKNOWN;
  12346. s = strm.state;
  12347. s.pending = 0;
  12348. s.pending_out = 0;
  12349. if (s.wrap < 0) {
  12350. s.wrap = -s.wrap;
  12351. /* was made negative by deflate(..., Z_FINISH); */
  12352. }
  12353. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  12354. strm.adler = (s.wrap === 2) ?
  12355. 0 // crc32(0, Z_NULL, 0)
  12356. :
  12357. 1; // adler32(0, Z_NULL, 0)
  12358. s.last_flush = Z_NO_FLUSH;
  12359. trees._tr_init(s);
  12360. return Z_OK;
  12361. }
  12362. function deflateReset(strm) {
  12363. var ret = deflateResetKeep(strm);
  12364. if (ret === Z_OK) {
  12365. lm_init(strm.state);
  12366. }
  12367. return ret;
  12368. }
  12369. function deflateSetHeader(strm, head) {
  12370. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  12371. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  12372. strm.state.gzhead = head;
  12373. return Z_OK;
  12374. }
  12375. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  12376. if (!strm) { // === Z_NULL
  12377. return Z_STREAM_ERROR;
  12378. }
  12379. var wrap = 1;
  12380. if (level === Z_DEFAULT_COMPRESSION) {
  12381. level = 6;
  12382. }
  12383. if (windowBits < 0) { /* suppress zlib wrapper */
  12384. wrap = 0;
  12385. windowBits = -windowBits;
  12386. }
  12387. else if (windowBits > 15) {
  12388. wrap = 2; /* write gzip wrapper instead */
  12389. windowBits -= 16;
  12390. }
  12391. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  12392. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  12393. strategy < 0 || strategy > Z_FIXED) {
  12394. return err(strm, Z_STREAM_ERROR);
  12395. }
  12396. if (windowBits === 8) {
  12397. windowBits = 9;
  12398. }
  12399. /* until 256-byte window bug fixed */
  12400. var s = new DeflateState();
  12401. strm.state = s;
  12402. s.strm = strm;
  12403. s.wrap = wrap;
  12404. s.gzhead = null;
  12405. s.w_bits = windowBits;
  12406. s.w_size = 1 << s.w_bits;
  12407. s.w_mask = s.w_size - 1;
  12408. s.hash_bits = memLevel + 7;
  12409. s.hash_size = 1 << s.hash_bits;
  12410. s.hash_mask = s.hash_size - 1;
  12411. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  12412. s.window = new utils.Buf8(s.w_size * 2);
  12413. s.head = new utils.Buf16(s.hash_size);
  12414. s.prev = new utils.Buf16(s.w_size);
  12415. // Don't need mem init magic for JS.
  12416. //s.high_water = 0; /* nothing written to s->window yet */
  12417. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  12418. s.pending_buf_size = s.lit_bufsize * 4;
  12419. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  12420. s.d_buf = s.lit_bufsize >> 1;
  12421. s.l_buf = (1 + 2) * s.lit_bufsize;
  12422. s.level = level;
  12423. s.strategy = strategy;
  12424. s.method = method;
  12425. return deflateReset(strm);
  12426. }
  12427. function deflateInit(strm, level) {
  12428. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  12429. }
  12430. function deflate(strm, flush) {
  12431. var old_flush, s;
  12432. var beg, val; // for gzip header write only
  12433. if (!strm || !strm.state ||
  12434. flush > Z_BLOCK || flush < 0) {
  12435. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  12436. }
  12437. s = strm.state;
  12438. if (!strm.output ||
  12439. (!strm.input && strm.avail_in !== 0) ||
  12440. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  12441. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  12442. }
  12443. s.strm = strm; /* just in case */
  12444. old_flush = s.last_flush;
  12445. s.last_flush = flush;
  12446. /* Write the header */
  12447. if (s.status === INIT_STATE) {
  12448. if (s.wrap === 2) { // GZIP header
  12449. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  12450. put_byte(s, 31);
  12451. put_byte(s, 139);
  12452. put_byte(s, 8);
  12453. if (!s.gzhead) { // s->gzhead == Z_NULL
  12454. put_byte(s, 0);
  12455. put_byte(s, 0);
  12456. put_byte(s, 0);
  12457. put_byte(s, 0);
  12458. put_byte(s, 0);
  12459. put_byte(s, s.level === 9 ? 2 :
  12460. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  12461. 4 : 0));
  12462. put_byte(s, OS_CODE);
  12463. s.status = BUSY_STATE;
  12464. }
  12465. else {
  12466. put_byte(s, (s.gzhead.text ? 1 : 0) +
  12467. (s.gzhead.hcrc ? 2 : 0) +
  12468. (!s.gzhead.extra ? 0 : 4) +
  12469. (!s.gzhead.name ? 0 : 8) +
  12470. (!s.gzhead.comment ? 0 : 16)
  12471. );
  12472. put_byte(s, s.gzhead.time & 0xff);
  12473. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  12474. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  12475. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  12476. put_byte(s, s.level === 9 ? 2 :
  12477. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  12478. 4 : 0));
  12479. put_byte(s, s.gzhead.os & 0xff);
  12480. if (s.gzhead.extra && s.gzhead.extra.length) {
  12481. put_byte(s, s.gzhead.extra.length & 0xff);
  12482. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  12483. }
  12484. if (s.gzhead.hcrc) {
  12485. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  12486. }
  12487. s.gzindex = 0;
  12488. s.status = EXTRA_STATE;
  12489. }
  12490. }
  12491. else // DEFLATE header
  12492. {
  12493. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  12494. var level_flags = -1;
  12495. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  12496. level_flags = 0;
  12497. } else if (s.level < 6) {
  12498. level_flags = 1;
  12499. } else if (s.level === 6) {
  12500. level_flags = 2;
  12501. } else {
  12502. level_flags = 3;
  12503. }
  12504. header |= (level_flags << 6);
  12505. if (s.strstart !== 0) { header |= PRESET_DICT; }
  12506. header += 31 - (header % 31);
  12507. s.status = BUSY_STATE;
  12508. putShortMSB(s, header);
  12509. /* Save the adler32 of the preset dictionary: */
  12510. if (s.strstart !== 0) {
  12511. putShortMSB(s, strm.adler >>> 16);
  12512. putShortMSB(s, strm.adler & 0xffff);
  12513. }
  12514. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  12515. }
  12516. }
  12517. //#ifdef GZIP
  12518. if (s.status === EXTRA_STATE) {
  12519. if (s.gzhead.extra/* != Z_NULL*/) {
  12520. beg = s.pending; /* start of bytes to update crc */
  12521. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  12522. if (s.pending === s.pending_buf_size) {
  12523. if (s.gzhead.hcrc && s.pending > beg) {
  12524. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12525. }
  12526. flush_pending(strm);
  12527. beg = s.pending;
  12528. if (s.pending === s.pending_buf_size) {
  12529. break;
  12530. }
  12531. }
  12532. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  12533. s.gzindex++;
  12534. }
  12535. if (s.gzhead.hcrc && s.pending > beg) {
  12536. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12537. }
  12538. if (s.gzindex === s.gzhead.extra.length) {
  12539. s.gzindex = 0;
  12540. s.status = NAME_STATE;
  12541. }
  12542. }
  12543. else {
  12544. s.status = NAME_STATE;
  12545. }
  12546. }
  12547. if (s.status === NAME_STATE) {
  12548. if (s.gzhead.name/* != Z_NULL*/) {
  12549. beg = s.pending; /* start of bytes to update crc */
  12550. //int val;
  12551. do {
  12552. if (s.pending === s.pending_buf_size) {
  12553. if (s.gzhead.hcrc && s.pending > beg) {
  12554. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12555. }
  12556. flush_pending(strm);
  12557. beg = s.pending;
  12558. if (s.pending === s.pending_buf_size) {
  12559. val = 1;
  12560. break;
  12561. }
  12562. }
  12563. // JS specific: little magic to add zero terminator to end of string
  12564. if (s.gzindex < s.gzhead.name.length) {
  12565. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  12566. } else {
  12567. val = 0;
  12568. }
  12569. put_byte(s, val);
  12570. } while (val !== 0);
  12571. if (s.gzhead.hcrc && s.pending > beg) {
  12572. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12573. }
  12574. if (val === 0) {
  12575. s.gzindex = 0;
  12576. s.status = COMMENT_STATE;
  12577. }
  12578. }
  12579. else {
  12580. s.status = COMMENT_STATE;
  12581. }
  12582. }
  12583. if (s.status === COMMENT_STATE) {
  12584. if (s.gzhead.comment/* != Z_NULL*/) {
  12585. beg = s.pending; /* start of bytes to update crc */
  12586. //int val;
  12587. do {
  12588. if (s.pending === s.pending_buf_size) {
  12589. if (s.gzhead.hcrc && s.pending > beg) {
  12590. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12591. }
  12592. flush_pending(strm);
  12593. beg = s.pending;
  12594. if (s.pending === s.pending_buf_size) {
  12595. val = 1;
  12596. break;
  12597. }
  12598. }
  12599. // JS specific: little magic to add zero terminator to end of string
  12600. if (s.gzindex < s.gzhead.comment.length) {
  12601. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  12602. } else {
  12603. val = 0;
  12604. }
  12605. put_byte(s, val);
  12606. } while (val !== 0);
  12607. if (s.gzhead.hcrc && s.pending > beg) {
  12608. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12609. }
  12610. if (val === 0) {
  12611. s.status = HCRC_STATE;
  12612. }
  12613. }
  12614. else {
  12615. s.status = HCRC_STATE;
  12616. }
  12617. }
  12618. if (s.status === HCRC_STATE) {
  12619. if (s.gzhead.hcrc) {
  12620. if (s.pending + 2 > s.pending_buf_size) {
  12621. flush_pending(strm);
  12622. }
  12623. if (s.pending + 2 <= s.pending_buf_size) {
  12624. put_byte(s, strm.adler & 0xff);
  12625. put_byte(s, (strm.adler >> 8) & 0xff);
  12626. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  12627. s.status = BUSY_STATE;
  12628. }
  12629. }
  12630. else {
  12631. s.status = BUSY_STATE;
  12632. }
  12633. }
  12634. //#endif
  12635. /* Flush as much pending output as possible */
  12636. if (s.pending !== 0) {
  12637. flush_pending(strm);
  12638. if (strm.avail_out === 0) {
  12639. /* Since avail_out is 0, deflate will be called again with
  12640. * more output space, but possibly with both pending and
  12641. * avail_in equal to zero. There won't be anything to do,
  12642. * but this is not an error situation so make sure we
  12643. * return OK instead of BUF_ERROR at next call of deflate:
  12644. */
  12645. s.last_flush = -1;
  12646. return Z_OK;
  12647. }
  12648. /* Make sure there is something to do and avoid duplicate consecutive
  12649. * flushes. For repeated and useless calls with Z_FINISH, we keep
  12650. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  12651. */
  12652. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  12653. flush !== Z_FINISH) {
  12654. return err(strm, Z_BUF_ERROR);
  12655. }
  12656. /* User must not provide more input after the first FINISH: */
  12657. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  12658. return err(strm, Z_BUF_ERROR);
  12659. }
  12660. /* Start a new block or continue the current one.
  12661. */
  12662. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  12663. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  12664. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  12665. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  12666. configuration_table[s.level].func(s, flush));
  12667. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  12668. s.status = FINISH_STATE;
  12669. }
  12670. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  12671. if (strm.avail_out === 0) {
  12672. s.last_flush = -1;
  12673. /* avoid BUF_ERROR next call, see above */
  12674. }
  12675. return Z_OK;
  12676. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  12677. * of deflate should use the same flush parameter to make sure
  12678. * that the flush is complete. So we don't have to output an
  12679. * empty block here, this will be done at next call. This also
  12680. * ensures that for a very small output buffer, we emit at most
  12681. * one empty block.
  12682. */
  12683. }
  12684. if (bstate === BS_BLOCK_DONE) {
  12685. if (flush === Z_PARTIAL_FLUSH) {
  12686. trees._tr_align(s);
  12687. }
  12688. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  12689. trees._tr_stored_block(s, 0, 0, false);
  12690. /* For a full flush, this empty block will be recognized
  12691. * as a special marker by inflate_sync().
  12692. */
  12693. if (flush === Z_FULL_FLUSH) {
  12694. /*** CLEAR_HASH(s); ***/ /* forget history */
  12695. zero(s.head); // Fill with NIL (= 0);
  12696. if (s.lookahead === 0) {
  12697. s.strstart = 0;
  12698. s.block_start = 0;
  12699. s.insert = 0;
  12700. }
  12701. }
  12702. }
  12703. flush_pending(strm);
  12704. if (strm.avail_out === 0) {
  12705. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  12706. return Z_OK;
  12707. }
  12708. }
  12709. }
  12710. //Assert(strm->avail_out > 0, "bug2");
  12711. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  12712. if (flush !== Z_FINISH) { return Z_OK; }
  12713. if (s.wrap <= 0) { return Z_STREAM_END; }
  12714. /* Write the trailer */
  12715. if (s.wrap === 2) {
  12716. put_byte(s, strm.adler & 0xff);
  12717. put_byte(s, (strm.adler >> 8) & 0xff);
  12718. put_byte(s, (strm.adler >> 16) & 0xff);
  12719. put_byte(s, (strm.adler >> 24) & 0xff);
  12720. put_byte(s, strm.total_in & 0xff);
  12721. put_byte(s, (strm.total_in >> 8) & 0xff);
  12722. put_byte(s, (strm.total_in >> 16) & 0xff);
  12723. put_byte(s, (strm.total_in >> 24) & 0xff);
  12724. }
  12725. else
  12726. {
  12727. putShortMSB(s, strm.adler >>> 16);
  12728. putShortMSB(s, strm.adler & 0xffff);
  12729. }
  12730. flush_pending(strm);
  12731. /* If avail_out is zero, the application will call deflate again
  12732. * to flush the rest.
  12733. */
  12734. if (s.wrap > 0) { s.wrap = -s.wrap; }
  12735. /* write the trailer only once! */
  12736. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  12737. }
  12738. function deflateEnd(strm) {
  12739. var status;
  12740. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  12741. return Z_STREAM_ERROR;
  12742. }
  12743. status = strm.state.status;
  12744. if (status !== INIT_STATE &&
  12745. status !== EXTRA_STATE &&
  12746. status !== NAME_STATE &&
  12747. status !== COMMENT_STATE &&
  12748. status !== HCRC_STATE &&
  12749. status !== BUSY_STATE &&
  12750. status !== FINISH_STATE
  12751. ) {
  12752. return err(strm, Z_STREAM_ERROR);
  12753. }
  12754. strm.state = null;
  12755. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  12756. }
  12757. /* =========================================================================
  12758. * Copy the source state to the destination state
  12759. */
  12760. //function deflateCopy(dest, source) {
  12761. //
  12762. //}
  12763. exports.deflateInit = deflateInit;
  12764. exports.deflateInit2 = deflateInit2;
  12765. exports.deflateReset = deflateReset;
  12766. exports.deflateResetKeep = deflateResetKeep;
  12767. exports.deflateSetHeader = deflateSetHeader;
  12768. exports.deflate = deflate;
  12769. exports.deflateEnd = deflateEnd;
  12770. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  12771. /* Not implemented
  12772. exports.deflateBound = deflateBound;
  12773. exports.deflateCopy = deflateCopy;
  12774. exports.deflateSetDictionary = deflateSetDictionary;
  12775. exports.deflateParams = deflateParams;
  12776. exports.deflatePending = deflatePending;
  12777. exports.deflatePrime = deflatePrime;
  12778. exports.deflateTune = deflateTune;
  12779. */
  12780. },{"../utils/common":39,"./adler32":41,"./crc32":43,"./messages":49,"./trees":50}],45:[function(require,module,exports){
  12781. 'use strict';
  12782. function GZheader() {
  12783. /* true if compressed data believed to be text */
  12784. this.text = 0;
  12785. /* modification time */
  12786. this.time = 0;
  12787. /* extra flags (not used when writing a gzip file) */
  12788. this.xflags = 0;
  12789. /* operating system */
  12790. this.os = 0;
  12791. /* pointer to extra field or Z_NULL if none */
  12792. this.extra = null;
  12793. /* extra field length (valid if extra != Z_NULL) */
  12794. this.extra_len = 0; // Actually, we don't need it in JS,
  12795. // but leave for few code modifications
  12796. //
  12797. // Setup limits is not necessary because in js we should not preallocate memory
  12798. // for inflate use constant limit in 65536 bytes
  12799. //
  12800. /* space at extra (only when reading header) */
  12801. // this.extra_max = 0;
  12802. /* pointer to zero-terminated file name or Z_NULL */
  12803. this.name = '';
  12804. /* space at name (only when reading header) */
  12805. // this.name_max = 0;
  12806. /* pointer to zero-terminated comment or Z_NULL */
  12807. this.comment = '';
  12808. /* space at comment (only when reading header) */
  12809. // this.comm_max = 0;
  12810. /* true if there was or will be a header crc */
  12811. this.hcrc = 0;
  12812. /* true when done reading gzip header (not used when writing a gzip file) */
  12813. this.done = false;
  12814. }
  12815. module.exports = GZheader;
  12816. },{}],46:[function(require,module,exports){
  12817. 'use strict';
  12818. // See state defs from inflate.js
  12819. var BAD = 30; /* got a data error -- remain here until reset */
  12820. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  12821. /*
  12822. Decode literal, length, and distance codes and write out the resulting
  12823. literal and match bytes until either not enough input or output is
  12824. available, an end-of-block is encountered, or a data error is encountered.
  12825. When large enough input and output buffers are supplied to inflate(), for
  12826. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  12827. inflate execution time is spent in this routine.
  12828. Entry assumptions:
  12829. state.mode === LEN
  12830. strm.avail_in >= 6
  12831. strm.avail_out >= 258
  12832. start >= strm.avail_out
  12833. state.bits < 8
  12834. On return, state.mode is one of:
  12835. LEN -- ran out of enough output space or enough available input
  12836. TYPE -- reached end of block code, inflate() to interpret next block
  12837. BAD -- error in block data
  12838. Notes:
  12839. - The maximum input bits used by a length/distance pair is 15 bits for the
  12840. length code, 5 bits for the length extra, 15 bits for the distance code,
  12841. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  12842. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  12843. checking for available input while decoding.
  12844. - The maximum bytes that a single length/distance pair can output is 258
  12845. bytes, which is the maximum length that can be coded. inflate_fast()
  12846. requires strm.avail_out >= 258 for each loop to avoid checking for
  12847. output space.
  12848. */
  12849. module.exports = function inflate_fast(strm, start) {
  12850. var state;
  12851. var _in; /* local strm.input */
  12852. var last; /* have enough input while in < last */
  12853. var _out; /* local strm.output */
  12854. var beg; /* inflate()'s initial strm.output */
  12855. var end; /* while out < end, enough space available */
  12856. //#ifdef INFLATE_STRICT
  12857. var dmax; /* maximum distance from zlib header */
  12858. //#endif
  12859. var wsize; /* window size or zero if not using window */
  12860. var whave; /* valid bytes in the window */
  12861. var wnext; /* window write index */
  12862. var window; /* allocated sliding window, if wsize != 0 */
  12863. var hold; /* local strm.hold */
  12864. var bits; /* local strm.bits */
  12865. var lcode; /* local strm.lencode */
  12866. var dcode; /* local strm.distcode */
  12867. var lmask; /* mask for first level of length codes */
  12868. var dmask; /* mask for first level of distance codes */
  12869. var here; /* retrieved table entry */
  12870. var op; /* code bits, operation, extra bits, or */
  12871. /* window position, window bytes to copy */
  12872. var len; /* match length, unused bytes */
  12873. var dist; /* match distance */
  12874. var from; /* where to copy match from */
  12875. var from_source;
  12876. var input, output; // JS specific, because we have no pointers
  12877. /* copy state to local variables */
  12878. state = strm.state;
  12879. //here = state.here;
  12880. _in = strm.next_in;
  12881. input = strm.input;
  12882. last = _in + (strm.avail_in - 5);
  12883. _out = strm.next_out;
  12884. output = strm.output;
  12885. beg = _out - (start - strm.avail_out);
  12886. end = _out + (strm.avail_out - 257);
  12887. //#ifdef INFLATE_STRICT
  12888. dmax = state.dmax;
  12889. //#endif
  12890. wsize = state.wsize;
  12891. whave = state.whave;
  12892. wnext = state.wnext;
  12893. window = state.window;
  12894. hold = state.hold;
  12895. bits = state.bits;
  12896. lcode = state.lencode;
  12897. dcode = state.distcode;
  12898. lmask = (1 << state.lenbits) - 1;
  12899. dmask = (1 << state.distbits) - 1;
  12900. /* decode literals and length/distances until end-of-block or not enough
  12901. input data or output space */
  12902. top:
  12903. do {
  12904. if (bits < 15) {
  12905. hold += input[_in++] << bits;
  12906. bits += 8;
  12907. hold += input[_in++] << bits;
  12908. bits += 8;
  12909. }
  12910. here = lcode[hold & lmask];
  12911. dolen:
  12912. for (;;) { // Goto emulation
  12913. op = here >>> 24/*here.bits*/;
  12914. hold >>>= op;
  12915. bits -= op;
  12916. op = (here >>> 16) & 0xff/*here.op*/;
  12917. if (op === 0) { /* literal */
  12918. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  12919. // "inflate: literal '%c'\n" :
  12920. // "inflate: literal 0x%02x\n", here.val));
  12921. output[_out++] = here & 0xffff/*here.val*/;
  12922. }
  12923. else if (op & 16) { /* length base */
  12924. len = here & 0xffff/*here.val*/;
  12925. op &= 15; /* number of extra bits */
  12926. if (op) {
  12927. if (bits < op) {
  12928. hold += input[_in++] << bits;
  12929. bits += 8;
  12930. }
  12931. len += hold & ((1 << op) - 1);
  12932. hold >>>= op;
  12933. bits -= op;
  12934. }
  12935. //Tracevv((stderr, "inflate: length %u\n", len));
  12936. if (bits < 15) {
  12937. hold += input[_in++] << bits;
  12938. bits += 8;
  12939. hold += input[_in++] << bits;
  12940. bits += 8;
  12941. }
  12942. here = dcode[hold & dmask];
  12943. dodist:
  12944. for (;;) { // goto emulation
  12945. op = here >>> 24/*here.bits*/;
  12946. hold >>>= op;
  12947. bits -= op;
  12948. op = (here >>> 16) & 0xff/*here.op*/;
  12949. if (op & 16) { /* distance base */
  12950. dist = here & 0xffff/*here.val*/;
  12951. op &= 15; /* number of extra bits */
  12952. if (bits < op) {
  12953. hold += input[_in++] << bits;
  12954. bits += 8;
  12955. if (bits < op) {
  12956. hold += input[_in++] << bits;
  12957. bits += 8;
  12958. }
  12959. }
  12960. dist += hold & ((1 << op) - 1);
  12961. //#ifdef INFLATE_STRICT
  12962. if (dist > dmax) {
  12963. strm.msg = 'invalid distance too far back';
  12964. state.mode = BAD;
  12965. break top;
  12966. }
  12967. //#endif
  12968. hold >>>= op;
  12969. bits -= op;
  12970. //Tracevv((stderr, "inflate: distance %u\n", dist));
  12971. op = _out - beg; /* max distance in output */
  12972. if (dist > op) { /* see if copy from window */
  12973. op = dist - op; /* distance back in window */
  12974. if (op > whave) {
  12975. if (state.sane) {
  12976. strm.msg = 'invalid distance too far back';
  12977. state.mode = BAD;
  12978. break top;
  12979. }
  12980. // (!) This block is disabled in zlib defailts,
  12981. // don't enable it for binary compatibility
  12982. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  12983. // if (len <= op - whave) {
  12984. // do {
  12985. // output[_out++] = 0;
  12986. // } while (--len);
  12987. // continue top;
  12988. // }
  12989. // len -= op - whave;
  12990. // do {
  12991. // output[_out++] = 0;
  12992. // } while (--op > whave);
  12993. // if (op === 0) {
  12994. // from = _out - dist;
  12995. // do {
  12996. // output[_out++] = output[from++];
  12997. // } while (--len);
  12998. // continue top;
  12999. // }
  13000. //#endif
  13001. }
  13002. from = 0; // window index
  13003. from_source = window;
  13004. if (wnext === 0) { /* very common case */
  13005. from += wsize - op;
  13006. if (op < len) { /* some from window */
  13007. len -= op;
  13008. do {
  13009. output[_out++] = window[from++];
  13010. } while (--op);
  13011. from = _out - dist; /* rest from output */
  13012. from_source = output;
  13013. }
  13014. }
  13015. else if (wnext < op) { /* wrap around window */
  13016. from += wsize + wnext - op;
  13017. op -= wnext;
  13018. if (op < len) { /* some from end of window */
  13019. len -= op;
  13020. do {
  13021. output[_out++] = window[from++];
  13022. } while (--op);
  13023. from = 0;
  13024. if (wnext < len) { /* some from start of window */
  13025. op = wnext;
  13026. len -= op;
  13027. do {
  13028. output[_out++] = window[from++];
  13029. } while (--op);
  13030. from = _out - dist; /* rest from output */
  13031. from_source = output;
  13032. }
  13033. }
  13034. }
  13035. else { /* contiguous in window */
  13036. from += wnext - op;
  13037. if (op < len) { /* some from window */
  13038. len -= op;
  13039. do {
  13040. output[_out++] = window[from++];
  13041. } while (--op);
  13042. from = _out - dist; /* rest from output */
  13043. from_source = output;
  13044. }
  13045. }
  13046. while (len > 2) {
  13047. output[_out++] = from_source[from++];
  13048. output[_out++] = from_source[from++];
  13049. output[_out++] = from_source[from++];
  13050. len -= 3;
  13051. }
  13052. if (len) {
  13053. output[_out++] = from_source[from++];
  13054. if (len > 1) {
  13055. output[_out++] = from_source[from++];
  13056. }
  13057. }
  13058. }
  13059. else {
  13060. from = _out - dist; /* copy direct from output */
  13061. do { /* minimum length is three */
  13062. output[_out++] = output[from++];
  13063. output[_out++] = output[from++];
  13064. output[_out++] = output[from++];
  13065. len -= 3;
  13066. } while (len > 2);
  13067. if (len) {
  13068. output[_out++] = output[from++];
  13069. if (len > 1) {
  13070. output[_out++] = output[from++];
  13071. }
  13072. }
  13073. }
  13074. }
  13075. else if ((op & 64) === 0) { /* 2nd level distance code */
  13076. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  13077. continue dodist;
  13078. }
  13079. else {
  13080. strm.msg = 'invalid distance code';
  13081. state.mode = BAD;
  13082. break top;
  13083. }
  13084. break; // need to emulate goto via "continue"
  13085. }
  13086. }
  13087. else if ((op & 64) === 0) { /* 2nd level length code */
  13088. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  13089. continue dolen;
  13090. }
  13091. else if (op & 32) { /* end-of-block */
  13092. //Tracevv((stderr, "inflate: end of block\n"));
  13093. state.mode = TYPE;
  13094. break top;
  13095. }
  13096. else {
  13097. strm.msg = 'invalid literal/length code';
  13098. state.mode = BAD;
  13099. break top;
  13100. }
  13101. break; // need to emulate goto via "continue"
  13102. }
  13103. } while (_in < last && _out < end);
  13104. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  13105. len = bits >> 3;
  13106. _in -= len;
  13107. bits -= len << 3;
  13108. hold &= (1 << bits) - 1;
  13109. /* update state and return */
  13110. strm.next_in = _in;
  13111. strm.next_out = _out;
  13112. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  13113. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  13114. state.hold = hold;
  13115. state.bits = bits;
  13116. return;
  13117. };
  13118. },{}],47:[function(require,module,exports){
  13119. 'use strict';
  13120. var utils = require('../utils/common');
  13121. var adler32 = require('./adler32');
  13122. var crc32 = require('./crc32');
  13123. var inflate_fast = require('./inffast');
  13124. var inflate_table = require('./inftrees');
  13125. var CODES = 0;
  13126. var LENS = 1;
  13127. var DISTS = 2;
  13128. /* Public constants ==========================================================*/
  13129. /* ===========================================================================*/
  13130. /* Allowed flush values; see deflate() and inflate() below for details */
  13131. //var Z_NO_FLUSH = 0;
  13132. //var Z_PARTIAL_FLUSH = 1;
  13133. //var Z_SYNC_FLUSH = 2;
  13134. //var Z_FULL_FLUSH = 3;
  13135. var Z_FINISH = 4;
  13136. var Z_BLOCK = 5;
  13137. var Z_TREES = 6;
  13138. /* Return codes for the compression/decompression functions. Negative values
  13139. * are errors, positive values are used for special but normal events.
  13140. */
  13141. var Z_OK = 0;
  13142. var Z_STREAM_END = 1;
  13143. var Z_NEED_DICT = 2;
  13144. //var Z_ERRNO = -1;
  13145. var Z_STREAM_ERROR = -2;
  13146. var Z_DATA_ERROR = -3;
  13147. var Z_MEM_ERROR = -4;
  13148. var Z_BUF_ERROR = -5;
  13149. //var Z_VERSION_ERROR = -6;
  13150. /* The deflate compression method */
  13151. var Z_DEFLATED = 8;
  13152. /* STATES ====================================================================*/
  13153. /* ===========================================================================*/
  13154. var HEAD = 1; /* i: waiting for magic header */
  13155. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  13156. var TIME = 3; /* i: waiting for modification time (gzip) */
  13157. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  13158. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  13159. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  13160. var NAME = 7; /* i: waiting for end of file name (gzip) */
  13161. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  13162. var HCRC = 9; /* i: waiting for header crc (gzip) */
  13163. var DICTID = 10; /* i: waiting for dictionary check value */
  13164. var DICT = 11; /* waiting for inflateSetDictionary() call */
  13165. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  13166. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  13167. var STORED = 14; /* i: waiting for stored size (length and complement) */
  13168. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  13169. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  13170. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  13171. var LENLENS = 18; /* i: waiting for code length code lengths */
  13172. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  13173. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  13174. var LEN = 21; /* i: waiting for length/lit/eob code */
  13175. var LENEXT = 22; /* i: waiting for length extra bits */
  13176. var DIST = 23; /* i: waiting for distance code */
  13177. var DISTEXT = 24; /* i: waiting for distance extra bits */
  13178. var MATCH = 25; /* o: waiting for output space to copy string */
  13179. var LIT = 26; /* o: waiting for output space to write literal */
  13180. var CHECK = 27; /* i: waiting for 32-bit check value */
  13181. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  13182. var DONE = 29; /* finished check, done -- remain here until reset */
  13183. var BAD = 30; /* got a data error -- remain here until reset */
  13184. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  13185. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  13186. /* ===========================================================================*/
  13187. var ENOUGH_LENS = 852;
  13188. var ENOUGH_DISTS = 592;
  13189. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  13190. var MAX_WBITS = 15;
  13191. /* 32K LZ77 window */
  13192. var DEF_WBITS = MAX_WBITS;
  13193. function ZSWAP32(q) {
  13194. return (((q >>> 24) & 0xff) +
  13195. ((q >>> 8) & 0xff00) +
  13196. ((q & 0xff00) << 8) +
  13197. ((q & 0xff) << 24));
  13198. }
  13199. function InflateState() {
  13200. this.mode = 0; /* current inflate mode */
  13201. this.last = false; /* true if processing last block */
  13202. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  13203. this.havedict = false; /* true if dictionary provided */
  13204. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  13205. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  13206. this.check = 0; /* protected copy of check value */
  13207. this.total = 0; /* protected copy of output count */
  13208. // TODO: may be {}
  13209. this.head = null; /* where to save gzip header information */
  13210. /* sliding window */
  13211. this.wbits = 0; /* log base 2 of requested window size */
  13212. this.wsize = 0; /* window size or zero if not using window */
  13213. this.whave = 0; /* valid bytes in the window */
  13214. this.wnext = 0; /* window write index */
  13215. this.window = null; /* allocated sliding window, if needed */
  13216. /* bit accumulator */
  13217. this.hold = 0; /* input bit accumulator */
  13218. this.bits = 0; /* number of bits in "in" */
  13219. /* for string and stored block copying */
  13220. this.length = 0; /* literal or length of data to copy */
  13221. this.offset = 0; /* distance back to copy string from */
  13222. /* for table and code decoding */
  13223. this.extra = 0; /* extra bits needed */
  13224. /* fixed and dynamic code tables */
  13225. this.lencode = null; /* starting table for length/literal codes */
  13226. this.distcode = null; /* starting table for distance codes */
  13227. this.lenbits = 0; /* index bits for lencode */
  13228. this.distbits = 0; /* index bits for distcode */
  13229. /* dynamic table building */
  13230. this.ncode = 0; /* number of code length code lengths */
  13231. this.nlen = 0; /* number of length code lengths */
  13232. this.ndist = 0; /* number of distance code lengths */
  13233. this.have = 0; /* number of code lengths in lens[] */
  13234. this.next = null; /* next available space in codes[] */
  13235. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  13236. this.work = new utils.Buf16(288); /* work area for code table building */
  13237. /*
  13238. because we don't have pointers in js, we use lencode and distcode directly
  13239. as buffers so we don't need codes
  13240. */
  13241. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  13242. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  13243. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  13244. this.sane = 0; /* if false, allow invalid distance too far */
  13245. this.back = 0; /* bits back of last unprocessed length/lit */
  13246. this.was = 0; /* initial length of match */
  13247. }
  13248. function inflateResetKeep(strm) {
  13249. var state;
  13250. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  13251. state = strm.state;
  13252. strm.total_in = strm.total_out = state.total = 0;
  13253. strm.msg = ''; /*Z_NULL*/
  13254. if (state.wrap) { /* to support ill-conceived Java test suite */
  13255. strm.adler = state.wrap & 1;
  13256. }
  13257. state.mode = HEAD;
  13258. state.last = 0;
  13259. state.havedict = 0;
  13260. state.dmax = 32768;
  13261. state.head = null/*Z_NULL*/;
  13262. state.hold = 0;
  13263. state.bits = 0;
  13264. //state.lencode = state.distcode = state.next = state.codes;
  13265. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  13266. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  13267. state.sane = 1;
  13268. state.back = -1;
  13269. //Tracev((stderr, "inflate: reset\n"));
  13270. return Z_OK;
  13271. }
  13272. function inflateReset(strm) {
  13273. var state;
  13274. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  13275. state = strm.state;
  13276. state.wsize = 0;
  13277. state.whave = 0;
  13278. state.wnext = 0;
  13279. return inflateResetKeep(strm);
  13280. }
  13281. function inflateReset2(strm, windowBits) {
  13282. var wrap;
  13283. var state;
  13284. /* get the state */
  13285. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  13286. state = strm.state;
  13287. /* extract wrap request from windowBits parameter */
  13288. if (windowBits < 0) {
  13289. wrap = 0;
  13290. windowBits = -windowBits;
  13291. }
  13292. else {
  13293. wrap = (windowBits >> 4) + 1;
  13294. if (windowBits < 48) {
  13295. windowBits &= 15;
  13296. }
  13297. }
  13298. /* set number of window bits, free window if different */
  13299. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  13300. return Z_STREAM_ERROR;
  13301. }
  13302. if (state.window !== null && state.wbits !== windowBits) {
  13303. state.window = null;
  13304. }
  13305. /* update state and reset the rest of it */
  13306. state.wrap = wrap;
  13307. state.wbits = windowBits;
  13308. return inflateReset(strm);
  13309. }
  13310. function inflateInit2(strm, windowBits) {
  13311. var ret;
  13312. var state;
  13313. if (!strm) { return Z_STREAM_ERROR; }
  13314. //strm.msg = Z_NULL; /* in case we return an error */
  13315. state = new InflateState();
  13316. //if (state === Z_NULL) return Z_MEM_ERROR;
  13317. //Tracev((stderr, "inflate: allocated\n"));
  13318. strm.state = state;
  13319. state.window = null/*Z_NULL*/;
  13320. ret = inflateReset2(strm, windowBits);
  13321. if (ret !== Z_OK) {
  13322. strm.state = null/*Z_NULL*/;
  13323. }
  13324. return ret;
  13325. }
  13326. function inflateInit(strm) {
  13327. return inflateInit2(strm, DEF_WBITS);
  13328. }
  13329. /*
  13330. Return state with length and distance decoding tables and index sizes set to
  13331. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  13332. If BUILDFIXED is defined, then instead this routine builds the tables the
  13333. first time it's called, and returns those tables the first time and
  13334. thereafter. This reduces the size of the code by about 2K bytes, in
  13335. exchange for a little execution time. However, BUILDFIXED should not be
  13336. used for threaded applications, since the rewriting of the tables and virgin
  13337. may not be thread-safe.
  13338. */
  13339. var virgin = true;
  13340. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  13341. function fixedtables(state) {
  13342. /* build fixed huffman tables if first call (may not be thread safe) */
  13343. if (virgin) {
  13344. var sym;
  13345. lenfix = new utils.Buf32(512);
  13346. distfix = new utils.Buf32(32);
  13347. /* literal/length table */
  13348. sym = 0;
  13349. while (sym < 144) { state.lens[sym++] = 8; }
  13350. while (sym < 256) { state.lens[sym++] = 9; }
  13351. while (sym < 280) { state.lens[sym++] = 7; }
  13352. while (sym < 288) { state.lens[sym++] = 8; }
  13353. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  13354. /* distance table */
  13355. sym = 0;
  13356. while (sym < 32) { state.lens[sym++] = 5; }
  13357. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  13358. /* do this just once */
  13359. virgin = false;
  13360. }
  13361. state.lencode = lenfix;
  13362. state.lenbits = 9;
  13363. state.distcode = distfix;
  13364. state.distbits = 5;
  13365. }
  13366. /*
  13367. Update the window with the last wsize (normally 32K) bytes written before
  13368. returning. If window does not exist yet, create it. This is only called
  13369. when a window is already in use, or when output has been written during this
  13370. inflate call, but the end of the deflate stream has not been reached yet.
  13371. It is also called to create a window for dictionary data when a dictionary
  13372. is loaded.
  13373. Providing output buffers larger than 32K to inflate() should provide a speed
  13374. advantage, since only the last 32K of output is copied to the sliding window
  13375. upon return from inflate(), and since all distances after the first 32K of
  13376. output will fall in the output data, making match copies simpler and faster.
  13377. The advantage may be dependent on the size of the processor's data caches.
  13378. */
  13379. function updatewindow(strm, src, end, copy) {
  13380. var dist;
  13381. var state = strm.state;
  13382. /* if it hasn't been done already, allocate space for the window */
  13383. if (state.window === null) {
  13384. state.wsize = 1 << state.wbits;
  13385. state.wnext = 0;
  13386. state.whave = 0;
  13387. state.window = new utils.Buf8(state.wsize);
  13388. }
  13389. /* copy state->wsize or less output bytes into the circular window */
  13390. if (copy >= state.wsize) {
  13391. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  13392. state.wnext = 0;
  13393. state.whave = state.wsize;
  13394. }
  13395. else {
  13396. dist = state.wsize - state.wnext;
  13397. if (dist > copy) {
  13398. dist = copy;
  13399. }
  13400. //zmemcpy(state->window + state->wnext, end - copy, dist);
  13401. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  13402. copy -= dist;
  13403. if (copy) {
  13404. //zmemcpy(state->window, end - copy, copy);
  13405. utils.arraySet(state.window,src, end - copy, copy, 0);
  13406. state.wnext = copy;
  13407. state.whave = state.wsize;
  13408. }
  13409. else {
  13410. state.wnext += dist;
  13411. if (state.wnext === state.wsize) { state.wnext = 0; }
  13412. if (state.whave < state.wsize) { state.whave += dist; }
  13413. }
  13414. }
  13415. return 0;
  13416. }
  13417. function inflate(strm, flush) {
  13418. var state;
  13419. var input, output; // input/output buffers
  13420. var next; /* next input INDEX */
  13421. var put; /* next output INDEX */
  13422. var have, left; /* available input and output */
  13423. var hold; /* bit buffer */
  13424. var bits; /* bits in bit buffer */
  13425. var _in, _out; /* save starting available input and output */
  13426. var copy; /* number of stored or match bytes to copy */
  13427. var from; /* where to copy match bytes from */
  13428. var from_source;
  13429. var here = 0; /* current decoding table entry */
  13430. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  13431. //var last; /* parent table entry */
  13432. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  13433. var len; /* length to copy for repeats, bits to drop */
  13434. var ret; /* return code */
  13435. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  13436. var opts;
  13437. var n; // temporary var for NEED_BITS
  13438. var order = /* permutation of code lengths */
  13439. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  13440. if (!strm || !strm.state || !strm.output ||
  13441. (!strm.input && strm.avail_in !== 0)) {
  13442. return Z_STREAM_ERROR;
  13443. }
  13444. state = strm.state;
  13445. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  13446. //--- LOAD() ---
  13447. put = strm.next_out;
  13448. output = strm.output;
  13449. left = strm.avail_out;
  13450. next = strm.next_in;
  13451. input = strm.input;
  13452. have = strm.avail_in;
  13453. hold = state.hold;
  13454. bits = state.bits;
  13455. //---
  13456. _in = have;
  13457. _out = left;
  13458. ret = Z_OK;
  13459. inf_leave: // goto emulation
  13460. for (;;) {
  13461. switch (state.mode) {
  13462. case HEAD:
  13463. if (state.wrap === 0) {
  13464. state.mode = TYPEDO;
  13465. break;
  13466. }
  13467. //=== NEEDBITS(16);
  13468. while (bits < 16) {
  13469. if (have === 0) { break inf_leave; }
  13470. have--;
  13471. hold += input[next++] << bits;
  13472. bits += 8;
  13473. }
  13474. //===//
  13475. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  13476. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  13477. //=== CRC2(state.check, hold);
  13478. hbuf[0] = hold & 0xff;
  13479. hbuf[1] = (hold >>> 8) & 0xff;
  13480. state.check = crc32(state.check, hbuf, 2, 0);
  13481. //===//
  13482. //=== INITBITS();
  13483. hold = 0;
  13484. bits = 0;
  13485. //===//
  13486. state.mode = FLAGS;
  13487. break;
  13488. }
  13489. state.flags = 0; /* expect zlib header */
  13490. if (state.head) {
  13491. state.head.done = false;
  13492. }
  13493. if (!(state.wrap & 1) || /* check if zlib header allowed */
  13494. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  13495. strm.msg = 'incorrect header check';
  13496. state.mode = BAD;
  13497. break;
  13498. }
  13499. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  13500. strm.msg = 'unknown compression method';
  13501. state.mode = BAD;
  13502. break;
  13503. }
  13504. //--- DROPBITS(4) ---//
  13505. hold >>>= 4;
  13506. bits -= 4;
  13507. //---//
  13508. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  13509. if (state.wbits === 0) {
  13510. state.wbits = len;
  13511. }
  13512. else if (len > state.wbits) {
  13513. strm.msg = 'invalid window size';
  13514. state.mode = BAD;
  13515. break;
  13516. }
  13517. state.dmax = 1 << len;
  13518. //Tracev((stderr, "inflate: zlib header ok\n"));
  13519. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  13520. state.mode = hold & 0x200 ? DICTID : TYPE;
  13521. //=== INITBITS();
  13522. hold = 0;
  13523. bits = 0;
  13524. //===//
  13525. break;
  13526. case FLAGS:
  13527. //=== NEEDBITS(16); */
  13528. while (bits < 16) {
  13529. if (have === 0) { break inf_leave; }
  13530. have--;
  13531. hold += input[next++] << bits;
  13532. bits += 8;
  13533. }
  13534. //===//
  13535. state.flags = hold;
  13536. if ((state.flags & 0xff) !== Z_DEFLATED) {
  13537. strm.msg = 'unknown compression method';
  13538. state.mode = BAD;
  13539. break;
  13540. }
  13541. if (state.flags & 0xe000) {
  13542. strm.msg = 'unknown header flags set';
  13543. state.mode = BAD;
  13544. break;
  13545. }
  13546. if (state.head) {
  13547. state.head.text = ((hold >> 8) & 1);
  13548. }
  13549. if (state.flags & 0x0200) {
  13550. //=== CRC2(state.check, hold);
  13551. hbuf[0] = hold & 0xff;
  13552. hbuf[1] = (hold >>> 8) & 0xff;
  13553. state.check = crc32(state.check, hbuf, 2, 0);
  13554. //===//
  13555. }
  13556. //=== INITBITS();
  13557. hold = 0;
  13558. bits = 0;
  13559. //===//
  13560. state.mode = TIME;
  13561. /* falls through */
  13562. case TIME:
  13563. //=== NEEDBITS(32); */
  13564. while (bits < 32) {
  13565. if (have === 0) { break inf_leave; }
  13566. have--;
  13567. hold += input[next++] << bits;
  13568. bits += 8;
  13569. }
  13570. //===//
  13571. if (state.head) {
  13572. state.head.time = hold;
  13573. }
  13574. if (state.flags & 0x0200) {
  13575. //=== CRC4(state.check, hold)
  13576. hbuf[0] = hold & 0xff;
  13577. hbuf[1] = (hold >>> 8) & 0xff;
  13578. hbuf[2] = (hold >>> 16) & 0xff;
  13579. hbuf[3] = (hold >>> 24) & 0xff;
  13580. state.check = crc32(state.check, hbuf, 4, 0);
  13581. //===
  13582. }
  13583. //=== INITBITS();
  13584. hold = 0;
  13585. bits = 0;
  13586. //===//
  13587. state.mode = OS;
  13588. /* falls through */
  13589. case OS:
  13590. //=== NEEDBITS(16); */
  13591. while (bits < 16) {
  13592. if (have === 0) { break inf_leave; }
  13593. have--;
  13594. hold += input[next++] << bits;
  13595. bits += 8;
  13596. }
  13597. //===//
  13598. if (state.head) {
  13599. state.head.xflags = (hold & 0xff);
  13600. state.head.os = (hold >> 8);
  13601. }
  13602. if (state.flags & 0x0200) {
  13603. //=== CRC2(state.check, hold);
  13604. hbuf[0] = hold & 0xff;
  13605. hbuf[1] = (hold >>> 8) & 0xff;
  13606. state.check = crc32(state.check, hbuf, 2, 0);
  13607. //===//
  13608. }
  13609. //=== INITBITS();
  13610. hold = 0;
  13611. bits = 0;
  13612. //===//
  13613. state.mode = EXLEN;
  13614. /* falls through */
  13615. case EXLEN:
  13616. if (state.flags & 0x0400) {
  13617. //=== NEEDBITS(16); */
  13618. while (bits < 16) {
  13619. if (have === 0) { break inf_leave; }
  13620. have--;
  13621. hold += input[next++] << bits;
  13622. bits += 8;
  13623. }
  13624. //===//
  13625. state.length = hold;
  13626. if (state.head) {
  13627. state.head.extra_len = hold;
  13628. }
  13629. if (state.flags & 0x0200) {
  13630. //=== CRC2(state.check, hold);
  13631. hbuf[0] = hold & 0xff;
  13632. hbuf[1] = (hold >>> 8) & 0xff;
  13633. state.check = crc32(state.check, hbuf, 2, 0);
  13634. //===//
  13635. }
  13636. //=== INITBITS();
  13637. hold = 0;
  13638. bits = 0;
  13639. //===//
  13640. }
  13641. else if (state.head) {
  13642. state.head.extra = null/*Z_NULL*/;
  13643. }
  13644. state.mode = EXTRA;
  13645. /* falls through */
  13646. case EXTRA:
  13647. if (state.flags & 0x0400) {
  13648. copy = state.length;
  13649. if (copy > have) { copy = have; }
  13650. if (copy) {
  13651. if (state.head) {
  13652. len = state.head.extra_len - state.length;
  13653. if (!state.head.extra) {
  13654. // Use untyped array for more conveniend processing later
  13655. state.head.extra = new Array(state.head.extra_len);
  13656. }
  13657. utils.arraySet(
  13658. state.head.extra,
  13659. input,
  13660. next,
  13661. // extra field is limited to 65536 bytes
  13662. // - no need for additional size check
  13663. copy,
  13664. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  13665. len
  13666. );
  13667. //zmemcpy(state.head.extra + len, next,
  13668. // len + copy > state.head.extra_max ?
  13669. // state.head.extra_max - len : copy);
  13670. }
  13671. if (state.flags & 0x0200) {
  13672. state.check = crc32(state.check, input, copy, next);
  13673. }
  13674. have -= copy;
  13675. next += copy;
  13676. state.length -= copy;
  13677. }
  13678. if (state.length) { break inf_leave; }
  13679. }
  13680. state.length = 0;
  13681. state.mode = NAME;
  13682. /* falls through */
  13683. case NAME:
  13684. if (state.flags & 0x0800) {
  13685. if (have === 0) { break inf_leave; }
  13686. copy = 0;
  13687. do {
  13688. // TODO: 2 or 1 bytes?
  13689. len = input[next + copy++];
  13690. /* use constant limit because in js we should not preallocate memory */
  13691. if (state.head && len &&
  13692. (state.length < 65536 /*state.head.name_max*/)) {
  13693. state.head.name += String.fromCharCode(len);
  13694. }
  13695. } while (len && copy < have);
  13696. if (state.flags & 0x0200) {
  13697. state.check = crc32(state.check, input, copy, next);
  13698. }
  13699. have -= copy;
  13700. next += copy;
  13701. if (len) { break inf_leave; }
  13702. }
  13703. else if (state.head) {
  13704. state.head.name = null;
  13705. }
  13706. state.length = 0;
  13707. state.mode = COMMENT;
  13708. /* falls through */
  13709. case COMMENT:
  13710. if (state.flags & 0x1000) {
  13711. if (have === 0) { break inf_leave; }
  13712. copy = 0;
  13713. do {
  13714. len = input[next + copy++];
  13715. /* use constant limit because in js we should not preallocate memory */
  13716. if (state.head && len &&
  13717. (state.length < 65536 /*state.head.comm_max*/)) {
  13718. state.head.comment += String.fromCharCode(len);
  13719. }
  13720. } while (len && copy < have);
  13721. if (state.flags & 0x0200) {
  13722. state.check = crc32(state.check, input, copy, next);
  13723. }
  13724. have -= copy;
  13725. next += copy;
  13726. if (len) { break inf_leave; }
  13727. }
  13728. else if (state.head) {
  13729. state.head.comment = null;
  13730. }
  13731. state.mode = HCRC;
  13732. /* falls through */
  13733. case HCRC:
  13734. if (state.flags & 0x0200) {
  13735. //=== NEEDBITS(16); */
  13736. while (bits < 16) {
  13737. if (have === 0) { break inf_leave; }
  13738. have--;
  13739. hold += input[next++] << bits;
  13740. bits += 8;
  13741. }
  13742. //===//
  13743. if (hold !== (state.check & 0xffff)) {
  13744. strm.msg = 'header crc mismatch';
  13745. state.mode = BAD;
  13746. break;
  13747. }
  13748. //=== INITBITS();
  13749. hold = 0;
  13750. bits = 0;
  13751. //===//
  13752. }
  13753. if (state.head) {
  13754. state.head.hcrc = ((state.flags >> 9) & 1);
  13755. state.head.done = true;
  13756. }
  13757. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  13758. state.mode = TYPE;
  13759. break;
  13760. case DICTID:
  13761. //=== NEEDBITS(32); */
  13762. while (bits < 32) {
  13763. if (have === 0) { break inf_leave; }
  13764. have--;
  13765. hold += input[next++] << bits;
  13766. bits += 8;
  13767. }
  13768. //===//
  13769. strm.adler = state.check = ZSWAP32(hold);
  13770. //=== INITBITS();
  13771. hold = 0;
  13772. bits = 0;
  13773. //===//
  13774. state.mode = DICT;
  13775. /* falls through */
  13776. case DICT:
  13777. if (state.havedict === 0) {
  13778. //--- RESTORE() ---
  13779. strm.next_out = put;
  13780. strm.avail_out = left;
  13781. strm.next_in = next;
  13782. strm.avail_in = have;
  13783. state.hold = hold;
  13784. state.bits = bits;
  13785. //---
  13786. return Z_NEED_DICT;
  13787. }
  13788. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  13789. state.mode = TYPE;
  13790. /* falls through */
  13791. case TYPE:
  13792. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  13793. /* falls through */
  13794. case TYPEDO:
  13795. if (state.last) {
  13796. //--- BYTEBITS() ---//
  13797. hold >>>= bits & 7;
  13798. bits -= bits & 7;
  13799. //---//
  13800. state.mode = CHECK;
  13801. break;
  13802. }
  13803. //=== NEEDBITS(3); */
  13804. while (bits < 3) {
  13805. if (have === 0) { break inf_leave; }
  13806. have--;
  13807. hold += input[next++] << bits;
  13808. bits += 8;
  13809. }
  13810. //===//
  13811. state.last = (hold & 0x01)/*BITS(1)*/;
  13812. //--- DROPBITS(1) ---//
  13813. hold >>>= 1;
  13814. bits -= 1;
  13815. //---//
  13816. switch ((hold & 0x03)/*BITS(2)*/) {
  13817. case 0: /* stored block */
  13818. //Tracev((stderr, "inflate: stored block%s\n",
  13819. // state.last ? " (last)" : ""));
  13820. state.mode = STORED;
  13821. break;
  13822. case 1: /* fixed block */
  13823. fixedtables(state);
  13824. //Tracev((stderr, "inflate: fixed codes block%s\n",
  13825. // state.last ? " (last)" : ""));
  13826. state.mode = LEN_; /* decode codes */
  13827. if (flush === Z_TREES) {
  13828. //--- DROPBITS(2) ---//
  13829. hold >>>= 2;
  13830. bits -= 2;
  13831. //---//
  13832. break inf_leave;
  13833. }
  13834. break;
  13835. case 2: /* dynamic block */
  13836. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  13837. // state.last ? " (last)" : ""));
  13838. state.mode = TABLE;
  13839. break;
  13840. case 3:
  13841. strm.msg = 'invalid block type';
  13842. state.mode = BAD;
  13843. }
  13844. //--- DROPBITS(2) ---//
  13845. hold >>>= 2;
  13846. bits -= 2;
  13847. //---//
  13848. break;
  13849. case STORED:
  13850. //--- BYTEBITS() ---// /* go to byte boundary */
  13851. hold >>>= bits & 7;
  13852. bits -= bits & 7;
  13853. //---//
  13854. //=== NEEDBITS(32); */
  13855. while (bits < 32) {
  13856. if (have === 0) { break inf_leave; }
  13857. have--;
  13858. hold += input[next++] << bits;
  13859. bits += 8;
  13860. }
  13861. //===//
  13862. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  13863. strm.msg = 'invalid stored block lengths';
  13864. state.mode = BAD;
  13865. break;
  13866. }
  13867. state.length = hold & 0xffff;
  13868. //Tracev((stderr, "inflate: stored length %u\n",
  13869. // state.length));
  13870. //=== INITBITS();
  13871. hold = 0;
  13872. bits = 0;
  13873. //===//
  13874. state.mode = COPY_;
  13875. if (flush === Z_TREES) { break inf_leave; }
  13876. /* falls through */
  13877. case COPY_:
  13878. state.mode = COPY;
  13879. /* falls through */
  13880. case COPY:
  13881. copy = state.length;
  13882. if (copy) {
  13883. if (copy > have) { copy = have; }
  13884. if (copy > left) { copy = left; }
  13885. if (copy === 0) { break inf_leave; }
  13886. //--- zmemcpy(put, next, copy); ---
  13887. utils.arraySet(output, input, next, copy, put);
  13888. //---//
  13889. have -= copy;
  13890. next += copy;
  13891. left -= copy;
  13892. put += copy;
  13893. state.length -= copy;
  13894. break;
  13895. }
  13896. //Tracev((stderr, "inflate: stored end\n"));
  13897. state.mode = TYPE;
  13898. break;
  13899. case TABLE:
  13900. //=== NEEDBITS(14); */
  13901. while (bits < 14) {
  13902. if (have === 0) { break inf_leave; }
  13903. have--;
  13904. hold += input[next++] << bits;
  13905. bits += 8;
  13906. }
  13907. //===//
  13908. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  13909. //--- DROPBITS(5) ---//
  13910. hold >>>= 5;
  13911. bits -= 5;
  13912. //---//
  13913. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  13914. //--- DROPBITS(5) ---//
  13915. hold >>>= 5;
  13916. bits -= 5;
  13917. //---//
  13918. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  13919. //--- DROPBITS(4) ---//
  13920. hold >>>= 4;
  13921. bits -= 4;
  13922. //---//
  13923. //#ifndef PKZIP_BUG_WORKAROUND
  13924. if (state.nlen > 286 || state.ndist > 30) {
  13925. strm.msg = 'too many length or distance symbols';
  13926. state.mode = BAD;
  13927. break;
  13928. }
  13929. //#endif
  13930. //Tracev((stderr, "inflate: table sizes ok\n"));
  13931. state.have = 0;
  13932. state.mode = LENLENS;
  13933. /* falls through */
  13934. case LENLENS:
  13935. while (state.have < state.ncode) {
  13936. //=== NEEDBITS(3);
  13937. while (bits < 3) {
  13938. if (have === 0) { break inf_leave; }
  13939. have--;
  13940. hold += input[next++] << bits;
  13941. bits += 8;
  13942. }
  13943. //===//
  13944. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  13945. //--- DROPBITS(3) ---//
  13946. hold >>>= 3;
  13947. bits -= 3;
  13948. //---//
  13949. }
  13950. while (state.have < 19) {
  13951. state.lens[order[state.have++]] = 0;
  13952. }
  13953. // We have separate tables & no pointers. 2 commented lines below not needed.
  13954. //state.next = state.codes;
  13955. //state.lencode = state.next;
  13956. // Switch to use dynamic table
  13957. state.lencode = state.lendyn;
  13958. state.lenbits = 7;
  13959. opts = {bits: state.lenbits};
  13960. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  13961. state.lenbits = opts.bits;
  13962. if (ret) {
  13963. strm.msg = 'invalid code lengths set';
  13964. state.mode = BAD;
  13965. break;
  13966. }
  13967. //Tracev((stderr, "inflate: code lengths ok\n"));
  13968. state.have = 0;
  13969. state.mode = CODELENS;
  13970. /* falls through */
  13971. case CODELENS:
  13972. while (state.have < state.nlen + state.ndist) {
  13973. for (;;) {
  13974. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  13975. here_bits = here >>> 24;
  13976. here_op = (here >>> 16) & 0xff;
  13977. here_val = here & 0xffff;
  13978. if ((here_bits) <= bits) { break; }
  13979. //--- PULLBYTE() ---//
  13980. if (have === 0) { break inf_leave; }
  13981. have--;
  13982. hold += input[next++] << bits;
  13983. bits += 8;
  13984. //---//
  13985. }
  13986. if (here_val < 16) {
  13987. //--- DROPBITS(here.bits) ---//
  13988. hold >>>= here_bits;
  13989. bits -= here_bits;
  13990. //---//
  13991. state.lens[state.have++] = here_val;
  13992. }
  13993. else {
  13994. if (here_val === 16) {
  13995. //=== NEEDBITS(here.bits + 2);
  13996. n = here_bits + 2;
  13997. while (bits < n) {
  13998. if (have === 0) { break inf_leave; }
  13999. have--;
  14000. hold += input[next++] << bits;
  14001. bits += 8;
  14002. }
  14003. //===//
  14004. //--- DROPBITS(here.bits) ---//
  14005. hold >>>= here_bits;
  14006. bits -= here_bits;
  14007. //---//
  14008. if (state.have === 0) {
  14009. strm.msg = 'invalid bit length repeat';
  14010. state.mode = BAD;
  14011. break;
  14012. }
  14013. len = state.lens[state.have - 1];
  14014. copy = 3 + (hold & 0x03);//BITS(2);
  14015. //--- DROPBITS(2) ---//
  14016. hold >>>= 2;
  14017. bits -= 2;
  14018. //---//
  14019. }
  14020. else if (here_val === 17) {
  14021. //=== NEEDBITS(here.bits + 3);
  14022. n = here_bits + 3;
  14023. while (bits < n) {
  14024. if (have === 0) { break inf_leave; }
  14025. have--;
  14026. hold += input[next++] << bits;
  14027. bits += 8;
  14028. }
  14029. //===//
  14030. //--- DROPBITS(here.bits) ---//
  14031. hold >>>= here_bits;
  14032. bits -= here_bits;
  14033. //---//
  14034. len = 0;
  14035. copy = 3 + (hold & 0x07);//BITS(3);
  14036. //--- DROPBITS(3) ---//
  14037. hold >>>= 3;
  14038. bits -= 3;
  14039. //---//
  14040. }
  14041. else {
  14042. //=== NEEDBITS(here.bits + 7);
  14043. n = here_bits + 7;
  14044. while (bits < n) {
  14045. if (have === 0) { break inf_leave; }
  14046. have--;
  14047. hold += input[next++] << bits;
  14048. bits += 8;
  14049. }
  14050. //===//
  14051. //--- DROPBITS(here.bits) ---//
  14052. hold >>>= here_bits;
  14053. bits -= here_bits;
  14054. //---//
  14055. len = 0;
  14056. copy = 11 + (hold & 0x7f);//BITS(7);
  14057. //--- DROPBITS(7) ---//
  14058. hold >>>= 7;
  14059. bits -= 7;
  14060. //---//
  14061. }
  14062. if (state.have + copy > state.nlen + state.ndist) {
  14063. strm.msg = 'invalid bit length repeat';
  14064. state.mode = BAD;
  14065. break;
  14066. }
  14067. while (copy--) {
  14068. state.lens[state.have++] = len;
  14069. }
  14070. }
  14071. }
  14072. /* handle error breaks in while */
  14073. if (state.mode === BAD) { break; }
  14074. /* check for end-of-block code (better have one) */
  14075. if (state.lens[256] === 0) {
  14076. strm.msg = 'invalid code -- missing end-of-block';
  14077. state.mode = BAD;
  14078. break;
  14079. }
  14080. /* build code tables -- note: do not change the lenbits or distbits
  14081. values here (9 and 6) without reading the comments in inftrees.h
  14082. concerning the ENOUGH constants, which depend on those values */
  14083. state.lenbits = 9;
  14084. opts = {bits: state.lenbits};
  14085. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  14086. // We have separate tables & no pointers. 2 commented lines below not needed.
  14087. // state.next_index = opts.table_index;
  14088. state.lenbits = opts.bits;
  14089. // state.lencode = state.next;
  14090. if (ret) {
  14091. strm.msg = 'invalid literal/lengths set';
  14092. state.mode = BAD;
  14093. break;
  14094. }
  14095. state.distbits = 6;
  14096. //state.distcode.copy(state.codes);
  14097. // Switch to use dynamic table
  14098. state.distcode = state.distdyn;
  14099. opts = {bits: state.distbits};
  14100. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  14101. // We have separate tables & no pointers. 2 commented lines below not needed.
  14102. // state.next_index = opts.table_index;
  14103. state.distbits = opts.bits;
  14104. // state.distcode = state.next;
  14105. if (ret) {
  14106. strm.msg = 'invalid distances set';
  14107. state.mode = BAD;
  14108. break;
  14109. }
  14110. //Tracev((stderr, 'inflate: codes ok\n'));
  14111. state.mode = LEN_;
  14112. if (flush === Z_TREES) { break inf_leave; }
  14113. /* falls through */
  14114. case LEN_:
  14115. state.mode = LEN;
  14116. /* falls through */
  14117. case LEN:
  14118. if (have >= 6 && left >= 258) {
  14119. //--- RESTORE() ---
  14120. strm.next_out = put;
  14121. strm.avail_out = left;
  14122. strm.next_in = next;
  14123. strm.avail_in = have;
  14124. state.hold = hold;
  14125. state.bits = bits;
  14126. //---
  14127. inflate_fast(strm, _out);
  14128. //--- LOAD() ---
  14129. put = strm.next_out;
  14130. output = strm.output;
  14131. left = strm.avail_out;
  14132. next = strm.next_in;
  14133. input = strm.input;
  14134. have = strm.avail_in;
  14135. hold = state.hold;
  14136. bits = state.bits;
  14137. //---
  14138. if (state.mode === TYPE) {
  14139. state.back = -1;
  14140. }
  14141. break;
  14142. }
  14143. state.back = 0;
  14144. for (;;) {
  14145. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  14146. here_bits = here >>> 24;
  14147. here_op = (here >>> 16) & 0xff;
  14148. here_val = here & 0xffff;
  14149. if (here_bits <= bits) { break; }
  14150. //--- PULLBYTE() ---//
  14151. if (have === 0) { break inf_leave; }
  14152. have--;
  14153. hold += input[next++] << bits;
  14154. bits += 8;
  14155. //---//
  14156. }
  14157. if (here_op && (here_op & 0xf0) === 0) {
  14158. last_bits = here_bits;
  14159. last_op = here_op;
  14160. last_val = here_val;
  14161. for (;;) {
  14162. here = state.lencode[last_val +
  14163. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  14164. here_bits = here >>> 24;
  14165. here_op = (here >>> 16) & 0xff;
  14166. here_val = here & 0xffff;
  14167. if ((last_bits + here_bits) <= bits) { break; }
  14168. //--- PULLBYTE() ---//
  14169. if (have === 0) { break inf_leave; }
  14170. have--;
  14171. hold += input[next++] << bits;
  14172. bits += 8;
  14173. //---//
  14174. }
  14175. //--- DROPBITS(last.bits) ---//
  14176. hold >>>= last_bits;
  14177. bits -= last_bits;
  14178. //---//
  14179. state.back += last_bits;
  14180. }
  14181. //--- DROPBITS(here.bits) ---//
  14182. hold >>>= here_bits;
  14183. bits -= here_bits;
  14184. //---//
  14185. state.back += here_bits;
  14186. state.length = here_val;
  14187. if (here_op === 0) {
  14188. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  14189. // "inflate: literal '%c'\n" :
  14190. // "inflate: literal 0x%02x\n", here.val));
  14191. state.mode = LIT;
  14192. break;
  14193. }
  14194. if (here_op & 32) {
  14195. //Tracevv((stderr, "inflate: end of block\n"));
  14196. state.back = -1;
  14197. state.mode = TYPE;
  14198. break;
  14199. }
  14200. if (here_op & 64) {
  14201. strm.msg = 'invalid literal/length code';
  14202. state.mode = BAD;
  14203. break;
  14204. }
  14205. state.extra = here_op & 15;
  14206. state.mode = LENEXT;
  14207. /* falls through */
  14208. case LENEXT:
  14209. if (state.extra) {
  14210. //=== NEEDBITS(state.extra);
  14211. n = state.extra;
  14212. while (bits < n) {
  14213. if (have === 0) { break inf_leave; }
  14214. have--;
  14215. hold += input[next++] << bits;
  14216. bits += 8;
  14217. }
  14218. //===//
  14219. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  14220. //--- DROPBITS(state.extra) ---//
  14221. hold >>>= state.extra;
  14222. bits -= state.extra;
  14223. //---//
  14224. state.back += state.extra;
  14225. }
  14226. //Tracevv((stderr, "inflate: length %u\n", state.length));
  14227. state.was = state.length;
  14228. state.mode = DIST;
  14229. /* falls through */
  14230. case DIST:
  14231. for (;;) {
  14232. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  14233. here_bits = here >>> 24;
  14234. here_op = (here >>> 16) & 0xff;
  14235. here_val = here & 0xffff;
  14236. if ((here_bits) <= bits) { break; }
  14237. //--- PULLBYTE() ---//
  14238. if (have === 0) { break inf_leave; }
  14239. have--;
  14240. hold += input[next++] << bits;
  14241. bits += 8;
  14242. //---//
  14243. }
  14244. if ((here_op & 0xf0) === 0) {
  14245. last_bits = here_bits;
  14246. last_op = here_op;
  14247. last_val = here_val;
  14248. for (;;) {
  14249. here = state.distcode[last_val +
  14250. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  14251. here_bits = here >>> 24;
  14252. here_op = (here >>> 16) & 0xff;
  14253. here_val = here & 0xffff;
  14254. if ((last_bits + here_bits) <= bits) { break; }
  14255. //--- PULLBYTE() ---//
  14256. if (have === 0) { break inf_leave; }
  14257. have--;
  14258. hold += input[next++] << bits;
  14259. bits += 8;
  14260. //---//
  14261. }
  14262. //--- DROPBITS(last.bits) ---//
  14263. hold >>>= last_bits;
  14264. bits -= last_bits;
  14265. //---//
  14266. state.back += last_bits;
  14267. }
  14268. //--- DROPBITS(here.bits) ---//
  14269. hold >>>= here_bits;
  14270. bits -= here_bits;
  14271. //---//
  14272. state.back += here_bits;
  14273. if (here_op & 64) {
  14274. strm.msg = 'invalid distance code';
  14275. state.mode = BAD;
  14276. break;
  14277. }
  14278. state.offset = here_val;
  14279. state.extra = (here_op) & 15;
  14280. state.mode = DISTEXT;
  14281. /* falls through */
  14282. case DISTEXT:
  14283. if (state.extra) {
  14284. //=== NEEDBITS(state.extra);
  14285. n = state.extra;
  14286. while (bits < n) {
  14287. if (have === 0) { break inf_leave; }
  14288. have--;
  14289. hold += input[next++] << bits;
  14290. bits += 8;
  14291. }
  14292. //===//
  14293. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  14294. //--- DROPBITS(state.extra) ---//
  14295. hold >>>= state.extra;
  14296. bits -= state.extra;
  14297. //---//
  14298. state.back += state.extra;
  14299. }
  14300. //#ifdef INFLATE_STRICT
  14301. if (state.offset > state.dmax) {
  14302. strm.msg = 'invalid distance too far back';
  14303. state.mode = BAD;
  14304. break;
  14305. }
  14306. //#endif
  14307. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  14308. state.mode = MATCH;
  14309. /* falls through */
  14310. case MATCH:
  14311. if (left === 0) { break inf_leave; }
  14312. copy = _out - left;
  14313. if (state.offset > copy) { /* copy from window */
  14314. copy = state.offset - copy;
  14315. if (copy > state.whave) {
  14316. if (state.sane) {
  14317. strm.msg = 'invalid distance too far back';
  14318. state.mode = BAD;
  14319. break;
  14320. }
  14321. // (!) This block is disabled in zlib defailts,
  14322. // don't enable it for binary compatibility
  14323. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  14324. // Trace((stderr, "inflate.c too far\n"));
  14325. // copy -= state.whave;
  14326. // if (copy > state.length) { copy = state.length; }
  14327. // if (copy > left) { copy = left; }
  14328. // left -= copy;
  14329. // state.length -= copy;
  14330. // do {
  14331. // output[put++] = 0;
  14332. // } while (--copy);
  14333. // if (state.length === 0) { state.mode = LEN; }
  14334. // break;
  14335. //#endif
  14336. }
  14337. if (copy > state.wnext) {
  14338. copy -= state.wnext;
  14339. from = state.wsize - copy;
  14340. }
  14341. else {
  14342. from = state.wnext - copy;
  14343. }
  14344. if (copy > state.length) { copy = state.length; }
  14345. from_source = state.window;
  14346. }
  14347. else { /* copy from output */
  14348. from_source = output;
  14349. from = put - state.offset;
  14350. copy = state.length;
  14351. }
  14352. if (copy > left) { copy = left; }
  14353. left -= copy;
  14354. state.length -= copy;
  14355. do {
  14356. output[put++] = from_source[from++];
  14357. } while (--copy);
  14358. if (state.length === 0) { state.mode = LEN; }
  14359. break;
  14360. case LIT:
  14361. if (left === 0) { break inf_leave; }
  14362. output[put++] = state.length;
  14363. left--;
  14364. state.mode = LEN;
  14365. break;
  14366. case CHECK:
  14367. if (state.wrap) {
  14368. //=== NEEDBITS(32);
  14369. while (bits < 32) {
  14370. if (have === 0) { break inf_leave; }
  14371. have--;
  14372. // Use '|' insdead of '+' to make sure that result is signed
  14373. hold |= input[next++] << bits;
  14374. bits += 8;
  14375. }
  14376. //===//
  14377. _out -= left;
  14378. strm.total_out += _out;
  14379. state.total += _out;
  14380. if (_out) {
  14381. strm.adler = state.check =
  14382. /*UPDATE(state.check, put - _out, _out);*/
  14383. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  14384. }
  14385. _out = left;
  14386. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  14387. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  14388. strm.msg = 'incorrect data check';
  14389. state.mode = BAD;
  14390. break;
  14391. }
  14392. //=== INITBITS();
  14393. hold = 0;
  14394. bits = 0;
  14395. //===//
  14396. //Tracev((stderr, "inflate: check matches trailer\n"));
  14397. }
  14398. state.mode = LENGTH;
  14399. /* falls through */
  14400. case LENGTH:
  14401. if (state.wrap && state.flags) {
  14402. //=== NEEDBITS(32);
  14403. while (bits < 32) {
  14404. if (have === 0) { break inf_leave; }
  14405. have--;
  14406. hold += input[next++] << bits;
  14407. bits += 8;
  14408. }
  14409. //===//
  14410. if (hold !== (state.total & 0xffffffff)) {
  14411. strm.msg = 'incorrect length check';
  14412. state.mode = BAD;
  14413. break;
  14414. }
  14415. //=== INITBITS();
  14416. hold = 0;
  14417. bits = 0;
  14418. //===//
  14419. //Tracev((stderr, "inflate: length matches trailer\n"));
  14420. }
  14421. state.mode = DONE;
  14422. /* falls through */
  14423. case DONE:
  14424. ret = Z_STREAM_END;
  14425. break inf_leave;
  14426. case BAD:
  14427. ret = Z_DATA_ERROR;
  14428. break inf_leave;
  14429. case MEM:
  14430. return Z_MEM_ERROR;
  14431. case SYNC:
  14432. /* falls through */
  14433. default:
  14434. return Z_STREAM_ERROR;
  14435. }
  14436. }
  14437. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  14438. /*
  14439. Return from inflate(), updating the total counts and the check value.
  14440. If there was no progress during the inflate() call, return a buffer
  14441. error. Call updatewindow() to create and/or update the window state.
  14442. Note: a memory error from inflate() is non-recoverable.
  14443. */
  14444. //--- RESTORE() ---
  14445. strm.next_out = put;
  14446. strm.avail_out = left;
  14447. strm.next_in = next;
  14448. strm.avail_in = have;
  14449. state.hold = hold;
  14450. state.bits = bits;
  14451. //---
  14452. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  14453. (state.mode < CHECK || flush !== Z_FINISH))) {
  14454. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  14455. state.mode = MEM;
  14456. return Z_MEM_ERROR;
  14457. }
  14458. }
  14459. _in -= strm.avail_in;
  14460. _out -= strm.avail_out;
  14461. strm.total_in += _in;
  14462. strm.total_out += _out;
  14463. state.total += _out;
  14464. if (state.wrap && _out) {
  14465. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  14466. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  14467. }
  14468. strm.data_type = state.bits + (state.last ? 64 : 0) +
  14469. (state.mode === TYPE ? 128 : 0) +
  14470. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  14471. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  14472. ret = Z_BUF_ERROR;
  14473. }
  14474. return ret;
  14475. }
  14476. function inflateEnd(strm) {
  14477. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  14478. return Z_STREAM_ERROR;
  14479. }
  14480. var state = strm.state;
  14481. if (state.window) {
  14482. state.window = null;
  14483. }
  14484. strm.state = null;
  14485. return Z_OK;
  14486. }
  14487. function inflateGetHeader(strm, head) {
  14488. var state;
  14489. /* check state */
  14490. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  14491. state = strm.state;
  14492. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  14493. /* save header structure */
  14494. state.head = head;
  14495. head.done = false;
  14496. return Z_OK;
  14497. }
  14498. exports.inflateReset = inflateReset;
  14499. exports.inflateReset2 = inflateReset2;
  14500. exports.inflateResetKeep = inflateResetKeep;
  14501. exports.inflateInit = inflateInit;
  14502. exports.inflateInit2 = inflateInit2;
  14503. exports.inflate = inflate;
  14504. exports.inflateEnd = inflateEnd;
  14505. exports.inflateGetHeader = inflateGetHeader;
  14506. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  14507. /* Not implemented
  14508. exports.inflateCopy = inflateCopy;
  14509. exports.inflateGetDictionary = inflateGetDictionary;
  14510. exports.inflateMark = inflateMark;
  14511. exports.inflatePrime = inflatePrime;
  14512. exports.inflateSetDictionary = inflateSetDictionary;
  14513. exports.inflateSync = inflateSync;
  14514. exports.inflateSyncPoint = inflateSyncPoint;
  14515. exports.inflateUndermine = inflateUndermine;
  14516. */
  14517. },{"../utils/common":39,"./adler32":41,"./crc32":43,"./inffast":46,"./inftrees":48}],48:[function(require,module,exports){
  14518. 'use strict';
  14519. var utils = require('../utils/common');
  14520. var MAXBITS = 15;
  14521. var ENOUGH_LENS = 852;
  14522. var ENOUGH_DISTS = 592;
  14523. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  14524. var CODES = 0;
  14525. var LENS = 1;
  14526. var DISTS = 2;
  14527. var lbase = [ /* Length codes 257..285 base */
  14528. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  14529. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  14530. ];
  14531. var lext = [ /* Length codes 257..285 extra */
  14532. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  14533. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  14534. ];
  14535. var dbase = [ /* Distance codes 0..29 base */
  14536. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  14537. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  14538. 8193, 12289, 16385, 24577, 0, 0
  14539. ];
  14540. var dext = [ /* Distance codes 0..29 extra */
  14541. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  14542. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  14543. 28, 28, 29, 29, 64, 64
  14544. ];
  14545. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  14546. {
  14547. var bits = opts.bits;
  14548. //here = opts.here; /* table entry for duplication */
  14549. var len = 0; /* a code's length in bits */
  14550. var sym = 0; /* index of code symbols */
  14551. var min = 0, max = 0; /* minimum and maximum code lengths */
  14552. var root = 0; /* number of index bits for root table */
  14553. var curr = 0; /* number of index bits for current table */
  14554. var drop = 0; /* code bits to drop for sub-table */
  14555. var left = 0; /* number of prefix codes available */
  14556. var used = 0; /* code entries in table used */
  14557. var huff = 0; /* Huffman code */
  14558. var incr; /* for incrementing code, index */
  14559. var fill; /* index for replicating entries */
  14560. var low; /* low bits for current root entry */
  14561. var mask; /* mask for low root bits */
  14562. var next; /* next available space in table */
  14563. var base = null; /* base value table to use */
  14564. var base_index = 0;
  14565. // var shoextra; /* extra bits table to use */
  14566. var end; /* use base and extra for symbol > end */
  14567. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  14568. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  14569. var extra = null;
  14570. var extra_index = 0;
  14571. var here_bits, here_op, here_val;
  14572. /*
  14573. Process a set of code lengths to create a canonical Huffman code. The
  14574. code lengths are lens[0..codes-1]. Each length corresponds to the
  14575. symbols 0..codes-1. The Huffman code is generated by first sorting the
  14576. symbols by length from short to long, and retaining the symbol order
  14577. for codes with equal lengths. Then the code starts with all zero bits
  14578. for the first code of the shortest length, and the codes are integer
  14579. increments for the same length, and zeros are appended as the length
  14580. increases. For the deflate format, these bits are stored backwards
  14581. from their more natural integer increment ordering, and so when the
  14582. decoding tables are built in the large loop below, the integer codes
  14583. are incremented backwards.
  14584. This routine assumes, but does not check, that all of the entries in
  14585. lens[] are in the range 0..MAXBITS. The caller must assure this.
  14586. 1..MAXBITS is interpreted as that code length. zero means that that
  14587. symbol does not occur in this code.
  14588. The codes are sorted by computing a count of codes for each length,
  14589. creating from that a table of starting indices for each length in the
  14590. sorted table, and then entering the symbols in order in the sorted
  14591. table. The sorted table is work[], with that space being provided by
  14592. the caller.
  14593. The length counts are used for other purposes as well, i.e. finding
  14594. the minimum and maximum length codes, determining if there are any
  14595. codes at all, checking for a valid set of lengths, and looking ahead
  14596. at length counts to determine sub-table sizes when building the
  14597. decoding tables.
  14598. */
  14599. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  14600. for (len = 0; len <= MAXBITS; len++) {
  14601. count[len] = 0;
  14602. }
  14603. for (sym = 0; sym < codes; sym++) {
  14604. count[lens[lens_index + sym]]++;
  14605. }
  14606. /* bound code lengths, force root to be within code lengths */
  14607. root = bits;
  14608. for (max = MAXBITS; max >= 1; max--) {
  14609. if (count[max] !== 0) { break; }
  14610. }
  14611. if (root > max) {
  14612. root = max;
  14613. }
  14614. if (max === 0) { /* no symbols to code at all */
  14615. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  14616. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  14617. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  14618. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  14619. //table.op[opts.table_index] = 64;
  14620. //table.bits[opts.table_index] = 1;
  14621. //table.val[opts.table_index++] = 0;
  14622. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  14623. opts.bits = 1;
  14624. return 0; /* no symbols, but wait for decoding to report error */
  14625. }
  14626. for (min = 1; min < max; min++) {
  14627. if (count[min] !== 0) { break; }
  14628. }
  14629. if (root < min) {
  14630. root = min;
  14631. }
  14632. /* check for an over-subscribed or incomplete set of lengths */
  14633. left = 1;
  14634. for (len = 1; len <= MAXBITS; len++) {
  14635. left <<= 1;
  14636. left -= count[len];
  14637. if (left < 0) {
  14638. return -1;
  14639. } /* over-subscribed */
  14640. }
  14641. if (left > 0 && (type === CODES || max !== 1)) {
  14642. return -1; /* incomplete set */
  14643. }
  14644. /* generate offsets into symbol table for each length for sorting */
  14645. offs[1] = 0;
  14646. for (len = 1; len < MAXBITS; len++) {
  14647. offs[len + 1] = offs[len] + count[len];
  14648. }
  14649. /* sort symbols by length, by symbol order within each length */
  14650. for (sym = 0; sym < codes; sym++) {
  14651. if (lens[lens_index + sym] !== 0) {
  14652. work[offs[lens[lens_index + sym]]++] = sym;
  14653. }
  14654. }
  14655. /*
  14656. Create and fill in decoding tables. In this loop, the table being
  14657. filled is at next and has curr index bits. The code being used is huff
  14658. with length len. That code is converted to an index by dropping drop
  14659. bits off of the bottom. For codes where len is less than drop + curr,
  14660. those top drop + curr - len bits are incremented through all values to
  14661. fill the table with replicated entries.
  14662. root is the number of index bits for the root table. When len exceeds
  14663. root, sub-tables are created pointed to by the root entry with an index
  14664. of the low root bits of huff. This is saved in low to check for when a
  14665. new sub-table should be started. drop is zero when the root table is
  14666. being filled, and drop is root when sub-tables are being filled.
  14667. When a new sub-table is needed, it is necessary to look ahead in the
  14668. code lengths to determine what size sub-table is needed. The length
  14669. counts are used for this, and so count[] is decremented as codes are
  14670. entered in the tables.
  14671. used keeps track of how many table entries have been allocated from the
  14672. provided *table space. It is checked for LENS and DIST tables against
  14673. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  14674. the initial root table size constants. See the comments in inftrees.h
  14675. for more information.
  14676. sym increments through all symbols, and the loop terminates when
  14677. all codes of length max, i.e. all codes, have been processed. This
  14678. routine permits incomplete codes, so another loop after this one fills
  14679. in the rest of the decoding tables with invalid code markers.
  14680. */
  14681. /* set up for code type */
  14682. // poor man optimization - use if-else instead of switch,
  14683. // to avoid deopts in old v8
  14684. if (type === CODES) {
  14685. base = extra = work; /* dummy value--not used */
  14686. end = 19;
  14687. } else if (type === LENS) {
  14688. base = lbase;
  14689. base_index -= 257;
  14690. extra = lext;
  14691. extra_index -= 257;
  14692. end = 256;
  14693. } else { /* DISTS */
  14694. base = dbase;
  14695. extra = dext;
  14696. end = -1;
  14697. }
  14698. /* initialize opts for loop */
  14699. huff = 0; /* starting code */
  14700. sym = 0; /* starting code symbol */
  14701. len = min; /* starting code length */
  14702. next = table_index; /* current table to fill in */
  14703. curr = root; /* current table index bits */
  14704. drop = 0; /* current bits to drop from code for index */
  14705. low = -1; /* trigger new sub-table when len > root */
  14706. used = 1 << root; /* use root table entries */
  14707. mask = used - 1; /* mask for comparing low */
  14708. /* check available table space */
  14709. if ((type === LENS && used > ENOUGH_LENS) ||
  14710. (type === DISTS && used > ENOUGH_DISTS)) {
  14711. return 1;
  14712. }
  14713. var i=0;
  14714. /* process all codes and make table entries */
  14715. for (;;) {
  14716. i++;
  14717. /* create table entry */
  14718. here_bits = len - drop;
  14719. if (work[sym] < end) {
  14720. here_op = 0;
  14721. here_val = work[sym];
  14722. }
  14723. else if (work[sym] > end) {
  14724. here_op = extra[extra_index + work[sym]];
  14725. here_val = base[base_index + work[sym]];
  14726. }
  14727. else {
  14728. here_op = 32 + 64; /* end of block */
  14729. here_val = 0;
  14730. }
  14731. /* replicate for those indices with low len bits equal to huff */
  14732. incr = 1 << (len - drop);
  14733. fill = 1 << curr;
  14734. min = fill; /* save offset to next table */
  14735. do {
  14736. fill -= incr;
  14737. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  14738. } while (fill !== 0);
  14739. /* backwards increment the len-bit code huff */
  14740. incr = 1 << (len - 1);
  14741. while (huff & incr) {
  14742. incr >>= 1;
  14743. }
  14744. if (incr !== 0) {
  14745. huff &= incr - 1;
  14746. huff += incr;
  14747. } else {
  14748. huff = 0;
  14749. }
  14750. /* go to next symbol, update count, len */
  14751. sym++;
  14752. if (--count[len] === 0) {
  14753. if (len === max) { break; }
  14754. len = lens[lens_index + work[sym]];
  14755. }
  14756. /* create new sub-table if needed */
  14757. if (len > root && (huff & mask) !== low) {
  14758. /* if first time, transition to sub-tables */
  14759. if (drop === 0) {
  14760. drop = root;
  14761. }
  14762. /* increment past last table */
  14763. next += min; /* here min is 1 << curr */
  14764. /* determine length of next table */
  14765. curr = len - drop;
  14766. left = 1 << curr;
  14767. while (curr + drop < max) {
  14768. left -= count[curr + drop];
  14769. if (left <= 0) { break; }
  14770. curr++;
  14771. left <<= 1;
  14772. }
  14773. /* check for enough space */
  14774. used += 1 << curr;
  14775. if ((type === LENS && used > ENOUGH_LENS) ||
  14776. (type === DISTS && used > ENOUGH_DISTS)) {
  14777. return 1;
  14778. }
  14779. /* point entry in root table to sub-table */
  14780. low = huff & mask;
  14781. /*table.op[low] = curr;
  14782. table.bits[low] = root;
  14783. table.val[low] = next - opts.table_index;*/
  14784. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  14785. }
  14786. }
  14787. /* fill in remaining table entry if code is incomplete (guaranteed to have
  14788. at most one remaining entry, since if the code is incomplete, the
  14789. maximum code length that was allowed to get this far is one bit) */
  14790. if (huff !== 0) {
  14791. //table.op[next + huff] = 64; /* invalid code marker */
  14792. //table.bits[next + huff] = len - drop;
  14793. //table.val[next + huff] = 0;
  14794. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  14795. }
  14796. /* set return parameters */
  14797. //opts.table_index += used;
  14798. opts.bits = root;
  14799. return 0;
  14800. };
  14801. },{"../utils/common":39}],49:[function(require,module,exports){
  14802. 'use strict';
  14803. module.exports = {
  14804. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  14805. '1': 'stream end', /* Z_STREAM_END 1 */
  14806. '0': '', /* Z_OK 0 */
  14807. '-1': 'file error', /* Z_ERRNO (-1) */
  14808. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  14809. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  14810. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  14811. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  14812. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  14813. };
  14814. },{}],50:[function(require,module,exports){
  14815. 'use strict';
  14816. var utils = require('../utils/common');
  14817. /* Public constants ==========================================================*/
  14818. /* ===========================================================================*/
  14819. //var Z_FILTERED = 1;
  14820. //var Z_HUFFMAN_ONLY = 2;
  14821. //var Z_RLE = 3;
  14822. var Z_FIXED = 4;
  14823. //var Z_DEFAULT_STRATEGY = 0;
  14824. /* Possible values of the data_type field (though see inflate()) */
  14825. var Z_BINARY = 0;
  14826. var Z_TEXT = 1;
  14827. //var Z_ASCII = 1; // = Z_TEXT
  14828. var Z_UNKNOWN = 2;
  14829. /*============================================================================*/
  14830. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  14831. // From zutil.h
  14832. var STORED_BLOCK = 0;
  14833. var STATIC_TREES = 1;
  14834. var DYN_TREES = 2;
  14835. /* The three kinds of block type */
  14836. var MIN_MATCH = 3;
  14837. var MAX_MATCH = 258;
  14838. /* The minimum and maximum match lengths */
  14839. // From deflate.h
  14840. /* ===========================================================================
  14841. * Internal compression state.
  14842. */
  14843. var LENGTH_CODES = 29;
  14844. /* number of length codes, not counting the special END_BLOCK code */
  14845. var LITERALS = 256;
  14846. /* number of literal bytes 0..255 */
  14847. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  14848. /* number of Literal or Length codes, including the END_BLOCK code */
  14849. var D_CODES = 30;
  14850. /* number of distance codes */
  14851. var BL_CODES = 19;
  14852. /* number of codes used to transfer the bit lengths */
  14853. var HEAP_SIZE = 2*L_CODES + 1;
  14854. /* maximum heap size */
  14855. var MAX_BITS = 15;
  14856. /* All codes must not exceed MAX_BITS bits */
  14857. var Buf_size = 16;
  14858. /* size of bit buffer in bi_buf */
  14859. /* ===========================================================================
  14860. * Constants
  14861. */
  14862. var MAX_BL_BITS = 7;
  14863. /* Bit length codes must not exceed MAX_BL_BITS bits */
  14864. var END_BLOCK = 256;
  14865. /* end of block literal code */
  14866. var REP_3_6 = 16;
  14867. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  14868. var REPZ_3_10 = 17;
  14869. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  14870. var REPZ_11_138 = 18;
  14871. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  14872. var extra_lbits = /* extra bits for each length code */
  14873. [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];
  14874. var extra_dbits = /* extra bits for each distance code */
  14875. [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];
  14876. var extra_blbits = /* extra bits for each bit length code */
  14877. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  14878. var bl_order =
  14879. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  14880. /* The lengths of the bit length codes are sent in order of decreasing
  14881. * probability, to avoid transmitting the lengths for unused bit length codes.
  14882. */
  14883. /* ===========================================================================
  14884. * Local data. These are initialized only once.
  14885. */
  14886. // We pre-fill arrays with 0 to avoid uninitialized gaps
  14887. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  14888. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  14889. var static_ltree = new Array((L_CODES+2) * 2);
  14890. zero(static_ltree);
  14891. /* The static literal tree. Since the bit lengths are imposed, there is no
  14892. * need for the L_CODES extra codes used during heap construction. However
  14893. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  14894. * below).
  14895. */
  14896. var static_dtree = new Array(D_CODES * 2);
  14897. zero(static_dtree);
  14898. /* The static distance tree. (Actually a trivial tree since all codes use
  14899. * 5 bits.)
  14900. */
  14901. var _dist_code = new Array(DIST_CODE_LEN);
  14902. zero(_dist_code);
  14903. /* Distance codes. The first 256 values correspond to the distances
  14904. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  14905. * the 15 bit distances.
  14906. */
  14907. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  14908. zero(_length_code);
  14909. /* length code for each normalized match length (0 == MIN_MATCH) */
  14910. var base_length = new Array(LENGTH_CODES);
  14911. zero(base_length);
  14912. /* First normalized length for each code (0 = MIN_MATCH) */
  14913. var base_dist = new Array(D_CODES);
  14914. zero(base_dist);
  14915. /* First normalized distance for each code (0 = distance of 1) */
  14916. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  14917. this.static_tree = static_tree; /* static tree or NULL */
  14918. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  14919. this.extra_base = extra_base; /* base index for extra_bits */
  14920. this.elems = elems; /* max number of elements in the tree */
  14921. this.max_length = max_length; /* max bit length for the codes */
  14922. // show if `static_tree` has data or dummy - needed for monomorphic objects
  14923. this.has_stree = static_tree && static_tree.length;
  14924. };
  14925. var static_l_desc;
  14926. var static_d_desc;
  14927. var static_bl_desc;
  14928. var TreeDesc = function(dyn_tree, stat_desc) {
  14929. this.dyn_tree = dyn_tree; /* the dynamic tree */
  14930. this.max_code = 0; /* largest code with non zero frequency */
  14931. this.stat_desc = stat_desc; /* the corresponding static tree */
  14932. };
  14933. function d_code(dist) {
  14934. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  14935. }
  14936. /* ===========================================================================
  14937. * Output a short LSB first on the stream.
  14938. * IN assertion: there is enough room in pendingBuf.
  14939. */
  14940. function put_short (s, w) {
  14941. // put_byte(s, (uch)((w) & 0xff));
  14942. // put_byte(s, (uch)((ush)(w) >> 8));
  14943. s.pending_buf[s.pending++] = (w) & 0xff;
  14944. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  14945. }
  14946. /* ===========================================================================
  14947. * Send a value on a given number of bits.
  14948. * IN assertion: length <= 16 and value fits in length bits.
  14949. */
  14950. function send_bits(s, value, length) {
  14951. if (s.bi_valid > (Buf_size - length)) {
  14952. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  14953. put_short(s, s.bi_buf);
  14954. s.bi_buf = value >> (Buf_size - s.bi_valid);
  14955. s.bi_valid += length - Buf_size;
  14956. } else {
  14957. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  14958. s.bi_valid += length;
  14959. }
  14960. }
  14961. function send_code(s, c, tree) {
  14962. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  14963. }
  14964. /* ===========================================================================
  14965. * Reverse the first len bits of a code, using straightforward code (a faster
  14966. * method would use a table)
  14967. * IN assertion: 1 <= len <= 15
  14968. */
  14969. function bi_reverse(code, len) {
  14970. var res = 0;
  14971. do {
  14972. res |= code & 1;
  14973. code >>>= 1;
  14974. res <<= 1;
  14975. } while (--len > 0);
  14976. return res >>> 1;
  14977. }
  14978. /* ===========================================================================
  14979. * Flush the bit buffer, keeping at most 7 bits in it.
  14980. */
  14981. function bi_flush(s) {
  14982. if (s.bi_valid === 16) {
  14983. put_short(s, s.bi_buf);
  14984. s.bi_buf = 0;
  14985. s.bi_valid = 0;
  14986. } else if (s.bi_valid >= 8) {
  14987. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  14988. s.bi_buf >>= 8;
  14989. s.bi_valid -= 8;
  14990. }
  14991. }
  14992. /* ===========================================================================
  14993. * Compute the optimal bit lengths for a tree and update the total bit length
  14994. * for the current block.
  14995. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  14996. * above are the tree nodes sorted by increasing frequency.
  14997. * OUT assertions: the field len is set to the optimal bit length, the
  14998. * array bl_count contains the frequencies for each bit length.
  14999. * The length opt_len is updated; static_len is also updated if stree is
  15000. * not null.
  15001. */
  15002. function gen_bitlen(s, desc)
  15003. // deflate_state *s;
  15004. // tree_desc *desc; /* the tree descriptor */
  15005. {
  15006. var tree = desc.dyn_tree;
  15007. var max_code = desc.max_code;
  15008. var stree = desc.stat_desc.static_tree;
  15009. var has_stree = desc.stat_desc.has_stree;
  15010. var extra = desc.stat_desc.extra_bits;
  15011. var base = desc.stat_desc.extra_base;
  15012. var max_length = desc.stat_desc.max_length;
  15013. var h; /* heap index */
  15014. var n, m; /* iterate over the tree elements */
  15015. var bits; /* bit length */
  15016. var xbits; /* extra bits */
  15017. var f; /* frequency */
  15018. var overflow = 0; /* number of elements with bit length too large */
  15019. for (bits = 0; bits <= MAX_BITS; bits++) {
  15020. s.bl_count[bits] = 0;
  15021. }
  15022. /* In a first pass, compute the optimal bit lengths (which may
  15023. * overflow in the case of the bit length tree).
  15024. */
  15025. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  15026. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  15027. n = s.heap[h];
  15028. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  15029. if (bits > max_length) {
  15030. bits = max_length;
  15031. overflow++;
  15032. }
  15033. tree[n*2 + 1]/*.Len*/ = bits;
  15034. /* We overwrite tree[n].Dad which is no longer needed */
  15035. if (n > max_code) { continue; } /* not a leaf node */
  15036. s.bl_count[bits]++;
  15037. xbits = 0;
  15038. if (n >= base) {
  15039. xbits = extra[n-base];
  15040. }
  15041. f = tree[n * 2]/*.Freq*/;
  15042. s.opt_len += f * (bits + xbits);
  15043. if (has_stree) {
  15044. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  15045. }
  15046. }
  15047. if (overflow === 0) { return; }
  15048. // Trace((stderr,"\nbit length overflow\n"));
  15049. /* This happens for example on obj2 and pic of the Calgary corpus */
  15050. /* Find the first bit length which could increase: */
  15051. do {
  15052. bits = max_length-1;
  15053. while (s.bl_count[bits] === 0) { bits--; }
  15054. s.bl_count[bits]--; /* move one leaf down the tree */
  15055. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  15056. s.bl_count[max_length]--;
  15057. /* The brother of the overflow item also moves one step up,
  15058. * but this does not affect bl_count[max_length]
  15059. */
  15060. overflow -= 2;
  15061. } while (overflow > 0);
  15062. /* Now recompute all bit lengths, scanning in increasing frequency.
  15063. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  15064. * lengths instead of fixing only the wrong ones. This idea is taken
  15065. * from 'ar' written by Haruhiko Okumura.)
  15066. */
  15067. for (bits = max_length; bits !== 0; bits--) {
  15068. n = s.bl_count[bits];
  15069. while (n !== 0) {
  15070. m = s.heap[--h];
  15071. if (m > max_code) { continue; }
  15072. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  15073. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  15074. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  15075. tree[m*2 + 1]/*.Len*/ = bits;
  15076. }
  15077. n--;
  15078. }
  15079. }
  15080. }
  15081. /* ===========================================================================
  15082. * Generate the codes for a given tree and bit counts (which need not be
  15083. * optimal).
  15084. * IN assertion: the array bl_count contains the bit length statistics for
  15085. * the given tree and the field len is set for all tree elements.
  15086. * OUT assertion: the field code is set for all tree elements of non
  15087. * zero code length.
  15088. */
  15089. function gen_codes(tree, max_code, bl_count)
  15090. // ct_data *tree; /* the tree to decorate */
  15091. // int max_code; /* largest code with non zero frequency */
  15092. // ushf *bl_count; /* number of codes at each bit length */
  15093. {
  15094. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  15095. var code = 0; /* running code value */
  15096. var bits; /* bit index */
  15097. var n; /* code index */
  15098. /* The distribution counts are first used to generate the code values
  15099. * without bit reversal.
  15100. */
  15101. for (bits = 1; bits <= MAX_BITS; bits++) {
  15102. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  15103. }
  15104. /* Check that the bit counts in bl_count are consistent. The last code
  15105. * must be all ones.
  15106. */
  15107. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  15108. // "inconsistent bit counts");
  15109. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  15110. for (n = 0; n <= max_code; n++) {
  15111. var len = tree[n*2 + 1]/*.Len*/;
  15112. if (len === 0) { continue; }
  15113. /* Now reverse the bits */
  15114. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  15115. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  15116. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  15117. }
  15118. }
  15119. /* ===========================================================================
  15120. * Initialize the various 'constant' tables.
  15121. */
  15122. function tr_static_init() {
  15123. var n; /* iterates over tree elements */
  15124. var bits; /* bit counter */
  15125. var length; /* length value */
  15126. var code; /* code value */
  15127. var dist; /* distance index */
  15128. var bl_count = new Array(MAX_BITS+1);
  15129. /* number of codes at each bit length for an optimal tree */
  15130. // do check in _tr_init()
  15131. //if (static_init_done) return;
  15132. /* For some embedded targets, global variables are not initialized: */
  15133. /*#ifdef NO_INIT_GLOBAL_POINTERS
  15134. static_l_desc.static_tree = static_ltree;
  15135. static_l_desc.extra_bits = extra_lbits;
  15136. static_d_desc.static_tree = static_dtree;
  15137. static_d_desc.extra_bits = extra_dbits;
  15138. static_bl_desc.extra_bits = extra_blbits;
  15139. #endif*/
  15140. /* Initialize the mapping length (0..255) -> length code (0..28) */
  15141. length = 0;
  15142. for (code = 0; code < LENGTH_CODES-1; code++) {
  15143. base_length[code] = length;
  15144. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  15145. _length_code[length++] = code;
  15146. }
  15147. }
  15148. //Assert (length == 256, "tr_static_init: length != 256");
  15149. /* Note that the length 255 (match length 258) can be represented
  15150. * in two different ways: code 284 + 5 bits or code 285, so we
  15151. * overwrite length_code[255] to use the best encoding:
  15152. */
  15153. _length_code[length-1] = code;
  15154. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  15155. dist = 0;
  15156. for (code = 0 ; code < 16; code++) {
  15157. base_dist[code] = dist;
  15158. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  15159. _dist_code[dist++] = code;
  15160. }
  15161. }
  15162. //Assert (dist == 256, "tr_static_init: dist != 256");
  15163. dist >>= 7; /* from now on, all distances are divided by 128 */
  15164. for (; code < D_CODES; code++) {
  15165. base_dist[code] = dist << 7;
  15166. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  15167. _dist_code[256 + dist++] = code;
  15168. }
  15169. }
  15170. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  15171. /* Construct the codes of the static literal tree */
  15172. for (bits = 0; bits <= MAX_BITS; bits++) {
  15173. bl_count[bits] = 0;
  15174. }
  15175. n = 0;
  15176. while (n <= 143) {
  15177. static_ltree[n*2 + 1]/*.Len*/ = 8;
  15178. n++;
  15179. bl_count[8]++;
  15180. }
  15181. while (n <= 255) {
  15182. static_ltree[n*2 + 1]/*.Len*/ = 9;
  15183. n++;
  15184. bl_count[9]++;
  15185. }
  15186. while (n <= 279) {
  15187. static_ltree[n*2 + 1]/*.Len*/ = 7;
  15188. n++;
  15189. bl_count[7]++;
  15190. }
  15191. while (n <= 287) {
  15192. static_ltree[n*2 + 1]/*.Len*/ = 8;
  15193. n++;
  15194. bl_count[8]++;
  15195. }
  15196. /* Codes 286 and 287 do not exist, but we must include them in the
  15197. * tree construction to get a canonical Huffman tree (longest code
  15198. * all ones)
  15199. */
  15200. gen_codes(static_ltree, L_CODES+1, bl_count);
  15201. /* The static distance tree is trivial: */
  15202. for (n = 0; n < D_CODES; n++) {
  15203. static_dtree[n*2 + 1]/*.Len*/ = 5;
  15204. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  15205. }
  15206. // Now data ready and we can init static trees
  15207. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  15208. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  15209. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  15210. //static_init_done = true;
  15211. }
  15212. /* ===========================================================================
  15213. * Initialize a new block.
  15214. */
  15215. function init_block(s) {
  15216. var n; /* iterates over tree elements */
  15217. /* Initialize the trees. */
  15218. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  15219. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  15220. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  15221. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  15222. s.opt_len = s.static_len = 0;
  15223. s.last_lit = s.matches = 0;
  15224. }
  15225. /* ===========================================================================
  15226. * Flush the bit buffer and align the output on a byte boundary
  15227. */
  15228. function bi_windup(s)
  15229. {
  15230. if (s.bi_valid > 8) {
  15231. put_short(s, s.bi_buf);
  15232. } else if (s.bi_valid > 0) {
  15233. //put_byte(s, (Byte)s->bi_buf);
  15234. s.pending_buf[s.pending++] = s.bi_buf;
  15235. }
  15236. s.bi_buf = 0;
  15237. s.bi_valid = 0;
  15238. }
  15239. /* ===========================================================================
  15240. * Copy a stored block, storing first the length and its
  15241. * one's complement if requested.
  15242. */
  15243. function copy_block(s, buf, len, header)
  15244. //DeflateState *s;
  15245. //charf *buf; /* the input data */
  15246. //unsigned len; /* its length */
  15247. //int header; /* true if block header must be written */
  15248. {
  15249. bi_windup(s); /* align on byte boundary */
  15250. if (header) {
  15251. put_short(s, len);
  15252. put_short(s, ~len);
  15253. }
  15254. // while (len--) {
  15255. // put_byte(s, *buf++);
  15256. // }
  15257. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  15258. s.pending += len;
  15259. }
  15260. /* ===========================================================================
  15261. * Compares to subtrees, using the tree depth as tie breaker when
  15262. * the subtrees have equal frequency. This minimizes the worst case length.
  15263. */
  15264. function smaller(tree, n, m, depth) {
  15265. var _n2 = n*2;
  15266. var _m2 = m*2;
  15267. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  15268. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  15269. }
  15270. /* ===========================================================================
  15271. * Restore the heap property by moving down the tree starting at node k,
  15272. * exchanging a node with the smallest of its two sons if necessary, stopping
  15273. * when the heap property is re-established (each father smaller than its
  15274. * two sons).
  15275. */
  15276. function pqdownheap(s, tree, k)
  15277. // deflate_state *s;
  15278. // ct_data *tree; /* the tree to restore */
  15279. // int k; /* node to move down */
  15280. {
  15281. var v = s.heap[k];
  15282. var j = k << 1; /* left son of k */
  15283. while (j <= s.heap_len) {
  15284. /* Set j to the smallest of the two sons: */
  15285. if (j < s.heap_len &&
  15286. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  15287. j++;
  15288. }
  15289. /* Exit if v is smaller than both sons */
  15290. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  15291. /* Exchange v with the smallest son */
  15292. s.heap[k] = s.heap[j];
  15293. k = j;
  15294. /* And continue down the tree, setting j to the left son of k */
  15295. j <<= 1;
  15296. }
  15297. s.heap[k] = v;
  15298. }
  15299. // inlined manually
  15300. // var SMALLEST = 1;
  15301. /* ===========================================================================
  15302. * Send the block data compressed using the given Huffman trees
  15303. */
  15304. function compress_block(s, ltree, dtree)
  15305. // deflate_state *s;
  15306. // const ct_data *ltree; /* literal tree */
  15307. // const ct_data *dtree; /* distance tree */
  15308. {
  15309. var dist; /* distance of matched string */
  15310. var lc; /* match length or unmatched char (if dist == 0) */
  15311. var lx = 0; /* running index in l_buf */
  15312. var code; /* the code to send */
  15313. var extra; /* number of extra bits to send */
  15314. if (s.last_lit !== 0) {
  15315. do {
  15316. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  15317. lc = s.pending_buf[s.l_buf + lx];
  15318. lx++;
  15319. if (dist === 0) {
  15320. send_code(s, lc, ltree); /* send a literal byte */
  15321. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  15322. } else {
  15323. /* Here, lc is the match length - MIN_MATCH */
  15324. code = _length_code[lc];
  15325. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  15326. extra = extra_lbits[code];
  15327. if (extra !== 0) {
  15328. lc -= base_length[code];
  15329. send_bits(s, lc, extra); /* send the extra length bits */
  15330. }
  15331. dist--; /* dist is now the match distance - 1 */
  15332. code = d_code(dist);
  15333. //Assert (code < D_CODES, "bad d_code");
  15334. send_code(s, code, dtree); /* send the distance code */
  15335. extra = extra_dbits[code];
  15336. if (extra !== 0) {
  15337. dist -= base_dist[code];
  15338. send_bits(s, dist, extra); /* send the extra distance bits */
  15339. }
  15340. } /* literal or match pair ? */
  15341. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  15342. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  15343. // "pendingBuf overflow");
  15344. } while (lx < s.last_lit);
  15345. }
  15346. send_code(s, END_BLOCK, ltree);
  15347. }
  15348. /* ===========================================================================
  15349. * Construct one Huffman tree and assigns the code bit strings and lengths.
  15350. * Update the total bit length for the current block.
  15351. * IN assertion: the field freq is set for all tree elements.
  15352. * OUT assertions: the fields len and code are set to the optimal bit length
  15353. * and corresponding code. The length opt_len is updated; static_len is
  15354. * also updated if stree is not null. The field max_code is set.
  15355. */
  15356. function build_tree(s, desc)
  15357. // deflate_state *s;
  15358. // tree_desc *desc; /* the tree descriptor */
  15359. {
  15360. var tree = desc.dyn_tree;
  15361. var stree = desc.stat_desc.static_tree;
  15362. var has_stree = desc.stat_desc.has_stree;
  15363. var elems = desc.stat_desc.elems;
  15364. var n, m; /* iterate over heap elements */
  15365. var max_code = -1; /* largest code with non zero frequency */
  15366. var node; /* new node being created */
  15367. /* Construct the initial heap, with least frequent element in
  15368. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  15369. * heap[0] is not used.
  15370. */
  15371. s.heap_len = 0;
  15372. s.heap_max = HEAP_SIZE;
  15373. for (n = 0; n < elems; n++) {
  15374. if (tree[n * 2]/*.Freq*/ !== 0) {
  15375. s.heap[++s.heap_len] = max_code = n;
  15376. s.depth[n] = 0;
  15377. } else {
  15378. tree[n*2 + 1]/*.Len*/ = 0;
  15379. }
  15380. }
  15381. /* The pkzip format requires that at least one distance code exists,
  15382. * and that at least one bit should be sent even if there is only one
  15383. * possible code. So to avoid special checks later on we force at least
  15384. * two codes of non zero frequency.
  15385. */
  15386. while (s.heap_len < 2) {
  15387. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  15388. tree[node * 2]/*.Freq*/ = 1;
  15389. s.depth[node] = 0;
  15390. s.opt_len--;
  15391. if (has_stree) {
  15392. s.static_len -= stree[node*2 + 1]/*.Len*/;
  15393. }
  15394. /* node is 0 or 1 so it does not have extra bits */
  15395. }
  15396. desc.max_code = max_code;
  15397. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  15398. * establish sub-heaps of increasing lengths:
  15399. */
  15400. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  15401. /* Construct the Huffman tree by repeatedly combining the least two
  15402. * frequent nodes.
  15403. */
  15404. node = elems; /* next internal node of the tree */
  15405. do {
  15406. //pqremove(s, tree, n); /* n = node of least frequency */
  15407. /*** pqremove ***/
  15408. n = s.heap[1/*SMALLEST*/];
  15409. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  15410. pqdownheap(s, tree, 1/*SMALLEST*/);
  15411. /***/
  15412. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  15413. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  15414. s.heap[--s.heap_max] = m;
  15415. /* Create a new node father of n and m */
  15416. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  15417. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  15418. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  15419. /* and insert the new node in the heap */
  15420. s.heap[1/*SMALLEST*/] = node++;
  15421. pqdownheap(s, tree, 1/*SMALLEST*/);
  15422. } while (s.heap_len >= 2);
  15423. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  15424. /* At this point, the fields freq and dad are set. We can now
  15425. * generate the bit lengths.
  15426. */
  15427. gen_bitlen(s, desc);
  15428. /* The field len is now set, we can generate the bit codes */
  15429. gen_codes(tree, max_code, s.bl_count);
  15430. }
  15431. /* ===========================================================================
  15432. * Scan a literal or distance tree to determine the frequencies of the codes
  15433. * in the bit length tree.
  15434. */
  15435. function scan_tree(s, tree, max_code)
  15436. // deflate_state *s;
  15437. // ct_data *tree; /* the tree to be scanned */
  15438. // int max_code; /* and its largest code of non zero frequency */
  15439. {
  15440. var n; /* iterates over all tree elements */
  15441. var prevlen = -1; /* last emitted length */
  15442. var curlen; /* length of current code */
  15443. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  15444. var count = 0; /* repeat count of the current code */
  15445. var max_count = 7; /* max repeat count */
  15446. var min_count = 4; /* min repeat count */
  15447. if (nextlen === 0) {
  15448. max_count = 138;
  15449. min_count = 3;
  15450. }
  15451. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  15452. for (n = 0; n <= max_code; n++) {
  15453. curlen = nextlen;
  15454. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  15455. if (++count < max_count && curlen === nextlen) {
  15456. continue;
  15457. } else if (count < min_count) {
  15458. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  15459. } else if (curlen !== 0) {
  15460. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  15461. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  15462. } else if (count <= 10) {
  15463. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  15464. } else {
  15465. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  15466. }
  15467. count = 0;
  15468. prevlen = curlen;
  15469. if (nextlen === 0) {
  15470. max_count = 138;
  15471. min_count = 3;
  15472. } else if (curlen === nextlen) {
  15473. max_count = 6;
  15474. min_count = 3;
  15475. } else {
  15476. max_count = 7;
  15477. min_count = 4;
  15478. }
  15479. }
  15480. }
  15481. /* ===========================================================================
  15482. * Send a literal or distance tree in compressed form, using the codes in
  15483. * bl_tree.
  15484. */
  15485. function send_tree(s, tree, max_code)
  15486. // deflate_state *s;
  15487. // ct_data *tree; /* the tree to be scanned */
  15488. // int max_code; /* and its largest code of non zero frequency */
  15489. {
  15490. var n; /* iterates over all tree elements */
  15491. var prevlen = -1; /* last emitted length */
  15492. var curlen; /* length of current code */
  15493. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  15494. var count = 0; /* repeat count of the current code */
  15495. var max_count = 7; /* max repeat count */
  15496. var min_count = 4; /* min repeat count */
  15497. /* tree[max_code+1].Len = -1; */ /* guard already set */
  15498. if (nextlen === 0) {
  15499. max_count = 138;
  15500. min_count = 3;
  15501. }
  15502. for (n = 0; n <= max_code; n++) {
  15503. curlen = nextlen;
  15504. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  15505. if (++count < max_count && curlen === nextlen) {
  15506. continue;
  15507. } else if (count < min_count) {
  15508. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  15509. } else if (curlen !== 0) {
  15510. if (curlen !== prevlen) {
  15511. send_code(s, curlen, s.bl_tree);
  15512. count--;
  15513. }
  15514. //Assert(count >= 3 && count <= 6, " 3_6?");
  15515. send_code(s, REP_3_6, s.bl_tree);
  15516. send_bits(s, count-3, 2);
  15517. } else if (count <= 10) {
  15518. send_code(s, REPZ_3_10, s.bl_tree);
  15519. send_bits(s, count-3, 3);
  15520. } else {
  15521. send_code(s, REPZ_11_138, s.bl_tree);
  15522. send_bits(s, count-11, 7);
  15523. }
  15524. count = 0;
  15525. prevlen = curlen;
  15526. if (nextlen === 0) {
  15527. max_count = 138;
  15528. min_count = 3;
  15529. } else if (curlen === nextlen) {
  15530. max_count = 6;
  15531. min_count = 3;
  15532. } else {
  15533. max_count = 7;
  15534. min_count = 4;
  15535. }
  15536. }
  15537. }
  15538. /* ===========================================================================
  15539. * Construct the Huffman tree for the bit lengths and return the index in
  15540. * bl_order of the last bit length code to send.
  15541. */
  15542. function build_bl_tree(s) {
  15543. var max_blindex; /* index of last bit length code of non zero freq */
  15544. /* Determine the bit length frequencies for literal and distance trees */
  15545. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  15546. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  15547. /* Build the bit length tree: */
  15548. build_tree(s, s.bl_desc);
  15549. /* opt_len now includes the length of the tree representations, except
  15550. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  15551. */
  15552. /* Determine the number of bit length codes to send. The pkzip format
  15553. * requires that at least 4 bit length codes be sent. (appnote.txt says
  15554. * 3 but the actual value used is 4.)
  15555. */
  15556. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  15557. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  15558. break;
  15559. }
  15560. }
  15561. /* Update opt_len to include the bit length tree and counts */
  15562. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  15563. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  15564. // s->opt_len, s->static_len));
  15565. return max_blindex;
  15566. }
  15567. /* ===========================================================================
  15568. * Send the header for a block using dynamic Huffman trees: the counts, the
  15569. * lengths of the bit length codes, the literal tree and the distance tree.
  15570. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  15571. */
  15572. function send_all_trees(s, lcodes, dcodes, blcodes)
  15573. // deflate_state *s;
  15574. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  15575. {
  15576. var rank; /* index in bl_order */
  15577. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  15578. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  15579. // "too many codes");
  15580. //Tracev((stderr, "\nbl counts: "));
  15581. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  15582. send_bits(s, dcodes-1, 5);
  15583. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  15584. for (rank = 0; rank < blcodes; rank++) {
  15585. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  15586. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  15587. }
  15588. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  15589. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  15590. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  15591. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  15592. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  15593. }
  15594. /* ===========================================================================
  15595. * Check if the data type is TEXT or BINARY, using the following algorithm:
  15596. * - TEXT if the two conditions below are satisfied:
  15597. * a) There are no non-portable control characters belonging to the
  15598. * "black list" (0..6, 14..25, 28..31).
  15599. * b) There is at least one printable character belonging to the
  15600. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  15601. * - BINARY otherwise.
  15602. * - The following partially-portable control characters form a
  15603. * "gray list" that is ignored in this detection algorithm:
  15604. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  15605. * IN assertion: the fields Freq of dyn_ltree are set.
  15606. */
  15607. function detect_data_type(s) {
  15608. /* black_mask is the bit mask of black-listed bytes
  15609. * set bits 0..6, 14..25, and 28..31
  15610. * 0xf3ffc07f = binary 11110011111111111100000001111111
  15611. */
  15612. var black_mask = 0xf3ffc07f;
  15613. var n;
  15614. /* Check for non-textual ("black-listed") bytes. */
  15615. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  15616. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  15617. return Z_BINARY;
  15618. }
  15619. }
  15620. /* Check for textual ("white-listed") bytes. */
  15621. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  15622. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  15623. return Z_TEXT;
  15624. }
  15625. for (n = 32; n < LITERALS; n++) {
  15626. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  15627. return Z_TEXT;
  15628. }
  15629. }
  15630. /* There are no "black-listed" or "white-listed" bytes:
  15631. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  15632. */
  15633. return Z_BINARY;
  15634. }
  15635. var static_init_done = false;
  15636. /* ===========================================================================
  15637. * Initialize the tree data structures for a new zlib stream.
  15638. */
  15639. function _tr_init(s)
  15640. {
  15641. if (!static_init_done) {
  15642. tr_static_init();
  15643. static_init_done = true;
  15644. }
  15645. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  15646. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  15647. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  15648. s.bi_buf = 0;
  15649. s.bi_valid = 0;
  15650. /* Initialize the first block of the first file: */
  15651. init_block(s);
  15652. }
  15653. /* ===========================================================================
  15654. * Send a stored block
  15655. */
  15656. function _tr_stored_block(s, buf, stored_len, last)
  15657. //DeflateState *s;
  15658. //charf *buf; /* input block */
  15659. //ulg stored_len; /* length of input block */
  15660. //int last; /* one if this is the last block for a file */
  15661. {
  15662. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  15663. copy_block(s, buf, stored_len, true); /* with header */
  15664. }
  15665. /* ===========================================================================
  15666. * Send one empty static block to give enough lookahead for inflate.
  15667. * This takes 10 bits, of which 7 may remain in the bit buffer.
  15668. */
  15669. function _tr_align(s) {
  15670. send_bits(s, STATIC_TREES<<1, 3);
  15671. send_code(s, END_BLOCK, static_ltree);
  15672. bi_flush(s);
  15673. }
  15674. /* ===========================================================================
  15675. * Determine the best encoding for the current block: dynamic trees, static
  15676. * trees or store, and output the encoded block to the zip file.
  15677. */
  15678. function _tr_flush_block(s, buf, stored_len, last)
  15679. //DeflateState *s;
  15680. //charf *buf; /* input block, or NULL if too old */
  15681. //ulg stored_len; /* length of input block */
  15682. //int last; /* one if this is the last block for a file */
  15683. {
  15684. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  15685. var max_blindex = 0; /* index of last bit length code of non zero freq */
  15686. /* Build the Huffman trees unless a stored block is forced */
  15687. if (s.level > 0) {
  15688. /* Check if the file is binary or text */
  15689. if (s.strm.data_type === Z_UNKNOWN) {
  15690. s.strm.data_type = detect_data_type(s);
  15691. }
  15692. /* Construct the literal and distance trees */
  15693. build_tree(s, s.l_desc);
  15694. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  15695. // s->static_len));
  15696. build_tree(s, s.d_desc);
  15697. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  15698. // s->static_len));
  15699. /* At this point, opt_len and static_len are the total bit lengths of
  15700. * the compressed block data, excluding the tree representations.
  15701. */
  15702. /* Build the bit length tree for the above two trees, and get the index
  15703. * in bl_order of the last bit length code to send.
  15704. */
  15705. max_blindex = build_bl_tree(s);
  15706. /* Determine the best encoding. Compute the block lengths in bytes. */
  15707. opt_lenb = (s.opt_len+3+7) >>> 3;
  15708. static_lenb = (s.static_len+3+7) >>> 3;
  15709. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  15710. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  15711. // s->last_lit));
  15712. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  15713. } else {
  15714. // Assert(buf != (char*)0, "lost buf");
  15715. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  15716. }
  15717. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  15718. /* 4: two words for the lengths */
  15719. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  15720. * Otherwise we can't have processed more than WSIZE input bytes since
  15721. * the last block flush, because compression would have been
  15722. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  15723. * transform a block into a stored block.
  15724. */
  15725. _tr_stored_block(s, buf, stored_len, last);
  15726. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  15727. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  15728. compress_block(s, static_ltree, static_dtree);
  15729. } else {
  15730. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  15731. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  15732. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  15733. }
  15734. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  15735. /* The above check is made mod 2^32, for files larger than 512 MB
  15736. * and uLong implemented on 32 bits.
  15737. */
  15738. init_block(s);
  15739. if (last) {
  15740. bi_windup(s);
  15741. }
  15742. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  15743. // s->compressed_len-7*last));
  15744. }
  15745. /* ===========================================================================
  15746. * Save the match info and tally the frequency counts. Return true if
  15747. * the current block must be flushed.
  15748. */
  15749. function _tr_tally(s, dist, lc)
  15750. // deflate_state *s;
  15751. // unsigned dist; /* distance of matched string */
  15752. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  15753. {
  15754. //var out_length, in_length, dcode;
  15755. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  15756. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  15757. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  15758. s.last_lit++;
  15759. if (dist === 0) {
  15760. /* lc is the unmatched char */
  15761. s.dyn_ltree[lc*2]/*.Freq*/++;
  15762. } else {
  15763. s.matches++;
  15764. /* Here, lc is the match length - MIN_MATCH */
  15765. dist--; /* dist = match distance - 1 */
  15766. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  15767. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  15768. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  15769. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  15770. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  15771. }
  15772. // (!) This block is disabled in zlib defailts,
  15773. // don't enable it for binary compatibility
  15774. //#ifdef TRUNCATE_BLOCK
  15775. // /* Try to guess if it is profitable to stop the current block here */
  15776. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  15777. // /* Compute an upper bound for the compressed length */
  15778. // out_length = s.last_lit*8;
  15779. // in_length = s.strstart - s.block_start;
  15780. //
  15781. // for (dcode = 0; dcode < D_CODES; dcode++) {
  15782. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  15783. // }
  15784. // out_length >>>= 3;
  15785. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  15786. // // s->last_lit, in_length, out_length,
  15787. // // 100L - out_length*100L/in_length));
  15788. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  15789. // return true;
  15790. // }
  15791. // }
  15792. //#endif
  15793. return (s.last_lit === s.lit_bufsize-1);
  15794. /* We avoid equality with lit_bufsize because of wraparound at 64K
  15795. * on 16 bit machines and because stored blocks are restricted to
  15796. * 64K-1 bytes.
  15797. */
  15798. }
  15799. exports._tr_init = _tr_init;
  15800. exports._tr_stored_block = _tr_stored_block;
  15801. exports._tr_flush_block = _tr_flush_block;
  15802. exports._tr_tally = _tr_tally;
  15803. exports._tr_align = _tr_align;
  15804. },{"../utils/common":39}],51:[function(require,module,exports){
  15805. 'use strict';
  15806. function ZStream() {
  15807. /* next input byte */
  15808. this.input = null; // JS specific, because we have no pointers
  15809. this.next_in = 0;
  15810. /* number of bytes available at input */
  15811. this.avail_in = 0;
  15812. /* total number of input bytes read so far */
  15813. this.total_in = 0;
  15814. /* next output byte should be put there */
  15815. this.output = null; // JS specific, because we have no pointers
  15816. this.next_out = 0;
  15817. /* remaining free space at output */
  15818. this.avail_out = 0;
  15819. /* total number of bytes output so far */
  15820. this.total_out = 0;
  15821. /* last error message, NULL if no error */
  15822. this.msg = ''/*Z_NULL*/;
  15823. /* not visible by applications */
  15824. this.state = null;
  15825. /* best guess about the data type: binary or text */
  15826. this.data_type = 2/*Z_UNKNOWN*/;
  15827. /* adler32 value of the uncompressed data */
  15828. this.adler = 0;
  15829. }
  15830. module.exports = ZStream;
  15831. },{}],52:[function(require,module,exports){
  15832. module.exports = function arrayEquals(array) {
  15833. // if the other array is a falsy value, return
  15834. if (!array)
  15835. return false;
  15836. // compare lengths - can save a lot of time
  15837. if (this.length != array.length)
  15838. return false;
  15839. for (var i = 0, l = this.length; i < l; i++) {
  15840. // Check if we have nested arrays
  15841. if (this[i] instanceof Array && array[i] instanceof Array) {
  15842. // recurse into the nested arrays
  15843. if (!arrayEquals.apply(this[i], [array[i]]))
  15844. return false;
  15845. } else if (this[i] != array[i]) {
  15846. // Warning - two different object instances will never be equal:
  15847. // {x:20} != {x:20}
  15848. return false;
  15849. }
  15850. }
  15851. return true;
  15852. }
  15853. },{}],53:[function(require,module,exports){
  15854. exports.Interop = require('./interop');
  15855. },{"./interop":54}],54:[function(require,module,exports){
  15856. "use strict";
  15857. var transform = require('./transform');
  15858. var arrayEquals = require('./array-equals');
  15859. function Interop() {
  15860. /**
  15861. * This map holds the most recent Unified Plan offer/answer SDP that was
  15862. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  15863. * the SDP string as values.
  15864. *
  15865. * @type {{}}
  15866. */
  15867. this.cache = {};
  15868. }
  15869. module.exports = Interop;
  15870. /**
  15871. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  15872. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  15873. * application.
  15874. *
  15875. * @param desc
  15876. * @returns {*}
  15877. */
  15878. Interop.prototype.toPlanB = function(desc) {
  15879. //#region Preliminary input validation.
  15880. if (typeof desc !== 'object' || desc === null ||
  15881. typeof desc.sdp !== 'string') {
  15882. console.warn('An empty description was passed as an argument.');
  15883. return desc;
  15884. }
  15885. // Objectify the SDP for easier manipulation.
  15886. var session = transform.parse(desc.sdp);
  15887. // If the SDP contains no media, there's nothing to transform.
  15888. if (typeof session.media === 'undefined' ||
  15889. !Array.isArray(session.media) || session.media.length === 0) {
  15890. console.warn('The description has no media.');
  15891. return desc;
  15892. }
  15893. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  15894. // SDP has a video, an audio and a data "channel" at most.
  15895. if (session.media.length <= 3 && session.media.every(function(m) {
  15896. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  15897. })) {
  15898. console.warn('This description does not look like Unified Plan.');
  15899. return desc;
  15900. }
  15901. //#endregion
  15902. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  15903. // -> Unified Plan transformation.
  15904. this.cache[desc.type] = desc.sdp;
  15905. //#region Convert from Unified Plan to Plan B.
  15906. // We rebuild the session.media array.
  15907. var media = session.media;
  15908. session.media = [];
  15909. // Associative array that maps channel types to channel objects for fast
  15910. // access to channel objects by their type, e.g. type2bl['audio']->channel
  15911. // obj.
  15912. var type2bl = {};
  15913. // Used to build the group:BUNDLE value after the channels construction
  15914. // loop.
  15915. var types = [];
  15916. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  15917. media.forEach(function(unifiedLine) {
  15918. // rtcp-mux is required in the Plan B SDP.
  15919. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  15920. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  15921. unifiedLine.direction !== 'inactive') {
  15922. throw new Error('Cannot convert to Plan B because m-lines ' +
  15923. 'without the rtcp-mux attribute were found.');
  15924. }
  15925. if (unifiedLine.type === 'application') {
  15926. session.media.push(unifiedLine);
  15927. types.push(unifiedLine.mid);
  15928. return;
  15929. }
  15930. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  15931. // as the channel basis.
  15932. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  15933. type2bl[unifiedLine.type] = unifiedLine;
  15934. }
  15935. // Add sources to the channel and handle a=msid.
  15936. if (typeof unifiedLine.sources === 'object') {
  15937. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  15938. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  15939. type2bl[unifiedLine.type].sources = {};
  15940. // Assign the sources to the channel.
  15941. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  15942. if (typeof unifiedLine.msid !== 'undefined') {
  15943. // In Plan B the msid is an SSRC attribute. Also, we don't
  15944. // care about the obsolete label and mslabel attributes.
  15945. //
  15946. // Note that it is not guaranteed that the unifiedLine will have
  15947. // an msid. recvonly channels in particular don't have one.
  15948. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  15949. }
  15950. // NOTE ssrcs in ssrc groups will share msids, as
  15951. // draft-uberti-rtcweb-plan-00 mandates.
  15952. });
  15953. }
  15954. // Add ssrc groups to the channel.
  15955. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  15956. Array.isArray(unifiedLine.ssrcGroups)) {
  15957. // Create the ssrcGroups array, if it's not defined.
  15958. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  15959. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  15960. type2bl[unifiedLine.type].ssrcGroups = [];
  15961. }
  15962. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  15963. }
  15964. if (type2bl[unifiedLine.type] === unifiedLine) {
  15965. // Copy ICE related stuff from the principal media line.
  15966. unifiedLine.candidates = media[0].candidates;
  15967. unifiedLine.iceUfrag = media[0].iceUfrag;
  15968. unifiedLine.icePwd = media[0].icePwd;
  15969. unifiedLine.fingerprint = media[0].fingerprint;
  15970. // Plan B mids are in ['audio', 'video', 'data']
  15971. unifiedLine.mid = unifiedLine.type;
  15972. // Plan B doesn't support/need the bundle-only attribute.
  15973. delete unifiedLine.bundleOnly;
  15974. // In Plan B the msid is an SSRC attribute.
  15975. delete unifiedLine.msid;
  15976. // Used to build the group:BUNDLE value after this loop.
  15977. types.push(unifiedLine.type);
  15978. // Add the channel to the new media array.
  15979. session.media.push(unifiedLine);
  15980. }
  15981. });
  15982. // We regenerate the BUNDLE group with the new mids.
  15983. session.groups.some(function(group) {
  15984. if (group.type === 'BUNDLE') {
  15985. group.mids = types.join(' ');
  15986. return true;
  15987. }
  15988. });
  15989. // msid semantic
  15990. session.msidSemantic = {
  15991. semantic: 'WMS',
  15992. token: '*'
  15993. };
  15994. var resStr = transform.write(session);
  15995. return new RTCSessionDescription({
  15996. type: desc.type,
  15997. sdp: resStr
  15998. });
  15999. //#endregion
  16000. };
  16001. /**
  16002. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  16003. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  16004. * to FF.
  16005. *
  16006. * @param desc
  16007. * @returns {*}
  16008. */
  16009. Interop.prototype.toUnifiedPlan = function(desc) {
  16010. //#region Preliminary input validation.
  16011. if (typeof desc !== 'object' || desc === null ||
  16012. typeof desc.sdp !== 'string') {
  16013. console.warn('An empty description was passed as an argument.');
  16014. return desc;
  16015. }
  16016. var session = transform.parse(desc.sdp);
  16017. // If the SDP contains no media, there's nothing to transform.
  16018. if (typeof session.media === 'undefined' ||
  16019. !Array.isArray(session.media) || session.media.length === 0) {
  16020. console.warn('The description has no media.');
  16021. return desc;
  16022. }
  16023. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  16024. // a video, an audio and a data "channel" at most.
  16025. if (session.media.length > 3 || !session.media.every(function(m) {
  16026. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  16027. })) {
  16028. console.warn('This description does not look like Plan B.');
  16029. return desc;
  16030. }
  16031. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  16032. var mids = [];
  16033. session.media.forEach(function(m) {
  16034. mids.push(m.mid);
  16035. });
  16036. var hasBundle = false;
  16037. if (typeof session.groups !== 'undefined' &&
  16038. Array.isArray(session.groups)) {
  16039. hasBundle = session.groups.every(function(g) {
  16040. return g.type !== 'BUNDLE' ||
  16041. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  16042. });
  16043. }
  16044. if (!hasBundle) {
  16045. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  16046. " are not bundled were found.");
  16047. }
  16048. //#endregion
  16049. //#region Convert from Plan B to Unified Plan.
  16050. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  16051. // rebuild an equivalent Unified Plan offer/answer.
  16052. //
  16053. // For example, if this is a local answer (in Unified Plan style) that we
  16054. // convert to Plan B prior to handing it over to the application (the
  16055. // PeerConnection wrapper called us, for instance, after a successful
  16056. // createAnswer), we want to remember the m-line at which we've seen the
  16057. // (local) SSRC. That's because when the application wants to do call the
  16058. // SLD method, forcing us to do the inverse transformation (from Plan B to
  16059. // Unified Plan), we need to know to which m-line to assign the (local)
  16060. // SSRC. We also need to know all the other m-lines that the original
  16061. // answer had and include them in the transformed answer as well.
  16062. //
  16063. // Another example is if this is a remote offer that we convert to Plan B
  16064. // prior to giving it to the application, we want to remember the mid at
  16065. // which we've seen the (remote) SSRC.
  16066. //
  16067. // In the iteration that follows, we use the cached Unified Plan (if it
  16068. // exists) to assign mids to ssrcs.
  16069. var cached;
  16070. if (typeof this.cache[desc.type] !== 'undefined') {
  16071. cached = transform.parse(this.cache[desc.type]);
  16072. }
  16073. // A helper map that sends mids to m-line objects. We use it later to
  16074. // rebuild the Unified Plan style session.media array.
  16075. var mid2ul = {};
  16076. session.media.forEach(function(bLine) {
  16077. if ((typeof bLine.rtcpMux !== 'string' ||
  16078. bLine.rtcpMux !== 'rtcp-mux') &&
  16079. bLine.direction !== 'inactive') {
  16080. throw new Error("Cannot convert to Unified Plan because m-lines " +
  16081. "without the rtcp-mux attribute were found.");
  16082. }
  16083. if (bLine.type === 'application') {
  16084. mid2ul[bLine.mid] = bLine;
  16085. return;
  16086. }
  16087. // With rtcp-mux and bundle all the channels should have the same ICE
  16088. // stuff.
  16089. var sources = bLine.sources;
  16090. var ssrcGroups = bLine.ssrcGroups;
  16091. var candidates = bLine.candidates;
  16092. var iceUfrag = bLine.iceUfrag;
  16093. var icePwd = bLine.icePwd;
  16094. var fingerprint = bLine.fingerprint;
  16095. var port = bLine.port;
  16096. // We'll use the "bLine" object as a prototype for each new "mLine"
  16097. // that we create, but first we need to clean it up a bit.
  16098. delete bLine.sources;
  16099. delete bLine.ssrcGroups;
  16100. delete bLine.candidates;
  16101. delete bLine.iceUfrag;
  16102. delete bLine.icePwd;
  16103. delete bLine.fingerprint;
  16104. delete bLine.port;
  16105. delete bLine.mid;
  16106. // inverted ssrc group map
  16107. var ssrc2group = {};
  16108. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  16109. ssrcGroups.forEach(function (ssrcGroup) {
  16110. // TODO(gp) find out how to receive simulcast with FF. For the
  16111. // time being, hide it.
  16112. if (ssrcGroup.semantics === 'SIM') {
  16113. return;
  16114. }
  16115. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  16116. Array.isArray(ssrcGroup.ssrcs)) {
  16117. ssrcGroup.ssrcs.forEach(function (ssrc) {
  16118. if (typeof ssrc2group[ssrc] === 'undefined') {
  16119. ssrc2group[ssrc] = [];
  16120. }
  16121. ssrc2group[ssrc].push(ssrcGroup);
  16122. });
  16123. }
  16124. });
  16125. }
  16126. // ssrc to m-line index.
  16127. var ssrc2ml = {};
  16128. if (typeof sources === 'object') {
  16129. // Explode the Plan B channel sources with one m-line per source.
  16130. Object.keys(sources).forEach(function(ssrc) {
  16131. // The (unified) m-line for this SSRC. We either create it from
  16132. // scratch or, if it's a grouped SSRC, we re-use a related
  16133. // mline. In other words, if the source is grouped with another
  16134. // source, put the two together in the same m-line.
  16135. var unifiedLine;
  16136. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  16137. Array.isArray(ssrc2group[ssrc])) {
  16138. ssrc2group[ssrc].some(function (ssrcGroup) {
  16139. // ssrcGroup.ssrcs *is* an Array, no need to check
  16140. // again here.
  16141. return ssrcGroup.ssrcs.some(function (related) {
  16142. if (typeof ssrc2ml[related] === 'object') {
  16143. unifiedLine = ssrc2ml[related];
  16144. return true;
  16145. }
  16146. });
  16147. });
  16148. }
  16149. if (typeof unifiedLine === 'object') {
  16150. // the m-line already exists. Just add the source.
  16151. unifiedLine.sources[ssrc] = sources[ssrc];
  16152. delete sources[ssrc].msid;
  16153. } else {
  16154. // Use the "bLine" as a prototype for the "unifiedLine".
  16155. unifiedLine = Object.create(bLine);
  16156. ssrc2ml[ssrc] = unifiedLine;
  16157. if (typeof sources[ssrc].msid !== 'undefined') {
  16158. // Assign the msid of the source to the m-line. Note
  16159. // that it is not guaranteed that the source will have
  16160. // msid. In particular "recvonly" sources don't have an
  16161. // msid. Note that "recvonly" is a term only defined
  16162. // for m-lines.
  16163. unifiedLine.msid = sources[ssrc].msid;
  16164. delete sources[ssrc].msid;
  16165. }
  16166. // We assign one SSRC per media line.
  16167. unifiedLine.sources = {};
  16168. unifiedLine.sources[ssrc] = sources[ssrc];
  16169. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  16170. // Use the cached Unified Plan SDP (if it exists) to assign
  16171. // SSRCs to mids.
  16172. if (typeof cached !== 'undefined' &&
  16173. typeof cached.media !== 'undefined' &&
  16174. Array.isArray(cached.media)) {
  16175. cached.media.forEach(function (m) {
  16176. if (typeof m.sources === 'object') {
  16177. Object.keys(m.sources).forEach(function (s) {
  16178. if (s === ssrc) {
  16179. unifiedLine.mid = m.mid;
  16180. }
  16181. });
  16182. }
  16183. });
  16184. }
  16185. if (typeof unifiedLine.mid === 'undefined') {
  16186. // If this is an SSRC that we see for the first time
  16187. // assign it a new mid. This is typically the case when
  16188. // this method is called to transform a remote
  16189. // description for the first time or when there is a
  16190. // new SSRC in the remote description because a new
  16191. // peer has joined the conference. Local SSRCs should
  16192. // have already been added to the map in the toPlanB
  16193. // method.
  16194. //
  16195. // Because FF generates answers in Unified Plan style,
  16196. // we MUST already have a cached answer with all the
  16197. // local SSRCs mapped to some m-line/mid.
  16198. if (desc.type === 'answer') {
  16199. throw new Error("An unmapped SSRC was found.");
  16200. }
  16201. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  16202. }
  16203. // Include the candidates in the 1st media line.
  16204. unifiedLine.candidates = candidates;
  16205. unifiedLine.iceUfrag = iceUfrag;
  16206. unifiedLine.icePwd = icePwd;
  16207. unifiedLine.fingerprint = fingerprint;
  16208. unifiedLine.port = port;
  16209. mid2ul[unifiedLine.mid] = unifiedLine;
  16210. }
  16211. });
  16212. }
  16213. });
  16214. // Rebuild the media array in the right order and add the missing mLines
  16215. // (missing from the Plan B SDP).
  16216. session.media = [];
  16217. mids = []; // reuse
  16218. if (desc.type === 'answer') {
  16219. // The media lines in the answer must match the media lines in the
  16220. // offer. The order is important too. Here we assume that Firefox is the
  16221. // answerer, so we merely have to use the reconstructed (unified) answer
  16222. // to update the cached (unified) answer accordingly.
  16223. //
  16224. // In the general case, one would have to use the cached (unified) offer
  16225. // to find the m-lines that are missing from the reconstructed answer,
  16226. // potentially grabbing them from the cached (unified) answer. One has
  16227. // to be carefull with this approach because inactive m-lines do not
  16228. // always have an mid, making it tricky (impossible?) to find where
  16229. // exactly and which m-lines are missing from the reconstructed answer.
  16230. for (var i = 0; i < cached.media.length; i++) {
  16231. var unifiedLine = cached.media[i];
  16232. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  16233. // The mid isn't in the reconstructed (unified) answer.
  16234. // This is either a (unified) m-line containing a remote
  16235. // track only, or a (unified) m-line containing a remote
  16236. // track and a local track that has been removed.
  16237. // In either case, it MUST exist in the cached
  16238. // (unified) answer.
  16239. //
  16240. // In case this is a removed local track, clean-up
  16241. // the (unified) m-line and make sure it's 'recvonly' or
  16242. // 'inactive'.
  16243. delete unifiedLine.msid;
  16244. delete unifiedLine.sources;
  16245. delete unifiedLine.ssrcGroups;
  16246. if (!unifiedLine.direction
  16247. || unifiedLine.direction === 'sendrecv')
  16248. unifiedLine.direction = 'recvonly';
  16249. if (!unifiedLine.direction
  16250. || unifiedLine.direction === 'sendonly')
  16251. unifiedLine.direction = 'inactive';
  16252. } else {
  16253. // This is an (unified) m-line/channel that contains a local
  16254. // track (sendrecv or sendonly channel) or it's a unified
  16255. // recvonly m-line/channel. In either case, since we're
  16256. // going from PlanB -> Unified Plan this m-line MUST
  16257. // exist in the cached answer.
  16258. }
  16259. session.media.push(unifiedLine);
  16260. if (typeof unifiedLine.mid === 'string') {
  16261. // inactive lines don't/may not have an mid.
  16262. mids.push(unifiedLine.mid);
  16263. }
  16264. }
  16265. } else {
  16266. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  16267. // under any circumstances. If we are no longer interested in sending a
  16268. // track, we just remove the msid and ssrc attributes and set it to
  16269. // either a=recvonly (as the reofferer, we must use recvonly if the
  16270. // other side was previously sending on the m-section, but we can also
  16271. // leave the possibility open if it wasn't previously in use), or
  16272. // a=inacive.
  16273. if (typeof cached !== 'undefined' &&
  16274. typeof cached.media !== 'undefined' &&
  16275. Array.isArray(cached.media)) {
  16276. cached.media.forEach(function(unifiedLine) {
  16277. mids.push(unifiedLine.mid);
  16278. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  16279. session.media.push(mid2ul[unifiedLine.mid]);
  16280. } else {
  16281. delete unifiedLine.msid;
  16282. delete unifiedLine.sources;
  16283. delete unifiedLine.ssrcGroups;
  16284. if (!unifiedLine.direction
  16285. || unifiedLine.direction === 'sendrecv')
  16286. unifiedLine.direction = 'recvonly';
  16287. if (!unifiedLine.direction
  16288. || unifiedLine.direction === 'sendonly')
  16289. unifiedLine.direction = 'inactive';
  16290. session.media.push(unifiedLine);
  16291. }
  16292. });
  16293. }
  16294. // Add all the remaining (new) m-lines of the transformed SDP.
  16295. Object.keys(mid2ul).forEach(function(mid) {
  16296. if (mids.indexOf(mid) === -1) {
  16297. mids.push(mid);
  16298. if (typeof mid2ul[mid].direction === 'recvonly') {
  16299. // This is a remote recvonly channel. Add its SSRC to the
  16300. // appropriate sendrecv or sendonly channel.
  16301. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  16302. session.media.some(function (unifiedLine) {
  16303. if ((unifiedLine.direction === 'sendrecv' ||
  16304. unifiedLine.direction === 'sendonly') &&
  16305. unifiedLine.type === mid2ul[mid].type) {
  16306. // mid2ul[mid] shouldn't have any ssrc-groups
  16307. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  16308. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  16309. });
  16310. return true;
  16311. }
  16312. });
  16313. } else {
  16314. session.media.push(mid2ul[mid]);
  16315. }
  16316. }
  16317. });
  16318. }
  16319. // We regenerate the BUNDLE group (since we regenerated the mids)
  16320. session.groups.some(function(group) {
  16321. if (group.type === 'BUNDLE') {
  16322. group.mids = mids.join(' ');
  16323. return true;
  16324. }
  16325. });
  16326. // msid semantic
  16327. session.msidSemantic = {
  16328. semantic: 'WMS',
  16329. token: '*'
  16330. };
  16331. var resStr = transform.write(session);
  16332. // Cache the transformed SDP (Unified Plan) for later re-use in this
  16333. // function.
  16334. this.cache[desc.type] = resStr;
  16335. return new RTCSessionDescription({
  16336. type: desc.type,
  16337. sdp: resStr
  16338. });
  16339. //#endregion
  16340. };
  16341. },{"./array-equals":52,"./transform":55}],55:[function(require,module,exports){
  16342. var transform = require('sdp-transform');
  16343. exports.write = function(session, opts) {
  16344. if (typeof session !== 'undefined' &&
  16345. typeof session.media !== 'undefined' &&
  16346. Array.isArray(session.media)) {
  16347. session.media.forEach(function (mLine) {
  16348. // expand sources to ssrcs
  16349. if (typeof mLine.sources !== 'undefined' &&
  16350. Object.keys(mLine.sources).length !== 0) {
  16351. mLine.ssrcs = [];
  16352. Object.keys(mLine.sources).forEach(function (ssrc) {
  16353. var source = mLine.sources[ssrc];
  16354. Object.keys(source).forEach(function (attribute) {
  16355. mLine.ssrcs.push({
  16356. id: ssrc,
  16357. attribute: attribute,
  16358. value: source[attribute]
  16359. });
  16360. });
  16361. });
  16362. delete mLine.sources;
  16363. }
  16364. // join ssrcs in ssrc groups
  16365. if (typeof mLine.ssrcGroups !== 'undefined' &&
  16366. Array.isArray(mLine.ssrcGroups)) {
  16367. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  16368. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  16369. Array.isArray(ssrcGroup.ssrcs)) {
  16370. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  16371. }
  16372. });
  16373. }
  16374. });
  16375. }
  16376. // join group mids
  16377. if (typeof session !== 'undefined' &&
  16378. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  16379. session.groups.forEach(function (g) {
  16380. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  16381. g.mids = g.mids.join(' ');
  16382. }
  16383. });
  16384. }
  16385. return transform.write(session, opts);
  16386. };
  16387. exports.parse = function(sdp) {
  16388. var session = transform.parse(sdp);
  16389. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  16390. Array.isArray(session.media)) {
  16391. session.media.forEach(function (mLine) {
  16392. // group sources attributes by ssrc
  16393. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  16394. mLine.sources = {};
  16395. mLine.ssrcs.forEach(function (ssrc) {
  16396. if (!mLine.sources[ssrc.id])
  16397. mLine.sources[ssrc.id] = {};
  16398. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  16399. });
  16400. delete mLine.ssrcs;
  16401. }
  16402. // split ssrcs in ssrc groups
  16403. if (typeof mLine.ssrcGroups !== 'undefined' &&
  16404. Array.isArray(mLine.ssrcGroups)) {
  16405. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  16406. if (typeof ssrcGroup.ssrcs === 'string') {
  16407. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  16408. }
  16409. });
  16410. }
  16411. });
  16412. }
  16413. // split group mids
  16414. if (typeof session !== 'undefined' &&
  16415. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  16416. session.groups.forEach(function (g) {
  16417. if (typeof g.mids === 'string') {
  16418. g.mids = g.mids.split(' ');
  16419. }
  16420. });
  16421. }
  16422. return session;
  16423. };
  16424. },{"sdp-transform":57}],56:[function(require,module,exports){
  16425. var grammar = module.exports = {
  16426. v: [{
  16427. name: 'version',
  16428. reg: /^(\d*)$/
  16429. }],
  16430. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  16431. // NB: sessionId will be a String in most cases because it is huge
  16432. name: 'origin',
  16433. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  16434. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  16435. format: "%s %s %d %s IP%d %s"
  16436. }],
  16437. // default parsing of these only (though some of these feel outdated)
  16438. s: [{ name: 'name' }],
  16439. i: [{ name: 'description' }],
  16440. u: [{ name: 'uri' }],
  16441. e: [{ name: 'email' }],
  16442. p: [{ name: 'phone' }],
  16443. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  16444. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  16445. //k: [{}], // outdated thing ignored
  16446. t: [{ //t=0 0
  16447. name: 'timing',
  16448. reg: /^(\d*) (\d*)/,
  16449. names: ['start', 'stop'],
  16450. format: "%d %d"
  16451. }],
  16452. c: [{ //c=IN IP4 10.47.197.26
  16453. name: 'connection',
  16454. reg: /^IN IP(\d) (\S*)/,
  16455. names: ['version', 'ip'],
  16456. format: "IN IP%d %s"
  16457. }],
  16458. b: [{ //b=AS:4000
  16459. push: 'bandwidth',
  16460. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  16461. names: ['type', 'limit'],
  16462. format: "%s:%s"
  16463. }],
  16464. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  16465. // NB: special - pushes to session
  16466. // TODO: rtp/fmtp should be filtered by the payloads found here?
  16467. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  16468. names: ['type', 'port', 'protocol', 'payloads'],
  16469. format: "%s %d %s %s"
  16470. }],
  16471. a: [
  16472. { //a=rtpmap:110 opus/48000/2
  16473. push: 'rtp',
  16474. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  16475. names: ['payload', 'codec', 'rate', 'encoding'],
  16476. format: function (o) {
  16477. return (o.encoding) ?
  16478. "rtpmap:%d %s/%s/%s":
  16479. "rtpmap:%d %s/%s";
  16480. }
  16481. },
  16482. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  16483. push: 'fmtp',
  16484. reg: /^fmtp:(\d*) (\S*)/,
  16485. names: ['payload', 'config'],
  16486. format: "fmtp:%d %s"
  16487. },
  16488. { //a=control:streamid=0
  16489. name: 'control',
  16490. reg: /^control:(.*)/,
  16491. format: "control:%s"
  16492. },
  16493. { //a=rtcp:65179 IN IP4 193.84.77.194
  16494. name: 'rtcp',
  16495. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  16496. names: ['port', 'netType', 'ipVer', 'address'],
  16497. format: function (o) {
  16498. return (o.address != null) ?
  16499. "rtcp:%d %s IP%d %s":
  16500. "rtcp:%d";
  16501. }
  16502. },
  16503. { //a=rtcp-fb:98 trr-int 100
  16504. push: 'rtcpFbTrrInt',
  16505. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  16506. names: ['payload', 'value'],
  16507. format: "rtcp-fb:%d trr-int %d"
  16508. },
  16509. { //a=rtcp-fb:98 nack rpsi
  16510. push: 'rtcpFb',
  16511. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  16512. names: ['payload', 'type', 'subtype'],
  16513. format: function (o) {
  16514. return (o.subtype != null) ?
  16515. "rtcp-fb:%s %s %s":
  16516. "rtcp-fb:%s %s";
  16517. }
  16518. },
  16519. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  16520. //a=extmap:1/recvonly URI-gps-string
  16521. push: 'ext',
  16522. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  16523. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  16524. format: function (o) {
  16525. return (o.config != null) ?
  16526. "extmap:%s %s %s":
  16527. "extmap:%s %s";
  16528. }
  16529. },
  16530. {
  16531. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  16532. push: 'crypto',
  16533. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  16534. names: ['id', 'suite', 'config', 'sessionConfig'],
  16535. format: function (o) {
  16536. return (o.sessionConfig != null) ?
  16537. "crypto:%d %s %s %s":
  16538. "crypto:%d %s %s";
  16539. }
  16540. },
  16541. { //a=setup:actpass
  16542. name: 'setup',
  16543. reg: /^setup:(\w*)/,
  16544. format: "setup:%s"
  16545. },
  16546. { //a=mid:1
  16547. name: 'mid',
  16548. reg: /^mid:([^\s]*)/,
  16549. format: "mid:%s"
  16550. },
  16551. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  16552. name: 'msid',
  16553. reg: /^msid:(.*)/,
  16554. format: "msid:%s"
  16555. },
  16556. { //a=ptime:20
  16557. name: 'ptime',
  16558. reg: /^ptime:(\d*)/,
  16559. format: "ptime:%d"
  16560. },
  16561. { //a=maxptime:60
  16562. name: 'maxptime',
  16563. reg: /^maxptime:(\d*)/,
  16564. format: "maxptime:%d"
  16565. },
  16566. { //a=sendrecv
  16567. name: 'direction',
  16568. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  16569. },
  16570. { //a=ice-lite
  16571. name: 'icelite',
  16572. reg: /^(ice-lite)/
  16573. },
  16574. { //a=ice-ufrag:F7gI
  16575. name: 'iceUfrag',
  16576. reg: /^ice-ufrag:(\S*)/,
  16577. format: "ice-ufrag:%s"
  16578. },
  16579. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  16580. name: 'icePwd',
  16581. reg: /^ice-pwd:(\S*)/,
  16582. format: "ice-pwd:%s"
  16583. },
  16584. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  16585. name: 'fingerprint',
  16586. reg: /^fingerprint:(\S*) (\S*)/,
  16587. names: ['type', 'hash'],
  16588. format: "fingerprint:%s %s"
  16589. },
  16590. {
  16591. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  16592. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  16593. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  16594. push:'candidates',
  16595. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  16596. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  16597. format: function (o) {
  16598. var str = "candidate:%s %d %s %d %s %d typ %s";
  16599. // NB: candidate has two optional chunks, so %void middle one if it's missing
  16600. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  16601. if (o.generation != null) {
  16602. str += " generation %d";
  16603. }
  16604. return str;
  16605. }
  16606. },
  16607. { //a=end-of-candidates (keep after the candidates line for readability)
  16608. name: 'endOfCandidates',
  16609. reg: /^(end-of-candidates)/
  16610. },
  16611. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  16612. name: 'remoteCandidates',
  16613. reg: /^remote-candidates:(.*)/,
  16614. format: "remote-candidates:%s"
  16615. },
  16616. { //a=ice-options:google-ice
  16617. name: 'iceOptions',
  16618. reg: /^ice-options:(\S*)/,
  16619. format: "ice-options:%s"
  16620. },
  16621. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  16622. push: "ssrcs",
  16623. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  16624. names: ['id', 'attribute', 'value'],
  16625. format: "ssrc:%d %s:%s"
  16626. },
  16627. { //a=ssrc-group:FEC 1 2
  16628. push: "ssrcGroups",
  16629. reg: /^ssrc-group:(\w*) (.*)/,
  16630. names: ['semantics', 'ssrcs'],
  16631. format: "ssrc-group:%s %s"
  16632. },
  16633. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  16634. name: "msidSemantic",
  16635. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  16636. names: ['semantic', 'token'],
  16637. format: "msid-semantic: %s %s" // space after ":" is not accidental
  16638. },
  16639. { //a=group:BUNDLE audio video
  16640. push: 'groups',
  16641. reg: /^group:(\w*) (.*)/,
  16642. names: ['type', 'mids'],
  16643. format: "group:%s %s"
  16644. },
  16645. { //a=rtcp-mux
  16646. name: 'rtcpMux',
  16647. reg: /^(rtcp-mux)/
  16648. },
  16649. { //a=rtcp-rsize
  16650. name: 'rtcpRsize',
  16651. reg: /^(rtcp-rsize)/
  16652. },
  16653. { // any a= that we don't understand is kepts verbatim on media.invalid
  16654. push: 'invalid',
  16655. names: ["value"]
  16656. }
  16657. ]
  16658. };
  16659. // set sensible defaults to avoid polluting the grammar with boring details
  16660. Object.keys(grammar).forEach(function (key) {
  16661. var objs = grammar[key];
  16662. objs.forEach(function (obj) {
  16663. if (!obj.reg) {
  16664. obj.reg = /(.*)/;
  16665. }
  16666. if (!obj.format) {
  16667. obj.format = "%s";
  16668. }
  16669. });
  16670. });
  16671. },{}],57:[function(require,module,exports){
  16672. var parser = require('./parser');
  16673. var writer = require('./writer');
  16674. exports.write = writer;
  16675. exports.parse = parser.parse;
  16676. exports.parseFmtpConfig = parser.parseFmtpConfig;
  16677. exports.parsePayloads = parser.parsePayloads;
  16678. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  16679. },{"./parser":58,"./writer":59}],58:[function(require,module,exports){
  16680. var toIntIfInt = function (v) {
  16681. return String(Number(v)) === v ? Number(v) : v;
  16682. };
  16683. var attachProperties = function (match, location, names, rawName) {
  16684. if (rawName && !names) {
  16685. location[rawName] = toIntIfInt(match[1]);
  16686. }
  16687. else {
  16688. for (var i = 0; i < names.length; i += 1) {
  16689. if (match[i+1] != null) {
  16690. location[names[i]] = toIntIfInt(match[i+1]);
  16691. }
  16692. }
  16693. }
  16694. };
  16695. var parseReg = function (obj, location, content) {
  16696. var needsBlank = obj.name && obj.names;
  16697. if (obj.push && !location[obj.push]) {
  16698. location[obj.push] = [];
  16699. }
  16700. else if (needsBlank && !location[obj.name]) {
  16701. location[obj.name] = {};
  16702. }
  16703. var keyLocation = obj.push ?
  16704. {} : // blank object that will be pushed
  16705. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  16706. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  16707. if (obj.push) {
  16708. location[obj.push].push(keyLocation);
  16709. }
  16710. };
  16711. var grammar = require('./grammar');
  16712. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  16713. exports.parse = function (sdp) {
  16714. var session = {}
  16715. , media = []
  16716. , location = session; // points at where properties go under (one of the above)
  16717. // parse lines we understand
  16718. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  16719. var type = l[0];
  16720. var content = l.slice(2);
  16721. if (type === 'm') {
  16722. media.push({rtp: [], fmtp: []});
  16723. location = media[media.length-1]; // point at latest media line
  16724. }
  16725. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  16726. var obj = grammar[type][j];
  16727. if (obj.reg.test(content)) {
  16728. return parseReg(obj, location, content);
  16729. }
  16730. }
  16731. });
  16732. session.media = media; // link it up
  16733. return session;
  16734. };
  16735. var fmtpReducer = function (acc, expr) {
  16736. var s = expr.split('=');
  16737. if (s.length === 2) {
  16738. acc[s[0]] = toIntIfInt(s[1]);
  16739. }
  16740. return acc;
  16741. };
  16742. exports.parseFmtpConfig = function (str) {
  16743. return str.split(';').reduce(fmtpReducer, {});
  16744. };
  16745. exports.parsePayloads = function (str) {
  16746. return str.split(' ').map(Number);
  16747. };
  16748. exports.parseRemoteCandidates = function (str) {
  16749. var candidates = [];
  16750. var parts = str.split(' ').map(toIntIfInt);
  16751. for (var i = 0; i < parts.length; i += 3) {
  16752. candidates.push({
  16753. component: parts[i],
  16754. ip: parts[i + 1],
  16755. port: parts[i + 2]
  16756. });
  16757. }
  16758. return candidates;
  16759. };
  16760. },{"./grammar":56}],59:[function(require,module,exports){
  16761. var grammar = require('./grammar');
  16762. // customized util.format - discards excess arguments and can void middle ones
  16763. var formatRegExp = /%[sdv%]/g;
  16764. var format = function (formatStr) {
  16765. var i = 1;
  16766. var args = arguments;
  16767. var len = args.length;
  16768. return formatStr.replace(formatRegExp, function (x) {
  16769. if (i >= len) {
  16770. return x; // missing argument
  16771. }
  16772. var arg = args[i];
  16773. i += 1;
  16774. switch (x) {
  16775. case '%%':
  16776. return '%';
  16777. case '%s':
  16778. return String(arg);
  16779. case '%d':
  16780. return Number(arg);
  16781. case '%v':
  16782. return '';
  16783. }
  16784. });
  16785. // NB: we discard excess arguments - they are typically undefined from makeLine
  16786. };
  16787. var makeLine = function (type, obj, location) {
  16788. var str = obj.format instanceof Function ?
  16789. (obj.format(obj.push ? location : location[obj.name])) :
  16790. obj.format;
  16791. var args = [type + '=' + str];
  16792. if (obj.names) {
  16793. for (var i = 0; i < obj.names.length; i += 1) {
  16794. var n = obj.names[i];
  16795. if (obj.name) {
  16796. args.push(location[obj.name][n]);
  16797. }
  16798. else { // for mLine and push attributes
  16799. args.push(location[obj.names[i]]);
  16800. }
  16801. }
  16802. }
  16803. else {
  16804. args.push(location[obj.name]);
  16805. }
  16806. return format.apply(null, args);
  16807. };
  16808. // RFC specified order
  16809. // TODO: extend this with all the rest
  16810. var defaultOuterOrder = [
  16811. 'v', 'o', 's', 'i',
  16812. 'u', 'e', 'p', 'c',
  16813. 'b', 't', 'r', 'z', 'a'
  16814. ];
  16815. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  16816. module.exports = function (session, opts) {
  16817. opts = opts || {};
  16818. // ensure certain properties exist
  16819. if (session.version == null) {
  16820. session.version = 0; // "v=0" must be there (only defined version atm)
  16821. }
  16822. if (session.name == null) {
  16823. session.name = " "; // "s= " must be there if no meaningful name set
  16824. }
  16825. session.media.forEach(function (mLine) {
  16826. if (mLine.payloads == null) {
  16827. mLine.payloads = "";
  16828. }
  16829. });
  16830. var outerOrder = opts.outerOrder || defaultOuterOrder;
  16831. var innerOrder = opts.innerOrder || defaultInnerOrder;
  16832. var sdp = [];
  16833. // loop through outerOrder for matching properties on session
  16834. outerOrder.forEach(function (type) {
  16835. grammar[type].forEach(function (obj) {
  16836. if (obj.name in session && session[obj.name] != null) {
  16837. sdp.push(makeLine(type, obj, session));
  16838. }
  16839. else if (obj.push in session && session[obj.push] != null) {
  16840. session[obj.push].forEach(function (el) {
  16841. sdp.push(makeLine(type, obj, el));
  16842. });
  16843. }
  16844. });
  16845. });
  16846. // then for each media line, follow the innerOrder
  16847. session.media.forEach(function (mLine) {
  16848. sdp.push(makeLine('m', grammar.m[0], mLine));
  16849. innerOrder.forEach(function (type) {
  16850. grammar[type].forEach(function (obj) {
  16851. if (obj.name in mLine && mLine[obj.name] != null) {
  16852. sdp.push(makeLine(type, obj, mLine));
  16853. }
  16854. else if (obj.push in mLine && mLine[obj.push] != null) {
  16855. mLine[obj.push].forEach(function (el) {
  16856. sdp.push(makeLine(type, obj, el));
  16857. });
  16858. }
  16859. });
  16860. });
  16861. });
  16862. return sdp.join('\r\n') + '\r\n';
  16863. };
  16864. },{"./grammar":56}],60:[function(require,module,exports){
  16865. var transform = require('sdp-transform');
  16866. var transformUtils = require('./transform-utils');
  16867. var parseSsrcs = transformUtils.parseSsrcs;
  16868. var writeSsrcs = transformUtils.writeSsrcs;
  16869. //region Constants
  16870. var DEFAULT_NUM_OF_LAYERS = 3;
  16871. //endregion
  16872. //region Ctor
  16873. function Simulcast(options) {
  16874. this.options = options ? options : {};
  16875. if (!this.options.numOfLayers) {
  16876. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  16877. }
  16878. this.layers = [];
  16879. }
  16880. //endregion
  16881. //region Stateless private utility functions
  16882. /**
  16883. * Returns a random integer between min (included) and max (excluded)
  16884. * Using Math.round() gives a non-uniform distribution!
  16885. * @returns {number}
  16886. */
  16887. function generateSSRC() {
  16888. var min = 0, max = 0xffffffff;
  16889. return Math.floor(Math.random() * (max - min)) + min;
  16890. };
  16891. function processVideo(session, action) {
  16892. if (session == null || !Array.isArray(session.media)) {
  16893. return;
  16894. }
  16895. session.media.forEach(function (mLine) {
  16896. if (mLine.type === 'video') {
  16897. action(mLine);
  16898. }
  16899. });
  16900. }
  16901. function validateDescription(desc)
  16902. {
  16903. return desc && desc != null
  16904. && desc.type && desc.type != ''
  16905. && desc.sdp && desc.sdp != '';
  16906. }
  16907. function explodeRemoteSimulcast(mLine) {
  16908. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  16909. return;
  16910. }
  16911. var sources = parseSsrcs(mLine);
  16912. var order = [];
  16913. // Find the SIM group and explode its sources.
  16914. var j = mLine.ssrcGroups.length;
  16915. while (j--) {
  16916. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  16917. continue;
  16918. }
  16919. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  16920. for (var i = 0; i < simulcastSsrcs.length; i++) {
  16921. var ssrc = simulcastSsrcs[i];
  16922. order.push(ssrc);
  16923. var parts = sources[ssrc].msid.split(' ');
  16924. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  16925. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  16926. // Remove all the groups that this SSRC participates in.
  16927. mLine.ssrcGroups.forEach(function (relatedGroup) {
  16928. if (relatedGroup.semantics === 'SIM') {
  16929. return;
  16930. }
  16931. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  16932. if (relatedSsrcs.indexOf(ssrc) === -1) {
  16933. return;
  16934. }
  16935. // Nuke all the related SSRCs.
  16936. relatedSsrcs.forEach(function (relatedSSRC) {
  16937. sources[relatedSSRC].msid = sources[ssrc].msid;
  16938. sources[relatedSSRC].cname = sources[ssrc].cname;
  16939. if (relatedSSRC !== ssrc) {
  16940. order.push(relatedSSRC);
  16941. }
  16942. });
  16943. // Schedule the related group for nuking.
  16944. })
  16945. }
  16946. mLine.ssrcs = writeSsrcs(sources, order);
  16947. mLine.ssrcGroups.splice(j, 1);
  16948. };
  16949. }
  16950. function squeezeRemoteSimulcast(mLine) {
  16951. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  16952. return;
  16953. }
  16954. var sources = parseSsrcs(mLine);
  16955. // Find the SIM group and nuke it.
  16956. mLine.ssrcGroups.some(function (simulcastGroup) {
  16957. if (simulcastGroup.semantics !== 'SIM') {
  16958. return false;
  16959. }
  16960. // Schedule the SIM group for nuking.
  16961. simulcastGroup.nuke = true;
  16962. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  16963. // Nuke all the higher layer SSRCs.
  16964. for (var i = 1; i < simulcastSsrcs.length; i++) {
  16965. var ssrc = simulcastSsrcs[i];
  16966. delete sources[ssrc];
  16967. // Remove all the groups that this SSRC participates in.
  16968. mLine.ssrcGroups.forEach(function (relatedGroup) {
  16969. if (relatedGroup.semantics === 'SIM') {
  16970. return;
  16971. }
  16972. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  16973. if (relatedSsrcs.indexOf(ssrc) === -1) {
  16974. return;
  16975. }
  16976. // Nuke all the related SSRCs.
  16977. relatedSsrcs.forEach(function (relatedSSRC) {
  16978. delete sources[relatedSSRC];
  16979. });
  16980. // Schedule the related group for nuking.
  16981. relatedGroup.nuke = true;
  16982. })
  16983. }
  16984. return true;
  16985. });
  16986. mLine.ssrcs = writeSsrcs(sources);
  16987. // Nuke all the scheduled groups.
  16988. var i = mLine.ssrcGroups.length;
  16989. while (i--) {
  16990. if (mLine.ssrcGroups[i].nuke) {
  16991. mLine.ssrcGroups.splice(i, 1);
  16992. }
  16993. }
  16994. }
  16995. function removeGoogConference(mLine) {
  16996. if (!mLine || !Array.isArray(mLine.invalid)) {
  16997. return;
  16998. }
  16999. var i = mLine.invalid.length;
  17000. while (i--) {
  17001. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  17002. mLine.invalid.splice(i, 1);
  17003. }
  17004. }
  17005. }
  17006. function assertGoogConference(mLine) {
  17007. if (!mLine) {
  17008. return;
  17009. }
  17010. if (!Array.isArray(mLine.invalid)) {
  17011. mLine.invalid = [];
  17012. }
  17013. if (!mLine.invalid.some(
  17014. function (i) { return i.value === 'x-google-flag:conference' })) {
  17015. mLine.invalid.push({'value': 'x-google-flag:conference'});
  17016. }
  17017. }
  17018. //endregion
  17019. //region "Private" functions
  17020. /**
  17021. *
  17022. * @param mLine
  17023. * @private
  17024. */
  17025. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  17026. if (!mLine || mLine.type !== 'video') {
  17027. return;
  17028. }
  17029. var sources = parseSsrcs(mLine);
  17030. if (Object.keys(sources).length === 0) {
  17031. // no sources, disable simulcast.
  17032. if (this.layers.length !== 0) {
  17033. this.layers = [];
  17034. }
  17035. return;
  17036. }
  17037. // find the base layer (we'll reuse its msid and cname).
  17038. var baseLayerSSRC = Object.keys(sources)[0];
  17039. var baseLayer = sources[baseLayerSSRC];
  17040. // todo(gp) handle screen sharing.
  17041. // check if base CNAME has changed and reinitialise layers.
  17042. if (this.layers.length > 0
  17043. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  17044. this.layers = [];
  17045. }
  17046. // (re)initialise layers
  17047. if (this.layers.length < 1) {
  17048. // first push the base layer.
  17049. this.layers.push({
  17050. ssrc: baseLayerSSRC,
  17051. msid: baseLayer.msid,
  17052. cname: baseLayer.cname
  17053. });
  17054. var rtx = false; // RFC 4588
  17055. if (Array.isArray(mLine.rtp)) {
  17056. rtx = mLine.rtp.some(
  17057. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  17058. }
  17059. if (rtx) {
  17060. this.layers[0].rtx = generateSSRC();
  17061. }
  17062. // now push additional layers.
  17063. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  17064. var layer = { ssrc: generateSSRC() };
  17065. if (rtx) {
  17066. layer.rtx = generateSSRC();
  17067. }
  17068. this.layers.push(layer);
  17069. }
  17070. }
  17071. };
  17072. /**
  17073. *
  17074. * @param mLine
  17075. * @private
  17076. */
  17077. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  17078. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  17079. var sources = {};
  17080. var msid = this.layers[0].msid;
  17081. var cname = this.layers[0].cname;
  17082. var simulcastSsrcs = [];
  17083. var ssrcGroups = [];
  17084. for (var i = 0; i < this.layers.length; i++) {
  17085. var layer = this.layers[i];
  17086. sources[layer.ssrc] = { msid: msid, cname: cname };
  17087. simulcastSsrcs.push(layer.ssrc);
  17088. if (layer.rtx) {
  17089. sources[layer.rtx] = {
  17090. msid: msid,
  17091. cname: cname
  17092. }
  17093. ssrcGroups.push({
  17094. semantics: 'FID',
  17095. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  17096. });
  17097. }
  17098. }
  17099. ssrcGroups.push({
  17100. semantics: 'SIM',
  17101. ssrcs: simulcastSsrcs.join(' ')
  17102. });
  17103. mLine.ssrcGroups = ssrcGroups;
  17104. mLine.ssrcs = writeSsrcs(sources);
  17105. }
  17106. }
  17107. //endregion
  17108. //region "Public" functions
  17109. Simulcast.prototype.isSupported = function () {
  17110. return window.chrome;
  17111. // TODO this needs improvements. For example I doubt that Chrome in Android
  17112. // has simulcast support. Also, only recent versions of Chromium have native
  17113. // simulcast support.
  17114. }
  17115. /**
  17116. *
  17117. * @param desc
  17118. * @returns {RTCSessionDescription}
  17119. */
  17120. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  17121. if (!validateDescription(desc)) {
  17122. return desc;
  17123. }
  17124. var session = transform.parse(desc.sdp);
  17125. var self = this;
  17126. processVideo(session, function (mLine) {
  17127. // Handle simulcast reception.
  17128. if (self.options.explodeRemoteSimulcast) {
  17129. explodeRemoteSimulcast(mLine);
  17130. } else {
  17131. squeezeRemoteSimulcast(mLine);
  17132. }
  17133. // If native simulcast is enabled, we must append the x-goog-conference
  17134. // attribute to the SDP.
  17135. if (self.layers.length < 1) {
  17136. removeGoogConference(mLine);
  17137. } else {
  17138. assertGoogConference(mLine);
  17139. }
  17140. });
  17141. return new RTCSessionDescription({
  17142. type: desc.type,
  17143. sdp: transform.write(session)
  17144. });
  17145. };
  17146. /**
  17147. *
  17148. * @param desc
  17149. * @returns {RTCSessionDescription}
  17150. */
  17151. Simulcast.prototype.mungeLocalDescription = function (desc) {
  17152. if (!validateDescription(desc) || !this.isSupported()) {
  17153. return desc;
  17154. }
  17155. var session = transform.parse(desc.sdp);
  17156. var self = this;
  17157. processVideo(session, function (mLine) {
  17158. // Initialize native simulcast layers, if not already done.
  17159. self._maybeInitializeLayers(mLine);
  17160. // Update the SDP with the simulcast layers.
  17161. self._restoreSimulcastView(mLine);
  17162. });
  17163. return new RTCSessionDescription({
  17164. type: desc.type,
  17165. sdp: transform.write(session)
  17166. });
  17167. };
  17168. //endregion
  17169. module.exports = Simulcast;
  17170. },{"./transform-utils":61,"sdp-transform":63}],61:[function(require,module,exports){
  17171. exports.writeSsrcs = function(sources, order) {
  17172. var ssrcs = [];
  17173. // expand sources to ssrcs
  17174. if (typeof sources !== 'undefined' &&
  17175. Object.keys(sources).length !== 0) {
  17176. if (Array.isArray(order)) {
  17177. for (var i = 0; i < order.length; i++) {
  17178. var ssrc = order[i];
  17179. var source = sources[ssrc];
  17180. Object.keys(source).forEach(function (attribute) {
  17181. ssrcs.push({
  17182. id: ssrc,
  17183. attribute: attribute,
  17184. value: source[attribute]
  17185. });
  17186. });
  17187. }
  17188. } else {
  17189. Object.keys(sources).forEach(function (ssrc) {
  17190. var source = sources[ssrc];
  17191. Object.keys(source).forEach(function (attribute) {
  17192. ssrcs.push({
  17193. id: ssrc,
  17194. attribute: attribute,
  17195. value: source[attribute]
  17196. });
  17197. });
  17198. });
  17199. }
  17200. }
  17201. return ssrcs;
  17202. };
  17203. exports.parseSsrcs = function (mLine) {
  17204. var sources = {};
  17205. // group sources attributes by ssrc.
  17206. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  17207. mLine.ssrcs.forEach(function (ssrc) {
  17208. if (!sources[ssrc.id])
  17209. sources[ssrc.id] = {};
  17210. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  17211. });
  17212. }
  17213. return sources;
  17214. };
  17215. },{}],62:[function(require,module,exports){
  17216. arguments[4][56][0].apply(exports,arguments)
  17217. },{"dup":56}],63:[function(require,module,exports){
  17218. arguments[4][57][0].apply(exports,arguments)
  17219. },{"./parser":64,"./writer":65,"dup":57}],64:[function(require,module,exports){
  17220. arguments[4][58][0].apply(exports,arguments)
  17221. },{"./grammar":62,"dup":58}],65:[function(require,module,exports){
  17222. arguments[4][59][0].apply(exports,arguments)
  17223. },{"./grammar":62,"dup":59}],66:[function(require,module,exports){
  17224. var grammar = module.exports = {
  17225. v: [{
  17226. name: 'version',
  17227. reg: /^(\d*)$/
  17228. }],
  17229. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  17230. // NB: sessionId will be a String in most cases because it is huge
  17231. name: 'origin',
  17232. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  17233. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  17234. format: "%s %s %d %s IP%d %s"
  17235. }],
  17236. // default parsing of these only (though some of these feel outdated)
  17237. s: [{ name: 'name' }],
  17238. i: [{ name: 'description' }],
  17239. u: [{ name: 'uri' }],
  17240. e: [{ name: 'email' }],
  17241. p: [{ name: 'phone' }],
  17242. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  17243. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  17244. //k: [{}], // outdated thing ignored
  17245. t: [{ //t=0 0
  17246. name: 'timing',
  17247. reg: /^(\d*) (\d*)/,
  17248. names: ['start', 'stop'],
  17249. format: "%d %d"
  17250. }],
  17251. c: [{ //c=IN IP4 10.47.197.26
  17252. name: 'connection',
  17253. reg: /^IN IP(\d) (\S*)/,
  17254. names: ['version', 'ip'],
  17255. format: "IN IP%d %s"
  17256. }],
  17257. b: [{ //b=AS:4000
  17258. push: 'bandwidth',
  17259. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  17260. names: ['type', 'limit'],
  17261. format: "%s:%s"
  17262. }],
  17263. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  17264. // NB: special - pushes to session
  17265. // TODO: rtp/fmtp should be filtered by the payloads found here?
  17266. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  17267. names: ['type', 'port', 'protocol', 'payloads'],
  17268. format: "%s %d %s %s"
  17269. }],
  17270. a: [
  17271. { //a=rtpmap:110 opus/48000/2
  17272. push: 'rtp',
  17273. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  17274. names: ['payload', 'codec', 'rate', 'encoding'],
  17275. format: function (o) {
  17276. return (o.encoding) ?
  17277. "rtpmap:%d %s/%s/%s":
  17278. "rtpmap:%d %s/%s";
  17279. }
  17280. },
  17281. {
  17282. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  17283. //a=fmtp:111 minptime=10; useinbandfec=1
  17284. push: 'fmtp',
  17285. reg: /^fmtp:(\d*) ([\S| ]*)/,
  17286. names: ['payload', 'config'],
  17287. format: "fmtp:%d %s"
  17288. },
  17289. { //a=control:streamid=0
  17290. name: 'control',
  17291. reg: /^control:(.*)/,
  17292. format: "control:%s"
  17293. },
  17294. { //a=rtcp:65179 IN IP4 193.84.77.194
  17295. name: 'rtcp',
  17296. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  17297. names: ['port', 'netType', 'ipVer', 'address'],
  17298. format: function (o) {
  17299. return (o.address != null) ?
  17300. "rtcp:%d %s IP%d %s":
  17301. "rtcp:%d";
  17302. }
  17303. },
  17304. { //a=rtcp-fb:98 trr-int 100
  17305. push: 'rtcpFbTrrInt',
  17306. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  17307. names: ['payload', 'value'],
  17308. format: "rtcp-fb:%d trr-int %d"
  17309. },
  17310. { //a=rtcp-fb:98 nack rpsi
  17311. push: 'rtcpFb',
  17312. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  17313. names: ['payload', 'type', 'subtype'],
  17314. format: function (o) {
  17315. return (o.subtype != null) ?
  17316. "rtcp-fb:%s %s %s":
  17317. "rtcp-fb:%s %s";
  17318. }
  17319. },
  17320. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  17321. //a=extmap:1/recvonly URI-gps-string
  17322. push: 'ext',
  17323. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  17324. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  17325. format: function (o) {
  17326. return (o.config != null) ?
  17327. "extmap:%s %s %s":
  17328. "extmap:%s %s";
  17329. }
  17330. },
  17331. {
  17332. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  17333. push: 'crypto',
  17334. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  17335. names: ['id', 'suite', 'config', 'sessionConfig'],
  17336. format: function (o) {
  17337. return (o.sessionConfig != null) ?
  17338. "crypto:%d %s %s %s":
  17339. "crypto:%d %s %s";
  17340. }
  17341. },
  17342. { //a=setup:actpass
  17343. name: 'setup',
  17344. reg: /^setup:(\w*)/,
  17345. format: "setup:%s"
  17346. },
  17347. { //a=mid:1
  17348. name: 'mid',
  17349. reg: /^mid:([^\s]*)/,
  17350. format: "mid:%s"
  17351. },
  17352. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  17353. name: 'msid',
  17354. reg: /^msid:(.*)/,
  17355. format: "msid:%s"
  17356. },
  17357. { //a=ptime:20
  17358. name: 'ptime',
  17359. reg: /^ptime:(\d*)/,
  17360. format: "ptime:%d"
  17361. },
  17362. { //a=maxptime:60
  17363. name: 'maxptime',
  17364. reg: /^maxptime:(\d*)/,
  17365. format: "maxptime:%d"
  17366. },
  17367. { //a=sendrecv
  17368. name: 'direction',
  17369. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  17370. },
  17371. { //a=ice-lite
  17372. name: 'icelite',
  17373. reg: /^(ice-lite)/
  17374. },
  17375. { //a=ice-ufrag:F7gI
  17376. name: 'iceUfrag',
  17377. reg: /^ice-ufrag:(\S*)/,
  17378. format: "ice-ufrag:%s"
  17379. },
  17380. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  17381. name: 'icePwd',
  17382. reg: /^ice-pwd:(\S*)/,
  17383. format: "ice-pwd:%s"
  17384. },
  17385. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  17386. name: 'fingerprint',
  17387. reg: /^fingerprint:(\S*) (\S*)/,
  17388. names: ['type', 'hash'],
  17389. format: "fingerprint:%s %s"
  17390. },
  17391. {
  17392. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  17393. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  17394. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  17395. push:'candidates',
  17396. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  17397. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  17398. format: function (o) {
  17399. var str = "candidate:%s %d %s %d %s %d typ %s";
  17400. // NB: candidate has two optional chunks, so %void middle one if it's missing
  17401. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  17402. if (o.generation != null) {
  17403. str += " generation %d";
  17404. }
  17405. return str;
  17406. }
  17407. },
  17408. { //a=end-of-candidates (keep after the candidates line for readability)
  17409. name: 'endOfCandidates',
  17410. reg: /^(end-of-candidates)/
  17411. },
  17412. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  17413. name: 'remoteCandidates',
  17414. reg: /^remote-candidates:(.*)/,
  17415. format: "remote-candidates:%s"
  17416. },
  17417. { //a=ice-options:google-ice
  17418. name: 'iceOptions',
  17419. reg: /^ice-options:(\S*)/,
  17420. format: "ice-options:%s"
  17421. },
  17422. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  17423. push: "ssrcs",
  17424. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  17425. names: ['id', 'attribute', 'value'],
  17426. format: "ssrc:%d %s:%s"
  17427. },
  17428. { //a=ssrc-group:FEC 1 2
  17429. push: "ssrcGroups",
  17430. reg: /^ssrc-group:(\w*) (.*)/,
  17431. names: ['semantics', 'ssrcs'],
  17432. format: "ssrc-group:%s %s"
  17433. },
  17434. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  17435. name: "msidSemantic",
  17436. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  17437. names: ['semantic', 'token'],
  17438. format: "msid-semantic: %s %s" // space after ":" is not accidental
  17439. },
  17440. { //a=group:BUNDLE audio video
  17441. push: 'groups',
  17442. reg: /^group:(\w*) (.*)/,
  17443. names: ['type', 'mids'],
  17444. format: "group:%s %s"
  17445. },
  17446. { //a=rtcp-mux
  17447. name: 'rtcpMux',
  17448. reg: /^(rtcp-mux)/
  17449. },
  17450. { //a=rtcp-rsize
  17451. name: 'rtcpRsize',
  17452. reg: /^(rtcp-rsize)/
  17453. },
  17454. { // any a= that we don't understand is kepts verbatim on media.invalid
  17455. push: 'invalid',
  17456. names: ["value"]
  17457. }
  17458. ]
  17459. };
  17460. // set sensible defaults to avoid polluting the grammar with boring details
  17461. Object.keys(grammar).forEach(function (key) {
  17462. var objs = grammar[key];
  17463. objs.forEach(function (obj) {
  17464. if (!obj.reg) {
  17465. obj.reg = /(.*)/;
  17466. }
  17467. if (!obj.format) {
  17468. obj.format = "%s";
  17469. }
  17470. });
  17471. });
  17472. },{}],67:[function(require,module,exports){
  17473. arguments[4][57][0].apply(exports,arguments)
  17474. },{"./parser":68,"./writer":69,"dup":57}],68:[function(require,module,exports){
  17475. var toIntIfInt = function (v) {
  17476. return String(Number(v)) === v ? Number(v) : v;
  17477. };
  17478. var attachProperties = function (match, location, names, rawName) {
  17479. if (rawName && !names) {
  17480. location[rawName] = toIntIfInt(match[1]);
  17481. }
  17482. else {
  17483. for (var i = 0; i < names.length; i += 1) {
  17484. if (match[i+1] != null) {
  17485. location[names[i]] = toIntIfInt(match[i+1]);
  17486. }
  17487. }
  17488. }
  17489. };
  17490. var parseReg = function (obj, location, content) {
  17491. var needsBlank = obj.name && obj.names;
  17492. if (obj.push && !location[obj.push]) {
  17493. location[obj.push] = [];
  17494. }
  17495. else if (needsBlank && !location[obj.name]) {
  17496. location[obj.name] = {};
  17497. }
  17498. var keyLocation = obj.push ?
  17499. {} : // blank object that will be pushed
  17500. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  17501. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  17502. if (obj.push) {
  17503. location[obj.push].push(keyLocation);
  17504. }
  17505. };
  17506. var grammar = require('./grammar');
  17507. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  17508. exports.parse = function (sdp) {
  17509. var session = {}
  17510. , media = []
  17511. , location = session; // points at where properties go under (one of the above)
  17512. // parse lines we understand
  17513. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  17514. var type = l[0];
  17515. var content = l.slice(2);
  17516. if (type === 'm') {
  17517. media.push({rtp: [], fmtp: []});
  17518. location = media[media.length-1]; // point at latest media line
  17519. }
  17520. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  17521. var obj = grammar[type][j];
  17522. if (obj.reg.test(content)) {
  17523. return parseReg(obj, location, content);
  17524. }
  17525. }
  17526. });
  17527. session.media = media; // link it up
  17528. return session;
  17529. };
  17530. var fmtpReducer = function (acc, expr) {
  17531. var s = expr.split('=');
  17532. if (s.length === 2) {
  17533. acc[s[0]] = toIntIfInt(s[1]);
  17534. }
  17535. return acc;
  17536. };
  17537. exports.parseFmtpConfig = function (str) {
  17538. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  17539. };
  17540. exports.parsePayloads = function (str) {
  17541. return str.split(' ').map(Number);
  17542. };
  17543. exports.parseRemoteCandidates = function (str) {
  17544. var candidates = [];
  17545. var parts = str.split(' ').map(toIntIfInt);
  17546. for (var i = 0; i < parts.length; i += 3) {
  17547. candidates.push({
  17548. component: parts[i],
  17549. ip: parts[i + 1],
  17550. port: parts[i + 2]
  17551. });
  17552. }
  17553. return candidates;
  17554. };
  17555. },{"./grammar":66}],69:[function(require,module,exports){
  17556. arguments[4][59][0].apply(exports,arguments)
  17557. },{"./grammar":66,"dup":59}],70:[function(require,module,exports){
  17558. var MediaStreamType = {
  17559. VIDEO_TYPE: "Video",
  17560. AUDIO_TYPE: "Audio"
  17561. };
  17562. module.exports = MediaStreamType;
  17563. },{}],71:[function(require,module,exports){
  17564. var RTCEvents = {
  17565. RTC_READY: "rtc.ready",
  17566. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  17567. LASTN_CHANGED: "rtc.lastn_changed",
  17568. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  17569. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  17570. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  17571. };
  17572. module.exports = RTCEvents;
  17573. },{}],72:[function(require,module,exports){
  17574. var Resolutions = {
  17575. "1080": {
  17576. width: 1920,
  17577. height: 1080,
  17578. order: 7
  17579. },
  17580. "fullhd": {
  17581. width: 1920,
  17582. height: 1080,
  17583. order: 7
  17584. },
  17585. "720": {
  17586. width: 1280,
  17587. height: 720,
  17588. order: 6
  17589. },
  17590. "hd": {
  17591. width: 1280,
  17592. height: 720,
  17593. order: 6
  17594. },
  17595. "960": {
  17596. width: 960,
  17597. height: 720,
  17598. order: 5
  17599. },
  17600. "640": {
  17601. width: 640,
  17602. height: 480,
  17603. order: 4
  17604. },
  17605. "vga": {
  17606. width: 640,
  17607. height: 480,
  17608. order: 4
  17609. },
  17610. "360": {
  17611. width: 640,
  17612. height: 360,
  17613. order: 3
  17614. },
  17615. "320": {
  17616. width: 320,
  17617. height: 240,
  17618. order: 2
  17619. },
  17620. "180": {
  17621. width: 320,
  17622. height: 180,
  17623. order: 1
  17624. }
  17625. };
  17626. module.exports = Resolutions;
  17627. },{}],73:[function(require,module,exports){
  17628. var StreamEventTypes = {
  17629. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  17630. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  17631. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  17632. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  17633. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  17634. TRACK_MUTE_CHANGED: "rtc.track_mute_changed"
  17635. };
  17636. module.exports = StreamEventTypes;
  17637. },{}],74:[function(require,module,exports){
  17638. var AuthenticationEvents = {
  17639. /**
  17640. * Event callback arguments:
  17641. * function(authenticationEnabled, userIdentity)
  17642. * authenticationEnabled - indicates whether authentication has been enabled
  17643. * in this session
  17644. * userIdentity - if user has been logged in then it contains user name. If
  17645. * contains 'null' or 'undefined' then user is not logged in.
  17646. */
  17647. IDENTITY_UPDATED: "authentication.identity_updated"
  17648. };
  17649. module.exports = AuthenticationEvents;
  17650. },{}],75:[function(require,module,exports){
  17651. var DesktopSharingEventTypes = {
  17652. INIT: "ds.init",
  17653. SWITCHING_DONE: "ds.switching_done",
  17654. NEW_STREAM_CREATED: "ds.new_stream_created"
  17655. };
  17656. module.exports = DesktopSharingEventTypes;
  17657. },{}],76:[function(require,module,exports){
  17658. var XMPPEvents = {
  17659. CONNECTION_FAILED: "xmpp.connection.failed",
  17660. // Indicates an interrupted connection event.
  17661. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  17662. // Indicates a restored connection event.
  17663. CONNECTION_RESTORED: "xmpp.connection.restored",
  17664. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  17665. CALL_INCOMING: "xmpp.callincoming.jingle",
  17666. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  17667. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  17668. KICKED: "xmpp.kicked",
  17669. BRIDGE_DOWN: "xmpp.bridge_down",
  17670. USER_ID_CHANGED: "xmpp.user_id_changed",
  17671. // We joined the MUC
  17672. MUC_JOINED: "xmpp.muc_joined",
  17673. // A member joined the MUC
  17674. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  17675. // A member left the MUC
  17676. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  17677. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  17678. MUC_DESTROYED: "xmpp.muc_destroyed",
  17679. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  17680. REMOTE_STATS: "xmpp.remote_stats",
  17681. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  17682. PRESENCE_STATUS: "xmpp.presence_status",
  17683. RESERVATION_ERROR: "xmpp.room_reservation_error",
  17684. SUBJECT_CHANGED: "xmpp.subject_changed",
  17685. MESSAGE_RECEIVED: "xmpp.message_received",
  17686. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  17687. PASSWORD_REQUIRED: "xmpp.password_required",
  17688. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  17689. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  17690. ETHERPAD: "xmpp.etherpad",
  17691. DEVICE_AVAILABLE: "xmpp.device_available",
  17692. VIDEO_TYPE: "xmpp.video_type",
  17693. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  17694. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  17695. AUDIO_MUTED: "xmpp.audio_muted",
  17696. VIDEO_MUTED: "xmpp.video_muted",
  17697. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  17698. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  17699. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  17700. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  17701. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  17702. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  17703. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  17704. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  17705. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  17706. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  17707. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  17708. // xmpp is connected and obtained user media
  17709. READY_TO_JOIN: 'xmpp.ready_to_join',
  17710. FOCUS_LEFT: "xmpp.focus_left",
  17711. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received"
  17712. };
  17713. module.exports = XMPPEvents;
  17714. },{}],77:[function(require,module,exports){
  17715. // Copyright Joyent, Inc. and other Node contributors.
  17716. //
  17717. // Permission is hereby granted, free of charge, to any person obtaining a
  17718. // copy of this software and associated documentation files (the
  17719. // "Software"), to deal in the Software without restriction, including
  17720. // without limitation the rights to use, copy, modify, merge, publish,
  17721. // distribute, sublicense, and/or sell copies of the Software, and to permit
  17722. // persons to whom the Software is furnished to do so, subject to the
  17723. // following conditions:
  17724. //
  17725. // The above copyright notice and this permission notice shall be included
  17726. // in all copies or substantial portions of the Software.
  17727. //
  17728. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  17729. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17730. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  17731. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  17732. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  17733. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  17734. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  17735. function EventEmitter() {
  17736. this._events = this._events || {};
  17737. this._maxListeners = this._maxListeners || undefined;
  17738. }
  17739. module.exports = EventEmitter;
  17740. // Backwards-compat with node 0.10.x
  17741. EventEmitter.EventEmitter = EventEmitter;
  17742. EventEmitter.prototype._events = undefined;
  17743. EventEmitter.prototype._maxListeners = undefined;
  17744. // By default EventEmitters will print a warning if more than 10 listeners are
  17745. // added to it. This is a useful default which helps finding memory leaks.
  17746. EventEmitter.defaultMaxListeners = 10;
  17747. // Obviously not all Emitters should be limited to 10. This function allows
  17748. // that to be increased. Set to zero for unlimited.
  17749. EventEmitter.prototype.setMaxListeners = function(n) {
  17750. if (!isNumber(n) || n < 0 || isNaN(n))
  17751. throw TypeError('n must be a positive number');
  17752. this._maxListeners = n;
  17753. return this;
  17754. };
  17755. EventEmitter.prototype.emit = function(type) {
  17756. var er, handler, len, args, i, listeners;
  17757. if (!this._events)
  17758. this._events = {};
  17759. // If there is no 'error' event listener then throw.
  17760. if (type === 'error') {
  17761. if (!this._events.error ||
  17762. (isObject(this._events.error) && !this._events.error.length)) {
  17763. er = arguments[1];
  17764. if (er instanceof Error) {
  17765. throw er; // Unhandled 'error' event
  17766. }
  17767. throw TypeError('Uncaught, unspecified "error" event.');
  17768. }
  17769. }
  17770. handler = this._events[type];
  17771. if (isUndefined(handler))
  17772. return false;
  17773. if (isFunction(handler)) {
  17774. switch (arguments.length) {
  17775. // fast cases
  17776. case 1:
  17777. handler.call(this);
  17778. break;
  17779. case 2:
  17780. handler.call(this, arguments[1]);
  17781. break;
  17782. case 3:
  17783. handler.call(this, arguments[1], arguments[2]);
  17784. break;
  17785. // slower
  17786. default:
  17787. len = arguments.length;
  17788. args = new Array(len - 1);
  17789. for (i = 1; i < len; i++)
  17790. args[i - 1] = arguments[i];
  17791. handler.apply(this, args);
  17792. }
  17793. } else if (isObject(handler)) {
  17794. len = arguments.length;
  17795. args = new Array(len - 1);
  17796. for (i = 1; i < len; i++)
  17797. args[i - 1] = arguments[i];
  17798. listeners = handler.slice();
  17799. len = listeners.length;
  17800. for (i = 0; i < len; i++)
  17801. listeners[i].apply(this, args);
  17802. }
  17803. return true;
  17804. };
  17805. EventEmitter.prototype.addListener = function(type, listener) {
  17806. var m;
  17807. if (!isFunction(listener))
  17808. throw TypeError('listener must be a function');
  17809. if (!this._events)
  17810. this._events = {};
  17811. // To avoid recursion in the case that type === "newListener"! Before
  17812. // adding it to the listeners, first emit "newListener".
  17813. if (this._events.newListener)
  17814. this.emit('newListener', type,
  17815. isFunction(listener.listener) ?
  17816. listener.listener : listener);
  17817. if (!this._events[type])
  17818. // Optimize the case of one listener. Don't need the extra array object.
  17819. this._events[type] = listener;
  17820. else if (isObject(this._events[type]))
  17821. // If we've already got an array, just append.
  17822. this._events[type].push(listener);
  17823. else
  17824. // Adding the second element, need to change to array.
  17825. this._events[type] = [this._events[type], listener];
  17826. // Check for listener leak
  17827. if (isObject(this._events[type]) && !this._events[type].warned) {
  17828. var m;
  17829. if (!isUndefined(this._maxListeners)) {
  17830. m = this._maxListeners;
  17831. } else {
  17832. m = EventEmitter.defaultMaxListeners;
  17833. }
  17834. if (m && m > 0 && this._events[type].length > m) {
  17835. this._events[type].warned = true;
  17836. console.error('(node) warning: possible EventEmitter memory ' +
  17837. 'leak detected. %d listeners added. ' +
  17838. 'Use emitter.setMaxListeners() to increase limit.',
  17839. this._events[type].length);
  17840. if (typeof console.trace === 'function') {
  17841. // not supported in IE 10
  17842. console.trace();
  17843. }
  17844. }
  17845. }
  17846. return this;
  17847. };
  17848. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  17849. EventEmitter.prototype.once = function(type, listener) {
  17850. if (!isFunction(listener))
  17851. throw TypeError('listener must be a function');
  17852. var fired = false;
  17853. function g() {
  17854. this.removeListener(type, g);
  17855. if (!fired) {
  17856. fired = true;
  17857. listener.apply(this, arguments);
  17858. }
  17859. }
  17860. g.listener = listener;
  17861. this.on(type, g);
  17862. return this;
  17863. };
  17864. // emits a 'removeListener' event iff the listener was removed
  17865. EventEmitter.prototype.removeListener = function(type, listener) {
  17866. var list, position, length, i;
  17867. if (!isFunction(listener))
  17868. throw TypeError('listener must be a function');
  17869. if (!this._events || !this._events[type])
  17870. return this;
  17871. list = this._events[type];
  17872. length = list.length;
  17873. position = -1;
  17874. if (list === listener ||
  17875. (isFunction(list.listener) && list.listener === listener)) {
  17876. delete this._events[type];
  17877. if (this._events.removeListener)
  17878. this.emit('removeListener', type, listener);
  17879. } else if (isObject(list)) {
  17880. for (i = length; i-- > 0;) {
  17881. if (list[i] === listener ||
  17882. (list[i].listener && list[i].listener === listener)) {
  17883. position = i;
  17884. break;
  17885. }
  17886. }
  17887. if (position < 0)
  17888. return this;
  17889. if (list.length === 1) {
  17890. list.length = 0;
  17891. delete this._events[type];
  17892. } else {
  17893. list.splice(position, 1);
  17894. }
  17895. if (this._events.removeListener)
  17896. this.emit('removeListener', type, listener);
  17897. }
  17898. return this;
  17899. };
  17900. EventEmitter.prototype.removeAllListeners = function(type) {
  17901. var key, listeners;
  17902. if (!this._events)
  17903. return this;
  17904. // not listening for removeListener, no need to emit
  17905. if (!this._events.removeListener) {
  17906. if (arguments.length === 0)
  17907. this._events = {};
  17908. else if (this._events[type])
  17909. delete this._events[type];
  17910. return this;
  17911. }
  17912. // emit removeListener for all listeners on all events
  17913. if (arguments.length === 0) {
  17914. for (key in this._events) {
  17915. if (key === 'removeListener') continue;
  17916. this.removeAllListeners(key);
  17917. }
  17918. this.removeAllListeners('removeListener');
  17919. this._events = {};
  17920. return this;
  17921. }
  17922. listeners = this._events[type];
  17923. if (isFunction(listeners)) {
  17924. this.removeListener(type, listeners);
  17925. } else {
  17926. // LIFO order
  17927. while (listeners.length)
  17928. this.removeListener(type, listeners[listeners.length - 1]);
  17929. }
  17930. delete this._events[type];
  17931. return this;
  17932. };
  17933. EventEmitter.prototype.listeners = function(type) {
  17934. var ret;
  17935. if (!this._events || !this._events[type])
  17936. ret = [];
  17937. else if (isFunction(this._events[type]))
  17938. ret = [this._events[type]];
  17939. else
  17940. ret = this._events[type].slice();
  17941. return ret;
  17942. };
  17943. EventEmitter.listenerCount = function(emitter, type) {
  17944. var ret;
  17945. if (!emitter._events || !emitter._events[type])
  17946. ret = 0;
  17947. else if (isFunction(emitter._events[type]))
  17948. ret = 1;
  17949. else
  17950. ret = emitter._events[type].length;
  17951. return ret;
  17952. };
  17953. function isFunction(arg) {
  17954. return typeof arg === 'function';
  17955. }
  17956. function isNumber(arg) {
  17957. return typeof arg === 'number';
  17958. }
  17959. function isObject(arg) {
  17960. return typeof arg === 'object' && arg !== null;
  17961. }
  17962. function isUndefined(arg) {
  17963. return arg === void 0;
  17964. }
  17965. },{}],78:[function(require,module,exports){
  17966. // shim for using process in browser
  17967. var process = module.exports = {};
  17968. var queue = [];
  17969. var draining = false;
  17970. function drainQueue() {
  17971. if (draining) {
  17972. return;
  17973. }
  17974. draining = true;
  17975. var currentQueue;
  17976. var len = queue.length;
  17977. while(len) {
  17978. currentQueue = queue;
  17979. queue = [];
  17980. var i = -1;
  17981. while (++i < len) {
  17982. currentQueue[i]();
  17983. }
  17984. len = queue.length;
  17985. }
  17986. draining = false;
  17987. }
  17988. process.nextTick = function (fun) {
  17989. queue.push(fun);
  17990. if (!draining) {
  17991. setTimeout(drainQueue, 0);
  17992. }
  17993. };
  17994. process.title = 'browser';
  17995. process.browser = true;
  17996. process.env = {};
  17997. process.argv = [];
  17998. process.version = ''; // empty string to avoid regexp issues
  17999. function noop() {}
  18000. process.on = noop;
  18001. process.addListener = noop;
  18002. process.once = noop;
  18003. process.off = noop;
  18004. process.removeListener = noop;
  18005. process.removeAllListeners = noop;
  18006. process.emit = noop;
  18007. process.binding = function (name) {
  18008. throw new Error('process.binding is not supported');
  18009. };
  18010. // TODO(shtylman)
  18011. process.cwd = function () { return '/' };
  18012. process.chdir = function (dir) {
  18013. throw new Error('process.chdir is not supported');
  18014. };
  18015. process.umask = function() { return 0; };
  18016. },{}]},{},[7])(7)
  18017. });