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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JitsiMeetJS = f()}})(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. var Statistics = require("./modules/statistics/statistics");
  10. /**
  11. * Creates a JitsiConference object with the given name and properties.
  12. * Note: this constructor is not a part of the public API (objects should be
  13. * created using JitsiConnection.createConference).
  14. * @param options.config properties / settings related to the conference that will be created.
  15. * @param options.name the name of the conference
  16. * @param options.connection the JitsiConnection object for this JitsiConference.
  17. * @constructor
  18. */
  19. function JitsiConference(options) {
  20. this.options = options;
  21. this.connection = this.options.connection;
  22. this.xmpp = this.connection.xmpp;
  23. this.eventEmitter = new EventEmitter();
  24. this.room = this.xmpp.createRoom(this.options.name, null, null, this.options.config);
  25. this.rtc = new RTC(this.room, options);
  26. if(!options.config.disableAudioLevels)
  27. this.statistics = new Statistics();
  28. setupListeners(this);
  29. this.participants = {};
  30. this.lastActiveSpeaker = null;
  31. }
  32. /**
  33. * Joins the conference.
  34. * @param password {string} the password
  35. */
  36. JitsiConference.prototype.join = function (password) {
  37. this.room.join(password);
  38. }
  39. /**
  40. * Leaves the conference.
  41. */
  42. JitsiConference.prototype.leave = function () {
  43. this.xmpp.leaveRoom(this.room.roomjid);
  44. this.room = null;
  45. }
  46. /**
  47. * Creates the media tracks and returns them trough the callback.
  48. * @param options Object with properties / settings specifying the tracks which should be created.
  49. * should be created or some additional configurations about resolution for example.
  50. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>} A promise that returns an array of created JitsiTracks if resolved,
  51. * or a JitsiConferenceError if rejected.
  52. */
  53. JitsiConference.prototype.createLocalTracks = function (options) {
  54. return this.rtc.obtainAudioAndVideoPermissions(options || {});
  55. }
  56. /**
  57. * Returns the local tracks.
  58. */
  59. JitsiConference.prototype.getLocalTracks = function () {
  60. return this.rtc.localStreams;
  61. };
  62. /**
  63. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  64. * in JitsiConferenceEvents.
  65. * @param eventId the event ID.
  66. * @param handler handler for the event.
  67. *
  68. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  69. */
  70. JitsiConference.prototype.on = function (eventId, handler) {
  71. this.eventEmitter.on(eventId, handler);
  72. }
  73. /**
  74. * Removes event listener
  75. * @param eventId the event ID.
  76. * @param [handler] optional, the specific handler to unbind
  77. *
  78. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  79. */
  80. JitsiConference.prototype.off = function (eventId, handler) {
  81. this.eventEmitter.removeListener(eventId, listener);
  82. }
  83. // Common aliases for event emitter
  84. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on
  85. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off
  86. /**
  87. * Receives notifications from another participants for commands / custom events(send by sendPresenceCommand method).
  88. * @param command {String} the name of the command
  89. * @param handler {Function} handler for the command
  90. */
  91. JitsiConference.prototype.addCommandListener = function (command, handler) {
  92. this.room.addPresenceListener(command, handler);
  93. }
  94. /**
  95. * Removes command listener
  96. * @param command {String} the name of the command
  97. */
  98. JitsiConference.prototype.removeCommandListener = function (command) {
  99. this.room.removePresenceListener(command);
  100. }
  101. /**
  102. * Sends text message to the other participants in the conference
  103. * @param message the text message.
  104. */
  105. JitsiConference.prototype.sendTextMessage = function (message) {
  106. this.room.sendMessage(message);
  107. }
  108. /**
  109. * Send presence command.
  110. * @param name the name of the command.
  111. * @param values Object with keys and values that will be send.
  112. **/
  113. JitsiConference.prototype.sendCommand = function (name, values) {
  114. this.room.addToPresence(name, values);
  115. this.room.sendPresence();
  116. }
  117. /**
  118. * Send presence command one time.
  119. * @param name the name of the command.
  120. * @param values Object with keys and values that will be send.
  121. **/
  122. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  123. this.sendCommand(name, values);
  124. this.removeCommand(name);
  125. }
  126. /**
  127. * Send presence command.
  128. * @param name the name of the command.
  129. * @param values Object with keys and values that will be send.
  130. * @param persistent if false the command will be sent only one time
  131. **/
  132. JitsiConference.prototype.removeCommand = function (name) {
  133. this.room.removeFromPresence(name);
  134. }
  135. /**
  136. * Sets the display name for this conference.
  137. * @param name the display name to set
  138. */
  139. JitsiConference.prototype.setDisplayName = function(name) {
  140. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  141. this.room.sendPresence();
  142. }
  143. /**
  144. * Elects the participant with the given id to be the selected participant or the speaker.
  145. * @param id the identifier of the participant
  146. */
  147. JitsiConference.prototype.selectParticipant = function(participantId) {
  148. this.rtc.selectedEndpoint(participantId);
  149. }
  150. /**
  151. *
  152. * @param id the identifier of the participant
  153. */
  154. JitsiConference.prototype.pinParticipant = function(participantId) {
  155. this.rtc.pinEndpoint(participantId);
  156. }
  157. /**
  158. * Returns the list of participants for this conference.
  159. * @return Object a list of participant identifiers containing all conference participants.
  160. */
  161. JitsiConference.prototype.getParticipants = function() {
  162. return this.participants;
  163. }
  164. /**
  165. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  166. * null if there isn't one).
  167. * @param id the id of the participant.
  168. */
  169. JitsiConference.prototype.getParticipantById = function(id) {
  170. return this.participants[id];
  171. }
  172. JitsiConference.prototype.onMemberJoined = function (jid, email, nick) {
  173. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, Strophe.getResourceFromJid(jid));
  174. // this.participants[jid] = new JitsiParticipant();
  175. }
  176. /**
  177. * Returns the local user's ID
  178. * @return {string} local user's ID
  179. */
  180. JitsiConference.prototype.myUserId = function () {
  181. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  182. }
  183. /**
  184. * Setups the listeners needed for the conference.
  185. * @param conference the conference
  186. */
  187. function setupListeners(conference) {
  188. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  189. conference.rtc.onIncommingCall(event);
  190. if(conference.statistics)
  191. conference.statistics.startRemoteStats(event.peerconnection);
  192. });
  193. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  194. conference.rtc.createRemoteStream.bind(conference.rtc));
  195. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, function (stream) {
  196. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, stream);
  197. });
  198. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_REMOTE_ENDED, function (stream) {
  199. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, stream);
  200. });
  201. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, function (stream) {
  202. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, stream);
  203. });
  204. conference.rtc.addListener(StreamEventTypes.TRACK_MUTE_CHANGED, function (track) {
  205. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  206. });
  207. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  208. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  209. });
  210. // FIXME
  211. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  212. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  213. // });
  214. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  215. if(conference.lastActiveSpeaker !== id && conference.room
  216. && conference.myUserId() !== id) {
  217. conference.lastActiveSpeaker = id;
  218. conference.eventEmitter.emit(JitsiConferenceEvents.ACTIVE_SPEAKER_CHANGED, id);
  219. }
  220. });
  221. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  222. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  223. });
  224. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  225. function (lastNEndpoints, endpointsEnteringLastN) {
  226. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  227. lastNEndpoints, endpointsEnteringLastN);
  228. });
  229. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  230. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT,function (jid) {
  231. conference.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, Strophe.getResourceFromJid(jid));
  232. });
  233. conference.room.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (from, displayName) {
  234. conference.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  235. Strophe.getResourceFromJid(from), displayName);
  236. });
  237. if(conference.statistics) {
  238. conference.statistics.addAudioLevelListener(function (ssrc, level) {
  239. var userId = null;
  240. if (ssrc === Statistics.LOCAL_JID) {
  241. userId = conference.myUserId();
  242. } else {
  243. var jid = conference.room.getJidBySSRC(ssrc);
  244. if (!jid)
  245. return;
  246. userId = Strophe.getResourceFromJid(jid);
  247. }
  248. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  249. userId, level);
  250. });
  251. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_LOCAL_CREATED, function (stream) {
  252. conference.statistics.startLocalStats(stream);
  253. });
  254. conference.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE,
  255. function () {
  256. conference.statistics.dispose();
  257. });
  258. }
  259. }
  260. module.exports = JitsiConference;
  261. },{"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./modules/RTC/RTC":13,"./modules/statistics/statistics":21,"./service/RTC/RTCEvents":77,"./service/RTC/StreamEventTypes":79,"./service/xmpp/XMPPEvents":83,"events":39}],2:[function(require,module,exports){
  262. /**
  263. * Enumeration with the errors for the conference.
  264. * @type {{string: string}}
  265. */
  266. var JitsiConferenceErrors = {
  267. /**
  268. * Indicates that a password is required in order to join the conference.
  269. */
  270. PASSWORD_REQUIRED: "conference.passwordRequired",
  271. /**
  272. * Indicates that a connection error occurred when trying to join a conference.
  273. */
  274. CONNECTION_ERROR: "conference.connectionError",
  275. /**
  276. * Indicates that there is no available videobridge.
  277. */
  278. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  279. /**
  280. * Many more errors TBD here.
  281. */
  282. };
  283. module.exports = JitsiConferenceErrors;
  284. },{}],3:[function(require,module,exports){
  285. /**
  286. * Enumeration with the events for the conference.
  287. * @type {{string: string}}
  288. */
  289. var JitsiConferenceEvents = {
  290. /**
  291. * A new media track was added to the conference.
  292. */
  293. TRACK_ADDED: "conference.trackAdded",
  294. /**
  295. * The media track was removed to the conference.
  296. */
  297. TRACK_REMOVED: "conference.trackRemoved",
  298. /**
  299. * The active speaker was changed.
  300. */
  301. ACTIVE_SPEAKER_CHANGED: "conference.activeSpeaker",
  302. /**
  303. * A new user joinned the conference.
  304. */
  305. USER_JOINED: "conference.userJoined",
  306. /**
  307. * A user has left the conference.
  308. */
  309. USER_LEFT: "conference.userLeft",
  310. /**
  311. * New text message was received.
  312. */
  313. MESSAGE_RECEIVED: "conference.messageReceived",
  314. /**
  315. * A user has changed it display name
  316. */
  317. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  318. /**
  319. * A participant avatar has changed.
  320. */
  321. AVATAR_CHANGED: "conference.avatarChanged",
  322. /**
  323. * New connection statistics are received.
  324. */
  325. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  326. /**
  327. * The Last N set is changed.
  328. */
  329. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  330. /**
  331. * You are included / excluded in somebody's last N set
  332. */
  333. IN_LAST_N_CHANGED: "conference.lastNEndpointsChanged",
  334. /**
  335. * A media track mute status was changed.
  336. */
  337. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  338. /**
  339. * Audio levels of a media track was changed.
  340. */
  341. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  342. /**
  343. * Indicates that the connection to the conference has been interrupted for some reason.
  344. */
  345. CONNECTION_INTERRUPTED: "conference.connecionInterrupted",
  346. /**
  347. * Indicates that the connection to the conference has been restored.
  348. */
  349. CONNECTION_RESTORED: "conference.connecionRestored",
  350. /**
  351. * Indicates that conference has been joined.
  352. */
  353. CONFERENCE_JOINED: "conference.joined",
  354. /**
  355. * Indicates that conference has been left.
  356. */
  357. CONFERENCE_LEFT: "conference.left"
  358. };
  359. module.exports = JitsiConferenceEvents;
  360. },{}],4:[function(require,module,exports){
  361. var JitsiConference = require("./JitsiConference");
  362. var XMPP = require("./modules/xmpp/xmpp");
  363. /**
  364. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  365. * JitsiConference interface.
  366. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  367. * @param token secret generated by the provider of Jitsi Meet video conferencing services.
  368. * The token will be send to the provider from the Jitsi Meet server deployment for authorization of the current client.
  369. * @param options Object with properties / settings related to connection with the server.
  370. * @constructor
  371. */
  372. function JitsiConnection(appID, token, options) {
  373. this.appID = appID;
  374. this.token = token;
  375. this.options = options;
  376. this.xmpp = new XMPP(options);
  377. this.conferences = {};
  378. }
  379. /**
  380. * Connect the client with the server.
  381. * @param options {object} connecting options (for example authentications parameters).
  382. */
  383. JitsiConnection.prototype.connect = function (options) {
  384. if(!options)
  385. options = {};
  386. this.xmpp.connect(options.id, options.password);
  387. }
  388. /**
  389. * Disconnect the client from the server.
  390. */
  391. JitsiConnection.prototype.disconnect = function () {
  392. this.xmpp.disconnect();
  393. }
  394. /**
  395. * This method allows renewal of the tokens if they are expiring.
  396. * @param token the new token.
  397. */
  398. JitsiConnection.prototype.setToken = function (token) {
  399. this.token = token;
  400. }
  401. /**
  402. * Creates and joins new conference.
  403. * @param name the name of the conference; if null - a generated name will be provided from the api
  404. * @param options Object with properties / settings related to the conference that will be created.
  405. * @returns {JitsiConference} returns the new conference object.
  406. */
  407. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  408. this.conferences[name] = new JitsiConference({name: name, config: options, connection: this});
  409. return this.conferences[name];
  410. }
  411. /**
  412. * Subscribes the passed listener to the event.
  413. * @param event {JitsiConnectionEvents} the connection event.
  414. * @param listener {Function} the function that will receive the event
  415. */
  416. JitsiConnection.prototype.addEventListener = function (event, listener) {
  417. this.xmpp.addListener(event, listener);
  418. }
  419. /**
  420. * Unsubscribes the passed handler.
  421. * @param event {JitsiConnectionEvents} the connection event.
  422. * @param listener {Function} the function that will receive the event
  423. */
  424. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  425. this.xmpp.removeListener(event, listener);
  426. }
  427. module.exports = JitsiConnection;
  428. },{"./JitsiConference":1,"./modules/xmpp/xmpp":37}],5:[function(require,module,exports){
  429. /**
  430. * Enumeration with the errors for the connection.
  431. * @type {{string: string}}
  432. */
  433. var JitsiConnectionErrors = {
  434. /**
  435. * Indicates that a password is required in order to join the conference.
  436. */
  437. PASSWORD_REQUIRED: "connection.passwordRequired",
  438. /**
  439. * Indicates that a connection error occurred when trying to join a conference.
  440. */
  441. CONNECTION_ERROR: "connection.connectionError",
  442. /**
  443. * Not specified errors.
  444. */
  445. OTHER_ERROR: "connection.otherError"
  446. };
  447. module.exports = JitsiConnectionErrors;
  448. },{}],6:[function(require,module,exports){
  449. /**
  450. * Enumeration with the events for the connection.
  451. * @type {{string: string}}
  452. */
  453. var JitsiConnnectionEvents = {
  454. /**
  455. * Indicates that the connection has been failed for some reason.
  456. */
  457. CONNECTION_FAILED: "connection.connecionFailed",
  458. /**
  459. * Indicates that the connection has been established.
  460. */
  461. CONNECTION_ESTABLISHED: "connection.connecionEstablished",
  462. /**
  463. * Indicates that the connection has been disconnected.
  464. */
  465. CONNECTION_DISCONNECTED: "connection.connecionDisconnected",
  466. /**
  467. * Indicates that the perfomed action cannot be executed because the
  468. * connection is not in the correct state(connected, disconnected, etc.)
  469. */
  470. WRONG_STATE: "connection.wrongState"
  471. };
  472. module.exports = JitsiConnnectionEvents;
  473. },{}],7:[function(require,module,exports){
  474. var JitsiConnection = require("./JitsiConnection");
  475. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  476. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  477. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  478. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  479. /**
  480. * Namespace for the interface of Jitsi Meet Library.
  481. */
  482. var LibJitsiMeet = {
  483. JitsiConnection: JitsiConnection,
  484. events: {
  485. conference: JitsiConferenceEvents,
  486. connection: JitsiConnectionEvents
  487. },
  488. errors: {
  489. conference: JitsiConferenceErrors,
  490. connection: JitsiConnectionErrors
  491. },
  492. init: function (options) {
  493. require("./modules/RTC/RTC").init(options || {});
  494. }
  495. }
  496. //Setups the promise object.
  497. window.Promise = window.Promise || require("es6-promise").polyfill();
  498. module.exports = LibJitsiMeet;
  499. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./modules/RTC/RTC":13,"es6-promise":41}],8:[function(require,module,exports){
  500. /**
  501. * Represents a participant in (a member of) a conference.
  502. */
  503. function JitsiParticipant(id, conference, displayName){
  504. this._id = id;
  505. this._conference = conference;
  506. this._displayName = displayName;
  507. }
  508. /**
  509. * @returns {JitsiConference} The conference that this participant belongs to.
  510. */
  511. JitsiParticipant.prototype.getConference = function() {
  512. return this._conference;
  513. }
  514. /**
  515. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  516. */
  517. JitsiParticipant.prototype.getTracks = function() {
  518. }
  519. /**
  520. * @returns {String} The ID (i.e. JID) of this participant.
  521. */
  522. JitsiParticipant.prototype.getId = function() {
  523. return this._id;
  524. }
  525. /**
  526. * @returns {String} The human-readable display name of this participant.
  527. */
  528. JitsiParticipant.prototype.getDisplayName = function() {
  529. return this._displayName;
  530. }
  531. /**
  532. * @returns {Boolean} Whether this participant is a moderator or not.
  533. */
  534. JitsiParticipant.prototype.isModerator = function() {
  535. }
  536. // Gets a link to an etherpad instance advertised by the participant?
  537. //JitsiParticipant.prototype.getEtherpad = function() {
  538. //
  539. //}
  540. /*
  541. * @returns {Boolean} Whether this participant has muted their audio.
  542. */
  543. JitsiParticipant.prototype.isAudioMuted = function() {
  544. }
  545. /*
  546. * @returns {Boolean} Whether this participant has muted their video.
  547. */
  548. JitsiParticipant.prototype.isVideoMuted = function() {
  549. }
  550. /*
  551. * @returns {???} The latest statistics reported by this participant (i.e. info used to populate the GSM bars)
  552. * TODO: do we expose this or handle it internally?
  553. */
  554. JitsiParticipant.prototype.getLatestStats = function() {
  555. }
  556. /**
  557. * @returns {String} The role of this participant.
  558. */
  559. JitsiParticipant.prototype.getRole = function() {
  560. }
  561. /*
  562. * @returns {Boolean} Whether this participant is the conference focus (i.e. jicofo).
  563. */
  564. JitsiParticipant.prototype.isFocus = function() {
  565. }
  566. /*
  567. * @returns {Boolean} Whether this participant is a conference recorder (i.e. jirecon).
  568. */
  569. JitsiParticipant.prototype.isRecorder = function() {
  570. }
  571. /*
  572. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  573. */
  574. JitsiParticipant.prototype.isSipGateway = function() {
  575. }
  576. /**
  577. * @returns {String} The ID for this participant's avatar.
  578. */
  579. JitsiParticipant.prototype.getAvatarId = function() {
  580. }
  581. /**
  582. * @returns {Boolean} Whether this participant is currently sharing their screen.
  583. */
  584. JitsiParticipant.prototype.isScreenSharing = function() {
  585. }
  586. /**
  587. * @returns {String} The user agent of this participant (i.e. browser userAgent string).
  588. */
  589. JitsiParticipant.prototype.getUserAgent = function() {
  590. }
  591. /**
  592. * Kicks the participant from the conference (requires certain privileges).
  593. */
  594. JitsiParticipant.prototype.kick = function() {
  595. }
  596. /**
  597. * Asks this participant to mute themselves.
  598. */
  599. JitsiParticipant.prototype.askToMute = function() {
  600. }
  601. module.exports = JitsiParticipant();
  602. },{}],9:[function(require,module,exports){
  603. /* global config, APP, Strophe */
  604. // cache datachannels to avoid garbage collection
  605. // https://code.google.com/p/chromium/issues/detail?id=405545
  606. var RTCEvents = require("../../service/RTC/RTCEvents");
  607. /**
  608. * Binds "ondatachannel" event listener to given PeerConnection instance.
  609. * @param peerConnection WebRTC peer connection instance.
  610. */
  611. function DataChannels(peerConnection, emitter) {
  612. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  613. this.eventEmitter = emitter;
  614. this._dataChannels = [];
  615. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  616. // Although it's not a requirement to open separate channels from both bridge
  617. // and peer as single channel can be used for sending and receiving data.
  618. // So either channel opened by the bridge or the one opened here is enough
  619. // for communication with the bridge.
  620. /*var dataChannelOptions =
  621. {
  622. reliable: true
  623. };
  624. var dataChannel
  625. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  626. // Can be used only when is in open state
  627. dataChannel.onopen = function ()
  628. {
  629. dataChannel.send("My channel !!!");
  630. };
  631. dataChannel.onmessage = function (event)
  632. {
  633. var msgData = event.data;
  634. console.info("Got My Data Channel Message:", msgData, dataChannel);
  635. };*/
  636. };
  637. /**
  638. * Callback triggered by PeerConnection when new data channel is opened
  639. * on the bridge.
  640. * @param event the event info object.
  641. */
  642. DataChannels.prototype.onDataChannel = function (event) {
  643. var dataChannel = event.channel;
  644. var self = this;
  645. dataChannel.onopen = function () {
  646. console.info("Data channel opened by the Videobridge!", dataChannel);
  647. // Code sample for sending string and/or binary data
  648. // Sends String message to the bridge
  649. //dataChannel.send("Hello bridge!");
  650. // Sends 12 bytes binary message to the bridge
  651. //dataChannel.send(new ArrayBuffer(12));
  652. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  653. };
  654. dataChannel.onerror = function (error) {
  655. console.error("Data Channel Error:", error, dataChannel);
  656. };
  657. dataChannel.onmessage = function (event) {
  658. var data = event.data;
  659. // JSON
  660. var obj;
  661. try {
  662. obj = JSON.parse(data);
  663. }
  664. catch (e) {
  665. console.error(
  666. "Failed to parse data channel message as JSON: ",
  667. data,
  668. dataChannel);
  669. }
  670. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  671. var colibriClass = obj.colibriClass;
  672. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  673. // Endpoint ID from the Videobridge.
  674. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  675. console.info(
  676. "Data channel new dominant speaker event: ",
  677. dominantSpeakerEndpoint);
  678. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  679. }
  680. else if ("InLastNChangeEvent" === colibriClass) {
  681. var oldValue = obj.oldValue;
  682. var newValue = obj.newValue;
  683. // Make sure that oldValue and newValue are of type boolean.
  684. var type;
  685. if ((type = typeof oldValue) !== 'boolean') {
  686. if (type === 'string') {
  687. oldValue = (oldValue == "true");
  688. } else {
  689. oldValue = new Boolean(oldValue).valueOf();
  690. }
  691. }
  692. if ((type = typeof newValue) !== 'boolean') {
  693. if (type === 'string') {
  694. newValue = (newValue == "true");
  695. } else {
  696. newValue = new Boolean(newValue).valueOf();
  697. }
  698. }
  699. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  700. }
  701. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  702. // The new/latest list of last-n endpoint IDs.
  703. var lastNEndpoints = obj.lastNEndpoints;
  704. // The list of endpoint IDs which are entering the list of
  705. // last-n at this time i.e. were not in the old list of last-n
  706. // endpoint IDs.
  707. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  708. console.log(
  709. "Data channel new last-n event: ",
  710. lastNEndpoints, endpointsEnteringLastN, obj);
  711. this.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  712. lastNEndpoints, endpointsEnteringLastN, obj);
  713. }
  714. else {
  715. console.debug("Data channel JSON-formatted message: ", obj);
  716. }
  717. }
  718. };
  719. dataChannel.onclose = function () {
  720. console.info("The Data Channel closed", dataChannel);
  721. var idx = self._dataChannels.indexOf(dataChannel);
  722. if (idx > -1)
  723. self._dataChannels = self._dataChannels.splice(idx, 1);
  724. };
  725. this._dataChannels.push(dataChannel);
  726. };
  727. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  728. console.log('selected endpoint changed: ', userResource);
  729. if (this._dataChannels && this._dataChannels.length != 0) {
  730. this._dataChannels.some(function (dataChannel) {
  731. if (dataChannel.readyState == 'open') {
  732. console.log('sending selected endpoint changed ' +
  733. 'notification to the bridge: ', userResource);
  734. dataChannel.send(JSON.stringify({
  735. 'colibriClass': 'SelectedEndpointChangedEvent',
  736. 'selectedEndpoint':
  737. (!userResource || userResource === null)?
  738. null : userResource
  739. }));
  740. return true;
  741. }
  742. });
  743. }
  744. }
  745. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  746. console.log('pinned endpoint changed: ', userResource);
  747. if (this._dataChannels && this._dataChannels.length != 0) {
  748. this._dataChannels.some(function (dataChannel) {
  749. if (dataChannel.readyState == 'open') {
  750. dataChannel.send(JSON.stringify({
  751. 'colibriClass': 'PinnedEndpointChangedEvent',
  752. 'pinnedEndpoint':
  753. (!userResource || userResource == null)?
  754. null : userResource
  755. }));
  756. return true;
  757. }
  758. });
  759. }
  760. }
  761. module.exports = DataChannels;
  762. },{"../../service/RTC/RTCEvents":77}],10:[function(require,module,exports){
  763. var JitsiTrack = require("./JitsiTrack");
  764. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  765. var RTC = require("./RTCUtils");
  766. var RTCBrowserType = require("./RTCBrowserType");
  767. /**
  768. * Represents a single media track (either audio or video).
  769. * @constructor
  770. */
  771. function JitsiLocalTrack(RTC, stream, eventEmitter, videoType, isGUMStream)
  772. {
  773. JitsiTrack.call(this, RTC, stream);
  774. this.eventEmitter = eventEmitter;
  775. this.videoType = videoType;
  776. this.isGUMStream = true;
  777. this.dontFireRemoveEvent = false;
  778. this.isStarted = false;
  779. var self = this;
  780. if(isGUMStream === false)
  781. this.isGUMStream = isGUMStream;
  782. this.stream.onended = function () {
  783. if(!self.dontFireRemoveEvent)
  784. self.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, self);
  785. self.dontFireRemoveEvent = false;
  786. };
  787. }
  788. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  789. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  790. /**
  791. * Mutes / unmutes the track.
  792. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  793. */
  794. JitsiLocalTrack.prototype._setMute = function (mute) {
  795. var isAudio = this.type === JitsiTrack.AUDIO;
  796. this.dontFireRemoveEvent = false;
  797. if ((window.location.protocol != "https:" && this.isGUMStream) ||
  798. (isAudio && this.isGUMStream) || this.videoType === "screen" ||
  799. // FIXME FF does not support 'removeStream' method used to mute
  800. RTCBrowserType.isFirefox()) {
  801. var tracks = this._getTracks();
  802. for (var idx = 0; idx < tracks.length; idx++) {
  803. tracks[idx].enabled = !mute;
  804. }
  805. if(isAudio)
  806. this.rtc.room.setAudioMute(mute);
  807. else
  808. this.rtc.room.setVideoMute(mute);
  809. this.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  810. } else {
  811. if (mute) {
  812. this.dontFireRemoveEvent = true;
  813. this.rtc.room.removeStream(this.stream);
  814. this.stream.stop();
  815. if(isAudio)
  816. this.rtc.room.setAudioMute(mute);
  817. else
  818. this.rtc.room.setVideoMute(mute);
  819. this.stream = null;
  820. this.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  821. //FIXME: Maybe here we should set the SRC for the containers to something
  822. } else {
  823. var self = this;
  824. this.rtc.obtainAudioAndVideoPermissions(
  825. {devices: (isAudio ? ["audio"] : ["video"])}, true)
  826. .then(function (streams) {
  827. var stream = null;
  828. for(var i = 0; i < streams.length; i++) {
  829. stream = streams[i];
  830. if(stream.type === self.type) {
  831. self.stream = stream.stream;
  832. self.videoType = stream.videoType;
  833. self.isGUMStream = stream.isGUMStream;
  834. break;
  835. }
  836. }
  837. if(!stream)
  838. return;
  839. for(var i = 0; i < self.containers.length; i++)
  840. {
  841. RTC.attachMediaStream(self.containers[i], self.stream);
  842. }
  843. self.rtc.room.addStream(stream.stream,
  844. function () {
  845. if(isAudio)
  846. self.rtc.room.setAudioMute(mute);
  847. else
  848. self.rtc.room.setVideoMute(mute);
  849. self.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, self);
  850. });
  851. });
  852. }
  853. }
  854. }
  855. /**
  856. * Stops sending the media track. And removes it from the HTML.
  857. * NOTE: Works for local tracks only.
  858. */
  859. JitsiLocalTrack.prototype.stop = function () {
  860. if(!this.stream)
  861. return;
  862. this.rtc.room.removeStream(this.stream);
  863. this.stream.stop();
  864. this.detach();
  865. }
  866. /**
  867. * Starts sending the track.
  868. * NOTE: Works for local tracks only.
  869. */
  870. JitsiLocalTrack.prototype.start = function() {
  871. this.isStarted = true;
  872. this.rtc.room.addStream(this.stream, function () {});
  873. }
  874. /**
  875. * Returns <tt>true</tt> - if the stream is muted
  876. * and <tt>false</tt> otherwise.
  877. * @returns {boolean} <tt>true</tt> - if the stream is muted
  878. * and <tt>false</tt> otherwise.
  879. */
  880. JitsiLocalTrack.prototype.isMuted = function () {
  881. if (!this.stream)
  882. return true;
  883. var tracks = [];
  884. var isAudio = this.type === JitsiTrack.AUDIO;
  885. if (isAudio) {
  886. tracks = this.stream.getAudioTracks();
  887. } else {
  888. if (this.stream.ended)
  889. return true;
  890. tracks = this.stream.getVideoTracks();
  891. }
  892. for (var idx = 0; idx < tracks.length; idx++) {
  893. if(tracks[idx].enabled)
  894. return false;
  895. }
  896. return true;
  897. };
  898. module.exports = JitsiLocalTrack;
  899. },{"../../service/RTC/StreamEventTypes":79,"./JitsiTrack":12,"./RTCBrowserType":14,"./RTCUtils":15}],11:[function(require,module,exports){
  900. var JitsiTrack = require("./JitsiTrack");
  901. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  902. /**
  903. * Represents a single media track (either audio or video).
  904. * @param RTC the rtc instance.
  905. * @param data object with the stream and some details about it(participant id, video type, etc.)
  906. * @param sid sid for the Media Stream
  907. * @param ssrc ssrc for the Media Stream
  908. * @param eventEmitter the event emitter
  909. * @constructor
  910. */
  911. function JitsiRemoteTrack(RTC, data, sid, ssrc, eventEmitter) {
  912. JitsiTrack.call(this, RTC, data.stream);
  913. this.rtc = RTC;
  914. this.sid = sid;
  915. this.stream = data.stream;
  916. this.peerjid = data.peerjid;
  917. this.videoType = data.videoType;
  918. this.ssrc = ssrc;
  919. this.muted = false;
  920. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  921. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  922. this.muted = true
  923. }
  924. this.eventEmitter = eventEmitter;
  925. var self = this;
  926. if(this.stream)
  927. this.stream.onended = function () {
  928. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_ENDED, self);
  929. }
  930. }
  931. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  932. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  933. /**
  934. * Sets current muted status and fires an events for the change.
  935. * @param value the muted status.
  936. */
  937. JitsiRemoteTrack.prototype.setMute = function (value) {
  938. this.stream.muted = value;
  939. this.muted = value;
  940. this.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  941. };
  942. /**
  943. * Returns the current muted status of the track.
  944. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  945. */
  946. JitsiRemoteTrack.prototype.isMuted = function () {
  947. return this.muted;
  948. }
  949. /**
  950. * Returns the participant id which owns the track.
  951. * @returns {string} the id of the participants.
  952. */
  953. JitsiRemoteTrack.prototype.getParitcipantId = function() {
  954. return Strophe.getResourceFromJid(this.peerjid);
  955. };
  956. delete JitsiRemoteTrack.prototype.stop;
  957. delete JitsiRemoteTrack.prototype.start;
  958. module.exports = JitsiRemoteTrack;
  959. },{"../../service/RTC/StreamEventTypes":79,"./JitsiTrack":12}],12:[function(require,module,exports){
  960. var RTC = require("./RTCUtils");
  961. var RTCBrowserType = require("./RTCBrowserType");
  962. /**
  963. * This implements 'onended' callback normally fired by WebRTC after the stream
  964. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  965. * @param stream original WebRTC stream object to which 'onended' handling
  966. * will be added.
  967. */
  968. function implementOnEndedHandling(stream) {
  969. var originalStop = stream.stop;
  970. stream.stop = function () {
  971. originalStop.apply(stream);
  972. if (!stream.ended) {
  973. stream.ended = true;
  974. stream.onended();
  975. }
  976. };
  977. }
  978. /**
  979. * Represents a single media track (either audio or video).
  980. * @constructor
  981. */
  982. function JitsiTrack(RTC, stream)
  983. {
  984. /**
  985. * Array with the HTML elements that are displaying the streams.
  986. * @type {Array}
  987. */
  988. this.containers = [];
  989. this.rtc = RTC;
  990. this.stream = stream;
  991. this.type = (this.stream.getVideoTracks().length > 0)?
  992. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  993. if(this.type == "audio") {
  994. this._getTracks = function () {
  995. return this.stream.getAudioTracks();
  996. }.bind(this);
  997. } else {
  998. this._getTracks = function () {
  999. return this.stream.getVideoTracks();
  1000. }.bind(this);
  1001. }
  1002. if (RTCBrowserType.isFirefox() && this.stream) {
  1003. implementOnEndedHandling(this.stream);
  1004. }
  1005. }
  1006. /**
  1007. * JitsiTrack video type.
  1008. * @type {string}
  1009. */
  1010. JitsiTrack.VIDEO = "video";
  1011. /**
  1012. * JitsiTrack audio type.
  1013. * @type {string}
  1014. */
  1015. JitsiTrack.AUDIO = "audio";
  1016. /**
  1017. * Returns the type (audio or video) of this track.
  1018. */
  1019. JitsiTrack.prototype.getType = function() {
  1020. return this.type;
  1021. };
  1022. /**
  1023. * Returns the RTCMediaStream from the browser (?).
  1024. */
  1025. JitsiTrack.prototype.getOriginalStream = function() {
  1026. return this.stream;
  1027. }
  1028. /**
  1029. * Mutes the track.
  1030. */
  1031. JitsiTrack.prototype.mute = function () {
  1032. this._setMute(true);
  1033. }
  1034. /**
  1035. * Unmutes the stream.
  1036. */
  1037. JitsiTrack.prototype.unmute = function () {
  1038. this._setMute(false);
  1039. }
  1040. /**
  1041. * Attaches the MediaStream of this track to an HTML container (?).
  1042. * Adds the container to the list of containers that are displaying the track.
  1043. * @param container the HTML container
  1044. */
  1045. JitsiTrack.prototype.attach = function (container) {
  1046. if(this.stream)
  1047. RTC.attachMediaStream(container, this.stream);
  1048. this.containers.push(container);
  1049. }
  1050. /**
  1051. * Removes the track from the passed HTML container.
  1052. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  1053. */
  1054. JitsiTrack.prototype.detach = function (container) {
  1055. for(var i = 0; i < this.containers.length; i++)
  1056. {
  1057. if(this.containers[i].is(container))
  1058. {
  1059. this.containers.splice(i,1);
  1060. }
  1061. if(!container)
  1062. {
  1063. this.containers[i].find(">video").remove();
  1064. }
  1065. }
  1066. if(container)
  1067. $(container).find(">video").remove();
  1068. }
  1069. /**
  1070. * Stops sending the media track. And removes it from the HTML.
  1071. * NOTE: Works for local tracks only.
  1072. */
  1073. JitsiTrack.prototype.stop = function () {
  1074. }
  1075. /**
  1076. * Starts sending the track.
  1077. * NOTE: Works for local tracks only.
  1078. */
  1079. JitsiTrack.prototype.start = function() {
  1080. }
  1081. /**
  1082. * Returns true if this is a video track and the source of the video is a
  1083. * screen capture as opposed to a camera.
  1084. */
  1085. JitsiTrack.prototype.isScreenSharing = function(){
  1086. }
  1087. /**
  1088. * Returns id of the track.
  1089. * @returns {string} id of the track or null if this is fake track.
  1090. */
  1091. JitsiTrack.prototype.getId = function () {
  1092. var tracks = this.stream.getTracks();
  1093. if(!tracks || tracks.length === 0)
  1094. return null;
  1095. return tracks[0].id;
  1096. };
  1097. module.exports = JitsiTrack;
  1098. },{"./RTCBrowserType":14,"./RTCUtils":15}],13:[function(require,module,exports){
  1099. /* global APP */
  1100. var EventEmitter = require("events");
  1101. var RTCBrowserType = require("./RTCBrowserType");
  1102. var RTCUtils = require("./RTCUtils.js");
  1103. var JitsiTrack = require("./JitsiTrack");
  1104. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  1105. var DataChannels = require("./DataChannels");
  1106. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  1107. var DesktopSharingEventTypes
  1108. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1109. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  1110. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  1111. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  1112. var desktopsharing = require("../desktopsharing/desktopsharing");
  1113. function getMediaStreamUsage()
  1114. {
  1115. var result = {
  1116. audio: true,
  1117. video: true
  1118. };
  1119. /** There are some issues with the desktop sharing
  1120. * when this property is enabled.
  1121. * WARNING: We must change the implementation to start video/audio if we
  1122. * receive from the focus that the peer is not muted.
  1123. var isSecureConnection = window.location.protocol == "https:";
  1124. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  1125. {
  1126. result = {
  1127. audio: false,
  1128. video: false
  1129. };
  1130. }
  1131. **/
  1132. return result;
  1133. }
  1134. var rtcReady = false;
  1135. function RTC(room, options) {
  1136. this.devices = {
  1137. audio: true,
  1138. video: true
  1139. };
  1140. this.room = room;
  1141. this.localStreams = [];
  1142. this.remoteStreams = {};
  1143. this.localAudio = null;
  1144. this.localVideo = null;
  1145. this.eventEmitter = new EventEmitter();
  1146. var self = this;
  1147. this.options = options || {};
  1148. desktopsharing.addListener(
  1149. function (stream, isUsingScreenStream, callback) {
  1150. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  1151. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  1152. room.addPresenceListener("videomuted", function (values, from) {
  1153. if(self.remoteStreams[from])
  1154. self.remoteStreams[from][JitsiTrack.VIDEO].setMute(values.value == "true");
  1155. });
  1156. room.addPresenceListener("audiomuted", function (values, from) {
  1157. if(self.remoteStreams[from])
  1158. self.remoteStreams[from][JitsiTrack.AUDIO].setMute(values.value == "true");
  1159. });
  1160. }
  1161. /**
  1162. * Creates the local MediaStreams.
  1163. * @param options object for options (NOTE: currently only list of devices and resolution are supported)
  1164. * @param dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1165. * type: "audio" or "video", isMuted: true/false, videoType: "camera" or "desktop"}
  1166. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1167. * @returns {*} Promise object that will receive the new JitsiTracks
  1168. */
  1169. RTC.prototype.obtainAudioAndVideoPermissions = function (options, dontCreateJitsiTrack) {
  1170. return RTCUtils.obtainAudioAndVideoPermissions(this,
  1171. options.devices, getMediaStreamUsage(), options.resolution, dontCreateJitsiTrack);
  1172. }
  1173. RTC.prototype.onIncommingCall = function(event) {
  1174. if(this.options.config.openSctp)
  1175. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  1176. for(var i = 0; i < this.localStreams.length; i++)
  1177. if(this.localStreams[i].isStarted)
  1178. {
  1179. this.localStreams[i].start();
  1180. }
  1181. }
  1182. RTC.prototype.selectedEndpoint = function (id) {
  1183. if(this.dataChannels)
  1184. this.dataChannels.handleSelectedEndpointEvent(id);
  1185. }
  1186. RTC.prototype.pinEndpoint = function (id) {
  1187. if(this.dataChannels)
  1188. this.dataChannels.handlePinnedEndpointEvent(id);
  1189. }
  1190. RTC.prototype.addListener = function (type, listener) {
  1191. this.eventEmitter.on(type, listener);
  1192. };
  1193. RTC.prototype.removeListener = function (eventType, listener) {
  1194. this.eventEmitter.removeListener(eventType, listener);
  1195. };
  1196. RTC.addRTCReadyListener = function (listener) {
  1197. RTCUtils.eventEmitter.on(RTCEvents.RTC_READY, listener);
  1198. }
  1199. RTC.removeRTCReadyListener = function (listener) {
  1200. RTCUtils.eventEmitter.removeListener(RTCEvents.RTC_READY, listener);
  1201. }
  1202. RTC.isRTCReady = function () {
  1203. return rtcReady;
  1204. }
  1205. RTC.init = function (options) {
  1206. // In case of IE we continue from 'onReady' callback
  1207. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  1208. // once it is initialized.
  1209. var onReady = function () {
  1210. rtcReady = true;
  1211. RTCUtils.eventEmitter.emit(RTCEvents.RTC_READY, true);
  1212. };
  1213. RTCUtils.init(onReady, options || {});
  1214. // Call onReady() if Temasys plugin is not used
  1215. if (!RTCBrowserType.isTemasysPluginUsed()) {
  1216. onReady();
  1217. }
  1218. }
  1219. RTC.prototype.createLocalStreams = function (streams, change) {
  1220. for (var i = 0; i < streams.length; i++) {
  1221. var localStream = new JitsiLocalTrack(this, streams[i].stream,
  1222. this.eventEmitter, streams[i].videoType,
  1223. streams[i].isGUMStream);
  1224. this.localStreams.push(localStream);
  1225. if (streams[i].isMuted === true)
  1226. localStream.setMute(true);
  1227. if (streams[i].type == "audio") {
  1228. this.localAudio = localStream;
  1229. } else {
  1230. this.localVideo = localStream;
  1231. }
  1232. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  1233. if (change)
  1234. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  1235. this.eventEmitter.emit(eventType, localStream, streams[i].isMuted);
  1236. }
  1237. return this.localStreams;
  1238. };
  1239. RTC.prototype.removeLocalStream = function (stream) {
  1240. for(var i = 0; i < this.localStreams.length; i++) {
  1241. if(this.localStreams[i].getOriginalStream() === stream) {
  1242. delete this.localStreams[i];
  1243. return;
  1244. }
  1245. }
  1246. };
  1247. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  1248. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc,
  1249. this.eventEmitter);
  1250. if(!data.peerjid)
  1251. return;
  1252. var jid = data.peerjid;
  1253. if(!this.remoteStreams[jid]) {
  1254. this.remoteStreams[jid] = {};
  1255. }
  1256. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  1257. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  1258. return remoteStream;
  1259. };
  1260. RTC.getPCConstraints = function () {
  1261. return RTCUtils.pc_constraints;
  1262. };
  1263. RTC.prototype.getUserMediaWithConstraints = function(um, success_callback,
  1264. failure_callback, resolution,
  1265. bandwidth, fps, desktopStream)
  1266. {
  1267. return RTCUtils.getUserMediaWithConstraints(this, um, success_callback,
  1268. failure_callback, resolution, bandwidth, fps, desktopStream);
  1269. };
  1270. RTC.attachMediaStream = function (elSelector, stream) {
  1271. RTCUtils.attachMediaStream(elSelector, stream);
  1272. };
  1273. RTC.getStreamID = function (stream) {
  1274. return RTCUtils.getStreamID(stream);
  1275. };
  1276. RTC.getVideoSrc = function (element) {
  1277. return RTCUtils.getVideoSrc(element);
  1278. };
  1279. RTC.setVideoSrc = function (element, src) {
  1280. RTCUtils.setVideoSrc(element, src);
  1281. };
  1282. RTC.prototype.getVideoElementName = function () {
  1283. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  1284. };
  1285. RTC.prototype.dispose = function() {
  1286. };
  1287. RTC.prototype.muteRemoteVideoStream = function (jid, value) {
  1288. var stream;
  1289. if(this.remoteStreams[jid] &&
  1290. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1291. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  1292. }
  1293. if(!stream)
  1294. return true;
  1295. if (value != stream.muted) {
  1296. stream.setMute(value);
  1297. return true;
  1298. }
  1299. return false;
  1300. };
  1301. RTC.prototype.switchVideoStreams = function (new_stream) {
  1302. this.localVideo.stream = new_stream;
  1303. this.localStreams = [];
  1304. //in firefox we have only one stream object
  1305. if (this.localAudio.getOriginalStream() != new_stream)
  1306. this.localStreams.push(this.localAudio);
  1307. this.localStreams.push(this.localVideo);
  1308. };
  1309. /**
  1310. * Creates <tt>JitsiTrack</tt> instance and replaces it with the local video.
  1311. * The method also handles the sdp changes.
  1312. * @param stream the new MediaStream received by the browser.
  1313. * @param isUsingScreenStream <tt>true</tt> if the stream is for desktop stream.
  1314. * @param callback - function that will be called after the operation is completed.
  1315. */
  1316. RTC.prototype.changeLocalVideo = function (stream, isUsingScreenStream, callback) {
  1317. var oldStream = this.localVideo.getOriginalStream();
  1318. var type = (isUsingScreenStream ? "screen" : "camera");
  1319. var localCallback = callback;
  1320. if(this.localVideo.isMuted() && this.localVideo.videoType !== type) {
  1321. localCallback = function() {
  1322. this.room.setVideoMute(false, function(mute) {
  1323. this.eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);
  1324. }.bind(this));
  1325. callback();
  1326. };
  1327. }
  1328. // FIXME: Workaround for FF/IE/Safari
  1329. if (stream && stream.videoStream) {
  1330. stream = stream.videoStream;
  1331. }
  1332. var videoStream = RTCUtils.createStream(stream, true);
  1333. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  1334. // Stop the stream to trigger onended event for old stream
  1335. oldStream.stop();
  1336. this.switchVideoStreams(videoStream, oldStream);
  1337. this.room.switchStreams(videoStream, oldStream,localCallback);
  1338. };
  1339. /**
  1340. * Creates <tt>JitsiTrack</tt> instance and replaces it with the local audio.
  1341. * The method also handles the sdp changes.
  1342. * @param stream the new MediaStream received by the browser.
  1343. * @param callback - function that will be called after the operation is completed.
  1344. */
  1345. RTC.prototype.changeLocalAudio = function (stream, callback) {
  1346. var oldStream = this.localAudio.getOriginalStream();
  1347. var newStream = RTCUtils.createStream(stream);
  1348. this.localAudio = this.createLocalStream(newStream, "audio", true);
  1349. // Stop the stream to trigger onended event for old stream
  1350. oldStream.stop();
  1351. this.room.switchStreams(newStream, oldStream, callback, true);
  1352. };
  1353. RTC.prototype.isVideoMuted = function (jid) {
  1354. if (jid === APP.xmpp.myJid()) {
  1355. var localVideo = APP.RTC.localVideo;
  1356. return (!localVideo || localVideo.isMuted());
  1357. } else {
  1358. if (!this.remoteStreams[jid] ||
  1359. !this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1360. return null;
  1361. }
  1362. return this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  1363. }
  1364. };
  1365. RTC.prototype.setVideoMute = function (mute, callback, options) {
  1366. if (!this.localVideo)
  1367. return;
  1368. if (mute == this.localVideo.isMuted())
  1369. {
  1370. APP.xmpp.sendVideoInfoPresence(mute);
  1371. if (callback)
  1372. callback(mute);
  1373. }
  1374. else
  1375. {
  1376. this.localVideo.setMute(mute);
  1377. this.room.setVideoMute(
  1378. mute,
  1379. callback,
  1380. options);
  1381. }
  1382. };
  1383. RTC.prototype.setDeviceAvailability = function (devices) {
  1384. if(!devices)
  1385. return;
  1386. if(devices.audio === true || devices.audio === false)
  1387. this.devices.audio = devices.audio;
  1388. if(devices.video === true || devices.video === false)
  1389. this.devices.video = devices.video;
  1390. this.eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  1391. };
  1392. module.exports = RTC;
  1393. },{"../../service/RTC/MediaStreamTypes":76,"../../service/RTC/RTCEvents.js":77,"../../service/RTC/StreamEventTypes.js":79,"../../service/desktopsharing/DesktopSharingEventTypes":81,"../desktopsharing/desktopsharing":17,"./DataChannels":9,"./JitsiLocalTrack.js":10,"./JitsiRemoteTrack.js":11,"./JitsiTrack":12,"./RTCBrowserType":14,"./RTCUtils.js":15,"events":39}],14:[function(require,module,exports){
  1394. var currentBrowser;
  1395. var browserVersion;
  1396. var RTCBrowserType = {
  1397. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  1398. RTC_BROWSER_OPERA: "rtc_browser.opera",
  1399. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  1400. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  1401. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  1402. getBrowserType: function () {
  1403. return currentBrowser;
  1404. },
  1405. isChrome: function () {
  1406. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  1407. },
  1408. isOpera: function () {
  1409. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  1410. },
  1411. isFirefox: function () {
  1412. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  1413. },
  1414. isIExplorer: function () {
  1415. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1416. },
  1417. isSafari: function () {
  1418. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  1419. },
  1420. isTemasysPluginUsed: function () {
  1421. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  1422. },
  1423. getFirefoxVersion: function () {
  1424. return RTCBrowserType.isFirefox() ? browserVersion : null;
  1425. },
  1426. getChromeVersion: function () {
  1427. return RTCBrowserType.isChrome() ? browserVersion : null;
  1428. },
  1429. usesPlanB: function() {
  1430. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  1431. RTCBrowserType.isTemasysPluginUsed();
  1432. },
  1433. usesUnifiedPlan: function() {
  1434. return RTCBrowserType.isFirefox();
  1435. }
  1436. // Add version getters for other browsers when needed
  1437. };
  1438. // detectOpera() must be called before detectChrome() !!!
  1439. // otherwise Opera wil be detected as Chrome
  1440. function detectChrome() {
  1441. if (navigator.webkitGetUserMedia) {
  1442. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  1443. var userAgent = navigator.userAgent.toLowerCase();
  1444. // We can assume that user agent is chrome, because it's
  1445. // enforced when 'ext' streaming method is set
  1446. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  1447. console.log("This appears to be Chrome, ver: " + ver);
  1448. return ver;
  1449. }
  1450. return null;
  1451. }
  1452. function detectOpera() {
  1453. var userAgent = navigator.userAgent;
  1454. if (userAgent.match(/Opera|OPR/)) {
  1455. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  1456. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  1457. console.info("This appears to be Opera, ver: " + version);
  1458. return version;
  1459. }
  1460. return null;
  1461. }
  1462. function detectFirefox() {
  1463. if (navigator.mozGetUserMedia) {
  1464. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1465. var version = parseInt(
  1466. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1467. console.log('This appears to be Firefox, ver: ' + version);
  1468. return version;
  1469. }
  1470. return null;
  1471. }
  1472. function detectSafari() {
  1473. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1474. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1475. console.info("This appears to be Safari");
  1476. // FIXME detect Safari version when needed
  1477. return 1;
  1478. }
  1479. return null;
  1480. }
  1481. function detectIE() {
  1482. var version;
  1483. var ua = window.navigator.userAgent;
  1484. var msie = ua.indexOf('MSIE ');
  1485. if (msie > 0) {
  1486. // IE 10 or older => return version number
  1487. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1488. }
  1489. var trident = ua.indexOf('Trident/');
  1490. if (!version && trident > 0) {
  1491. // IE 11 => return version number
  1492. var rv = ua.indexOf('rv:');
  1493. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1494. }
  1495. var edge = ua.indexOf('Edge/');
  1496. if (!version && edge > 0) {
  1497. // IE 12 => return version number
  1498. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1499. }
  1500. if (version) {
  1501. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1502. console.info("This appears to be IExplorer, ver: " + version);
  1503. }
  1504. return version;
  1505. }
  1506. function detectBrowser() {
  1507. var version;
  1508. var detectors = [
  1509. detectOpera,
  1510. detectChrome,
  1511. detectFirefox,
  1512. detectIE,
  1513. detectSafari
  1514. ];
  1515. // Try all browser detectors
  1516. for (var i = 0; i < detectors.length; i++) {
  1517. version = detectors[i]();
  1518. if (version)
  1519. return version;
  1520. }
  1521. console.error("Failed to detect browser type");
  1522. return undefined;
  1523. }
  1524. browserVersion = detectBrowser();
  1525. module.exports = RTCBrowserType;
  1526. },{}],15:[function(require,module,exports){
  1527. /* global config, require, attachMediaStream, getUserMedia */
  1528. var RTCBrowserType = require("./RTCBrowserType");
  1529. var Resolutions = require("../../service/RTC/Resolutions");
  1530. var AdapterJS = require("./adapter.screenshare");
  1531. var SDPUtil = require("../xmpp/SDPUtil");
  1532. var EventEmitter = require("events");
  1533. function DummyMediaStream(id) {
  1534. this.id = id;
  1535. this.label = id;
  1536. this.stop = function() { };
  1537. this.getAudioTracks = function() { return []; };
  1538. this.getVideoTracks = function() { return []; };
  1539. }
  1540. function getPreviousResolution(resolution) {
  1541. if(!Resolutions[resolution])
  1542. return null;
  1543. var order = Resolutions[resolution].order;
  1544. var res = null;
  1545. var resName = null;
  1546. for(var i in Resolutions) {
  1547. var tmp = Resolutions[i];
  1548. if(res == null || (res.order < tmp.order && tmp.order < order)) {
  1549. resName = i;
  1550. res = tmp;
  1551. }
  1552. }
  1553. return resName;
  1554. }
  1555. function setResolutionConstraints(constraints, resolution, isAndroid) {
  1556. if (Resolutions[resolution]) {
  1557. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1558. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1559. }
  1560. else if (isAndroid) {
  1561. // FIXME can't remember if the purpose of this was to always request
  1562. // low resolution on Android ? if yes it should be moved up front
  1563. constraints.video.mandatory.minWidth = 320;
  1564. constraints.video.mandatory.minHeight = 240;
  1565. constraints.video.mandatory.maxFrameRate = 15;
  1566. }
  1567. if (constraints.video.mandatory.minWidth)
  1568. constraints.video.mandatory.maxWidth =
  1569. constraints.video.mandatory.minWidth;
  1570. if (constraints.video.mandatory.minHeight)
  1571. constraints.video.mandatory.maxHeight =
  1572. constraints.video.mandatory.minHeight;
  1573. }
  1574. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1575. {
  1576. var constraints = {audio: false, video: false};
  1577. if (um.indexOf('video') >= 0) {
  1578. // same behaviour as true
  1579. constraints.video = { mandatory: {}, optional: [] };
  1580. constraints.video.optional.push({ googLeakyBucket: true });
  1581. setResolutionConstraints(constraints, resolution, isAndroid);
  1582. }
  1583. if (um.indexOf('audio') >= 0) {
  1584. if (!RTCBrowserType.isFirefox()) {
  1585. // same behaviour as true
  1586. constraints.audio = { mandatory: {}, optional: []};
  1587. // if it is good enough for hangouts...
  1588. constraints.audio.optional.push(
  1589. {googEchoCancellation: true},
  1590. {googAutoGainControl: true},
  1591. {googNoiseSupression: true},
  1592. {googHighpassFilter: true},
  1593. {googNoisesuppression2: true},
  1594. {googEchoCancellation2: true},
  1595. {googAutoGainControl2: true}
  1596. );
  1597. } else {
  1598. constraints.audio = true;
  1599. }
  1600. }
  1601. if (um.indexOf('screen') >= 0) {
  1602. if (RTCBrowserType.isChrome()) {
  1603. constraints.video = {
  1604. mandatory: {
  1605. chromeMediaSource: "screen",
  1606. googLeakyBucket: true,
  1607. maxWidth: window.screen.width,
  1608. maxHeight: window.screen.height,
  1609. maxFrameRate: 3
  1610. },
  1611. optional: []
  1612. };
  1613. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1614. constraints.video = {
  1615. optional: [
  1616. {
  1617. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1618. }
  1619. ]
  1620. };
  1621. } else {
  1622. console.error(
  1623. "'screen' WebRTC media source is supported only in Chrome" +
  1624. " and with Temasys plugin");
  1625. }
  1626. }
  1627. if (um.indexOf('desktop') >= 0) {
  1628. constraints.video = {
  1629. mandatory: {
  1630. chromeMediaSource: "desktop",
  1631. chromeMediaSourceId: desktopStream,
  1632. googLeakyBucket: true,
  1633. maxWidth: window.screen.width,
  1634. maxHeight: window.screen.height,
  1635. maxFrameRate: 3
  1636. },
  1637. optional: []
  1638. };
  1639. }
  1640. if (bandwidth) {
  1641. if (!constraints.video) {
  1642. //same behaviour as true
  1643. constraints.video = {mandatory: {}, optional: []};
  1644. }
  1645. constraints.video.optional.push({bandwidth: bandwidth});
  1646. }
  1647. if (fps) {
  1648. // for some cameras it might be necessary to request 30fps
  1649. // so they choose 30fps mjpg over 10fps yuy2
  1650. if (!constraints.video) {
  1651. // same behaviour as true;
  1652. constraints.video = {mandatory: {}, optional: []};
  1653. }
  1654. constraints.video.mandatory.minFrameRate = fps;
  1655. }
  1656. return constraints;
  1657. }
  1658. //Options parameter is to pass config options. Currently uses only "useIPv6".
  1659. var RTCUtils = {
  1660. eventEmitter: new EventEmitter(),
  1661. init: function (onTemasysPluginReady, options) {
  1662. var self = this;
  1663. if (RTCBrowserType.isFirefox()) {
  1664. var FFversion = RTCBrowserType.getFirefoxVersion();
  1665. if (FFversion >= 40) {
  1666. this.peerconnection = mozRTCPeerConnection;
  1667. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1668. this.pc_constraints = {};
  1669. this.attachMediaStream = function (element, stream) {
  1670. // srcObject is being standardized and FF will eventually
  1671. // support that unprefixed. FF also supports the
  1672. // "element.src = URL.createObjectURL(...)" combo, but that
  1673. // will be deprecated in favour of srcObject.
  1674. //
  1675. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1676. // https://github.com/webrtc/samples/issues/302
  1677. if (!element[0])
  1678. return;
  1679. element[0].mozSrcObject = stream;
  1680. element[0].play();
  1681. };
  1682. this.getStreamID = function (stream) {
  1683. var id = stream.id;
  1684. if (!id) {
  1685. var tracks = stream.getVideoTracks();
  1686. if (!tracks || tracks.length === 0) {
  1687. tracks = stream.getAudioTracks();
  1688. }
  1689. id = tracks[0].id;
  1690. }
  1691. return SDPUtil.filter_special_chars(id);
  1692. };
  1693. this.getVideoSrc = function (element) {
  1694. if (!element)
  1695. return null;
  1696. return element.mozSrcObject;
  1697. };
  1698. this.setVideoSrc = function (element, src) {
  1699. if (element)
  1700. element.mozSrcObject = src;
  1701. };
  1702. RTCSessionDescription = mozRTCSessionDescription;
  1703. RTCIceCandidate = mozRTCIceCandidate;
  1704. } else {
  1705. console.error(
  1706. "Firefox version too old: " + FFversion + ". Required >= 40.");
  1707. window.location.href = 'unsupported_browser.html';
  1708. return;
  1709. }
  1710. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1711. this.peerconnection = webkitRTCPeerConnection;
  1712. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1713. this.attachMediaStream = function (element, stream) {
  1714. element.attr('src', webkitURL.createObjectURL(stream));
  1715. };
  1716. this.getStreamID = function (stream) {
  1717. // streams from FF endpoints have the characters '{' and '}'
  1718. // that make jQuery choke.
  1719. return SDPUtil.filter_special_chars(stream.id);
  1720. };
  1721. this.getVideoSrc = function (element) {
  1722. if (!element)
  1723. return null;
  1724. return element.getAttribute("src");
  1725. };
  1726. this.setVideoSrc = function (element, src) {
  1727. if (element)
  1728. element.setAttribute("src", src);
  1729. };
  1730. // DTLS should now be enabled by default but..
  1731. this.pc_constraints = {'optional': [
  1732. {'DtlsSrtpKeyAgreement': 'true'}
  1733. ]};
  1734. if (options.useIPv6) {
  1735. // https://code.google.com/p/webrtc/issues/detail?id=2828
  1736. this.pc_constraints.optional.push({googIPv6: true});
  1737. }
  1738. if (navigator.userAgent.indexOf('Android') != -1) {
  1739. this.pc_constraints = {}; // disable DTLS on Android
  1740. }
  1741. if (!webkitMediaStream.prototype.getVideoTracks) {
  1742. webkitMediaStream.prototype.getVideoTracks = function () {
  1743. return this.videoTracks;
  1744. };
  1745. }
  1746. if (!webkitMediaStream.prototype.getAudioTracks) {
  1747. webkitMediaStream.prototype.getAudioTracks = function () {
  1748. return this.audioTracks;
  1749. };
  1750. }
  1751. }
  1752. // Detect IE/Safari
  1753. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1754. //AdapterJS.WebRTCPlugin.setLogLevel(
  1755. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1756. AdapterJS.webRTCReady(function (isPlugin) {
  1757. self.peerconnection = RTCPeerConnection;
  1758. self.getUserMedia = getUserMedia;
  1759. self.attachMediaStream = function (elSel, stream) {
  1760. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1761. return;
  1762. }
  1763. attachMediaStream(elSel[0], stream);
  1764. };
  1765. self.getStreamID = function (stream) {
  1766. var id = SDPUtil.filter_special_chars(stream.label);
  1767. return id;
  1768. };
  1769. self.getVideoSrc = function (element) {
  1770. if (!element) {
  1771. console.warn("Attempt to get video SRC of null element");
  1772. return null;
  1773. }
  1774. var children = element.children;
  1775. for (var i = 0; i !== children.length; ++i) {
  1776. if (children[i].name === 'streamId') {
  1777. return children[i].value;
  1778. }
  1779. }
  1780. //console.info(element.id + " SRC: " + src);
  1781. return null;
  1782. };
  1783. self.setVideoSrc = function (element, src) {
  1784. //console.info("Set video src: ", element, src);
  1785. if (!src) {
  1786. console.warn("Not attaching video stream, 'src' is null");
  1787. return;
  1788. }
  1789. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1790. var stream = AdapterJS.WebRTCPlugin.plugin
  1791. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1792. attachMediaStream(element, stream);
  1793. };
  1794. onTemasysPluginReady(isPlugin);
  1795. });
  1796. } else {
  1797. try {
  1798. console.log('Browser does not appear to be WebRTC-capable');
  1799. } catch (e) {
  1800. }
  1801. window.location.href = 'unsupported_browser.html';
  1802. }
  1803. },
  1804. getUserMediaWithConstraints: function (RTC, um, success_callback, failure_callback, resolution, bandwidth, fps, desktopStream) {
  1805. // Check if we are running on Android device
  1806. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1807. var constraints = getConstraints(
  1808. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1809. console.info("Get media constraints", constraints);
  1810. var self = this;
  1811. try {
  1812. this.getUserMedia(constraints,
  1813. function (stream) {
  1814. console.log('onUserMediaSuccess');
  1815. self.setAvailableDevices(RTC, um, true);
  1816. success_callback(stream);
  1817. },
  1818. function (error) {
  1819. self.setAvailableDevices(RTC, um, false);
  1820. console.warn('Failed to get access to local media. Error ',
  1821. error, constraints);
  1822. if (failure_callback) {
  1823. failure_callback(error, resolution);
  1824. }
  1825. });
  1826. } catch (e) {
  1827. console.error('GUM failed: ', e);
  1828. if (failure_callback) {
  1829. failure_callback(e);
  1830. }
  1831. }
  1832. },
  1833. setAvailableDevices: function (RTC, um, available) {
  1834. var devices = {};
  1835. if (um.indexOf("video") != -1) {
  1836. devices.video = available;
  1837. }
  1838. if (um.indexOf("audio") != -1) {
  1839. devices.audio = available;
  1840. }
  1841. RTC.setDeviceAvailability(devices);
  1842. },
  1843. /**
  1844. * Creates the local MediaStreams.
  1845. * @param RTC the rtc service.
  1846. * @param devices the devices that will be requested
  1847. * @param usageOptions object with devices that should be requested.
  1848. * @param resolution resolution constraints
  1849. * @param dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1850. * type: "audio" or "video", isMuted: true/false, videoType: "camera" or "desktop"}
  1851. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1852. * @returns {*} Promise object that will receive the new JitsiTracks
  1853. */
  1854. obtainAudioAndVideoPermissions: function (RTC, devices, usageOptions, resolution, dontCreateJitsiTracks) {
  1855. var self = this;
  1856. // Get AV
  1857. return new Promise(function (resolve, reject) {
  1858. var successCallback = function (stream) {
  1859. var streams = self.successCallback(RTC , stream, usageOptions);
  1860. resolve(dontCreateJitsiTracks? streams: RTC.createLocalStreams(streams));
  1861. };
  1862. if (!devices)
  1863. devices = ['audio', 'video'];
  1864. var newDevices = [];
  1865. if (usageOptions)
  1866. for (var i = 0; i < devices.length; i++) {
  1867. var device = devices[i];
  1868. if (usageOptions[device] === true)
  1869. newDevices.push(device);
  1870. }
  1871. else
  1872. newDevices = devices;
  1873. if (newDevices.length === 0) {
  1874. successCallback();
  1875. return;
  1876. }
  1877. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1878. // With FF/IE we can't split the stream into audio and video because FF
  1879. // doesn't support media stream constructors. So, we need to get the
  1880. // audio stream separately from the video stream using two distinct GUM
  1881. // calls. Not very user friendly :-( but we don't have many other
  1882. // options neither.
  1883. //
  1884. // Note that we pack those 2 streams in a single object and pass it to
  1885. // the successCallback method.
  1886. var obtainVideo = function (audioStream) {
  1887. self.getUserMediaWithConstraints(
  1888. RTC,
  1889. ['video'],
  1890. function (videoStream) {
  1891. return successCallback({
  1892. audioStream: audioStream,
  1893. videoStream: videoStream
  1894. });
  1895. },
  1896. function (error, resolution) {
  1897. console.error(
  1898. 'failed to obtain video stream - stop', error);
  1899. self.errorCallback(error, resolve, RTC, resolution, dontCreateJitsiTracks);
  1900. },
  1901. resolution || '360');
  1902. };
  1903. var obtainAudio = function () {
  1904. self.getUserMediaWithConstraints(
  1905. RTC,
  1906. ['audio'],
  1907. function (audioStream) {
  1908. if (newDevices.indexOf('video') !== -1)
  1909. obtainVideo(audioStream);
  1910. },
  1911. function (error) {
  1912. console.error(
  1913. 'failed to obtain audio stream - stop', error);
  1914. self.errorCallback(error, resolve, RTC, null, dontCreateJitsiTracks);
  1915. }
  1916. );
  1917. };
  1918. if (newDevices.indexOf('audio') !== -1) {
  1919. obtainAudio();
  1920. } else {
  1921. obtainVideo(null);
  1922. }
  1923. } else {
  1924. this.getUserMediaWithConstraints(
  1925. RTC,
  1926. newDevices,
  1927. function (stream) {
  1928. successCallback(stream);
  1929. },
  1930. function (error, resolution) {
  1931. self.errorCallback(error, resolve, RTC, resolution, dontCreateJitsiTracks);
  1932. },
  1933. resolution || '360');
  1934. }
  1935. }.bind(this));
  1936. },
  1937. /**
  1938. * Successful callback called from GUM.
  1939. * @param RTC the rtc service
  1940. * @param stream the new MediaStream
  1941. * @param usageOptions the list of the devices that should be queried.
  1942. * @returns {*}
  1943. */
  1944. successCallback: function (RTC, stream, usageOptions) {
  1945. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1946. // it's an object with two properties: audioStream, videoStream.
  1947. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1948. console.log('got', stream, stream.getAudioTracks().length,
  1949. stream.getVideoTracks().length);
  1950. return this.handleLocalStream(RTC, stream, usageOptions);
  1951. },
  1952. /**
  1953. * Error callback called from GUM. Retries the GUM call with different resolutions.
  1954. * @param error the error
  1955. * @param resolve the resolve funtion that will be called on success.
  1956. * @param RTC the rtc service
  1957. * @param currentResolution the last resolution used for GUM.
  1958. * @param dontCreateJitsiTracks if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1959. * type: "audio" or "video", isMuted: true/false, videoType: "camera" or "desktop"}
  1960. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1961. */
  1962. errorCallback: function (error, resolve, RTC, currentResolution, dontCreateJitsiTracks) {
  1963. var self = this;
  1964. console.error('failed to obtain audio/video stream - trying audio only', error);
  1965. var resolution = getPreviousResolution(currentResolution);
  1966. if (typeof error == "object" && error.constraintName && error.name
  1967. && (error.name == "ConstraintNotSatisfiedError" ||
  1968. error.name == "OverconstrainedError") &&
  1969. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1970. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1971. && resolution != null) {
  1972. self.getUserMediaWithConstraints(RTC, ['audio', 'video'],
  1973. function (stream) {
  1974. var streams = self.successCallback(RTC, stream);
  1975. resolve(dontCreateJitsiTracks? streams: RTC.createLocalStreams(streams));
  1976. }, function (error, resolution) {
  1977. return self.errorCallback(error, resolve, RTC, resolution, dontCreateJitsiTracks);
  1978. }, resolution);
  1979. }
  1980. else {
  1981. self.getUserMediaWithConstraints(
  1982. RTC,
  1983. ['audio'],
  1984. function (stream) {
  1985. var streams = self.successCallback(RTC, stream);
  1986. resolve(dontCreateJitsiTracks? streams: RTC.createLocalStreams(streams));
  1987. },
  1988. function (error) {
  1989. console.error('failed to obtain audio/video stream - stop',
  1990. error);
  1991. var streams = self.successCallback(RTC, null);
  1992. resolve(dontCreateJitsiTracks? streams: RTC.createLocalStreams(streams));
  1993. }
  1994. );
  1995. }
  1996. },
  1997. /**
  1998. * Handles the newly created Media Streams.
  1999. * @param service the rtc service
  2000. * @param stream the new Media Streams
  2001. * @param usageOptions the list of the devices that should be queried.
  2002. * @returns {*[]} Promise object with the new Media Streams.
  2003. */
  2004. handleLocalStream: function (service, stream, usageOptions) {
  2005. var audioStream, videoStream;
  2006. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  2007. // an object with two properties: audioStream, videoStream.
  2008. if (window.webkitMediaStream) {
  2009. audioStream = new webkitMediaStream();
  2010. videoStream = new webkitMediaStream();
  2011. if (stream) {
  2012. var audioTracks = stream.getAudioTracks();
  2013. for (var i = 0; i < audioTracks.length; i++) {
  2014. audioStream.addTrack(audioTracks[i]);
  2015. }
  2016. var videoTracks = stream.getVideoTracks();
  2017. for (i = 0; i < videoTracks.length; i++) {
  2018. videoStream.addTrack(videoTracks[i]);
  2019. }
  2020. }
  2021. }
  2022. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  2023. if (stream && stream.audioStream)
  2024. audioStream = stream.audioStream;
  2025. else
  2026. audioStream = new DummyMediaStream("dummyAudio");
  2027. if (stream && stream.videoStream)
  2028. videoStream = stream.videoStream;
  2029. else
  2030. videoStream = new DummyMediaStream("dummyVideo");
  2031. }
  2032. var audioMuted = (usageOptions && usageOptions.audio === false),
  2033. videoMuted = (usageOptions && usageOptions.video === false);
  2034. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  2035. videoGUM = (!usageOptions || usageOptions.video !== false);
  2036. return [
  2037. {stream: audioStream, type: "audio", isMuted: audioMuted, isGUMStream: audioGUM, videoType: null},
  2038. {stream: videoStream, type: "video", isMuted: videoMuted, isGUMStream: videoGUM, videoType: "camera"}
  2039. ];
  2040. },
  2041. createStream: function (stream, isVideo) {
  2042. var newStream = null;
  2043. if (window.webkitMediaStream) {
  2044. newStream = new webkitMediaStream();
  2045. if (newStream) {
  2046. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  2047. for (var i = 0; i < tracks.length; i++) {
  2048. newStream.addTrack(tracks[i]);
  2049. }
  2050. }
  2051. } else {
  2052. // FIXME: this is duplicated with 'handleLocalStream' !!!
  2053. if (stream) {
  2054. newStream = stream;
  2055. } else {
  2056. newStream =
  2057. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  2058. }
  2059. }
  2060. return newStream;
  2061. }
  2062. }
  2063. module.exports = RTCUtils;
  2064. },{"../../service/RTC/Resolutions":78,"../xmpp/SDPUtil":29,"./RTCBrowserType":14,"./adapter.screenshare":16,"events":39}],16:[function(require,module,exports){
  2065. /*! adapterjs - v0.12.0 - 2015-09-04 */
  2066. // Adapter's interface.
  2067. var AdapterJS = AdapterJS || {};
  2068. // Browserify compatibility
  2069. if(typeof exports !== 'undefined') {
  2070. module.exports = AdapterJS;
  2071. }
  2072. AdapterJS.options = AdapterJS.options || {};
  2073. // uncomment to get virtual webcams
  2074. // AdapterJS.options.getAllCams = true;
  2075. // uncomment to prevent the install prompt when the plugin in not yet installed
  2076. // AdapterJS.options.hidePluginInstallPrompt = true;
  2077. // AdapterJS version
  2078. AdapterJS.VERSION = '0.12.0';
  2079. // This function will be called when the WebRTC API is ready to be used
  2080. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  2081. // the plugin
  2082. // You may Override this function to synchronise the start of your application
  2083. // with the WebRTC API being ready.
  2084. // If you decide not to override use this synchronisation, it may result in
  2085. // an extensive CPU usage on the plugin start (once per tab loaded)
  2086. // Params:
  2087. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  2088. //
  2089. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  2090. // The WebRTC API is ready.
  2091. // Override me and do whatever you want here
  2092. };
  2093. // Sets a callback function to be called when the WebRTC interface is ready.
  2094. // The first argument is the function to callback.\
  2095. // Throws an error if the first argument is not a function
  2096. AdapterJS.webRTCReady = function (callback) {
  2097. if (typeof callback !== 'function') {
  2098. throw new Error('Callback provided is not a function');
  2099. }
  2100. if (true === AdapterJS.onwebrtcreadyDone) {
  2101. // All WebRTC interfaces are ready, just call the callback
  2102. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  2103. } else {
  2104. // will be triggered automatically when your browser/plugin is ready.
  2105. AdapterJS.onwebrtcready = callback;
  2106. }
  2107. };
  2108. // Plugin namespace
  2109. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  2110. // The object to store plugin information
  2111. AdapterJS.WebRTCPlugin.pluginInfo = {
  2112. prefix : 'Tem',
  2113. plugName : 'TemWebRTCPlugin',
  2114. pluginId : 'plugin0',
  2115. type : 'application/x-temwebrtcplugin',
  2116. onload : '__TemWebRTCReady0',
  2117. portalLink : 'http://skylink.io/plugin/',
  2118. downloadLink : null, //set below
  2119. companyName: 'Temasys'
  2120. };
  2121. if(!!navigator.platform.match(/^Mac/i)) {
  2122. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  2123. }
  2124. else if(!!navigator.platform.match(/^Win/i)) {
  2125. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  2126. }
  2127. AdapterJS.WebRTCPlugin.TAGS = {
  2128. NONE : 'none',
  2129. AUDIO : 'audio',
  2130. VIDEO : 'video'
  2131. };
  2132. // Unique identifier of each opened page
  2133. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  2134. // Use this whenever you want to call the plugin.
  2135. AdapterJS.WebRTCPlugin.plugin = null;
  2136. // Set log level for the plugin once it is ready.
  2137. // The different values are
  2138. // This is an asynchronous function that will run when the plugin is ready
  2139. AdapterJS.WebRTCPlugin.setLogLevel = null;
  2140. // Defines webrtc's JS interface according to the plugin's implementation.
  2141. // Define plugin Browsers as WebRTC Interface.
  2142. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  2143. // This function detects whether or not a plugin is installed.
  2144. // Checks if Not IE (firefox, for example), else if it's IE,
  2145. // we're running IE and do something. If not it is not supported.
  2146. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  2147. // Lets adapter.js wait until the the document is ready before injecting the plugin
  2148. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  2149. // Inject the HTML DOM object element into the page.
  2150. AdapterJS.WebRTCPlugin.injectPlugin = null;
  2151. // States of readiness that the plugin goes through when
  2152. // being injected and stated
  2153. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  2154. NONE : 0, // no plugin use
  2155. INITIALIZING : 1, // Detected need for plugin
  2156. INJECTING : 2, // Injecting plugin
  2157. INJECTED: 3, // Plugin element injected but not usable yet
  2158. READY: 4 // Plugin ready to be used
  2159. };
  2160. // Current state of the plugin. You cannot use the plugin before this is
  2161. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  2162. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  2163. // True is AdapterJS.onwebrtcready was already called, false otherwise
  2164. // Used to make sure AdapterJS.onwebrtcready is only called once
  2165. AdapterJS.onwebrtcreadyDone = false;
  2166. // Log levels for the plugin.
  2167. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  2168. /*
  2169. Log outputs are prefixed in some cases.
  2170. INFO: Information reported by the plugin.
  2171. ERROR: Errors originating from within the plugin.
  2172. WEBRTC: Error originating from within the libWebRTC library
  2173. */
  2174. // From the least verbose to the most verbose
  2175. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  2176. NONE : 'NONE',
  2177. ERROR : 'ERROR',
  2178. WARNING : 'WARNING',
  2179. INFO: 'INFO',
  2180. VERBOSE: 'VERBOSE',
  2181. SENSITIVE: 'SENSITIVE'
  2182. };
  2183. // Does a waiting check before proceeding to load the plugin.
  2184. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  2185. // This methid will use an interval to wait for the plugin to be ready.
  2186. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  2187. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  2188. // This function will be called when plugin is ready. It sends necessary
  2189. // details to the plugin.
  2190. // The function will wait for the document to be ready and the set the
  2191. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  2192. // indicating that it can start being requested.
  2193. // This function is not in the IE/Safari condition brackets so that
  2194. // TemPluginLoaded function might be called on Chrome/Firefox.
  2195. // This function is the only private function that is not encapsulated to
  2196. // allow the plugin method to be called.
  2197. __TemWebRTCReady0 = function () {
  2198. if (document.readyState === 'complete') {
  2199. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  2200. AdapterJS.maybeThroughWebRTCReady();
  2201. } else {
  2202. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  2203. if (document.readyState === 'complete') {
  2204. // TODO: update comments, we wait for the document to be ready
  2205. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  2206. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  2207. AdapterJS.maybeThroughWebRTCReady();
  2208. }
  2209. }, 100);
  2210. }
  2211. };
  2212. AdapterJS.maybeThroughWebRTCReady = function() {
  2213. if (!AdapterJS.onwebrtcreadyDone) {
  2214. AdapterJS.onwebrtcreadyDone = true;
  2215. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  2216. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  2217. }
  2218. }
  2219. };
  2220. // Text namespace
  2221. AdapterJS.TEXT = {
  2222. PLUGIN: {
  2223. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  2224. 'to work on this browser.',
  2225. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  2226. BUTTON: 'Install Now'
  2227. },
  2228. REFRESH: {
  2229. REQUIRE_REFRESH: 'Please refresh page',
  2230. BUTTON: 'Refresh Page'
  2231. }
  2232. };
  2233. // The result of ice connection states.
  2234. // - starting: Ice connection is starting.
  2235. // - checking: Ice connection is checking.
  2236. // - connected Ice connection is connected.
  2237. // - completed Ice connection is connected.
  2238. // - done Ice connection has been completed.
  2239. // - disconnected Ice connection has been disconnected.
  2240. // - failed Ice connection has failed.
  2241. // - closed Ice connection is closed.
  2242. AdapterJS._iceConnectionStates = {
  2243. starting : 'starting',
  2244. checking : 'checking',
  2245. connected : 'connected',
  2246. completed : 'connected',
  2247. done : 'completed',
  2248. disconnected : 'disconnected',
  2249. failed : 'failed',
  2250. closed : 'closed'
  2251. };
  2252. //The IceConnection states that has been fired for each peer.
  2253. AdapterJS._iceConnectionFiredStates = [];
  2254. // Check if WebRTC Interface is defined.
  2255. AdapterJS.isDefined = null;
  2256. // This function helps to retrieve the webrtc detected browser information.
  2257. // This sets:
  2258. // - webrtcDetectedBrowser: The browser agent name.
  2259. // - webrtcDetectedVersion: The browser version.
  2260. // - webrtcDetectedType: The types of webRTC support.
  2261. // - 'moz': Mozilla implementation of webRTC.
  2262. // - 'webkit': WebKit implementation of webRTC.
  2263. // - 'plugin': Using the plugin implementation.
  2264. AdapterJS.parseWebrtcDetectedBrowser = function () {
  2265. var hasMatch, checkMatch = navigator.userAgent.match(
  2266. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  2267. if (/trident/i.test(checkMatch[1])) {
  2268. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  2269. webrtcDetectedBrowser = 'IE';
  2270. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  2271. } else if (checkMatch[1] === 'Chrome') {
  2272. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2273. if (hasMatch !== null) {
  2274. webrtcDetectedBrowser = 'opera';
  2275. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  2276. }
  2277. }
  2278. if (navigator.userAgent.indexOf('Safari')) {
  2279. if (typeof InstallTrigger !== 'undefined') {
  2280. webrtcDetectedBrowser = 'firefox';
  2281. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  2282. webrtcDetectedBrowser = 'IE';
  2283. } else if (
  2284. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  2285. webrtcDetectedBrowser = 'safari';
  2286. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  2287. webrtcDetectedBrowser = 'opera';
  2288. } else if (!!window.chrome) {
  2289. webrtcDetectedBrowser = 'chrome';
  2290. }
  2291. }
  2292. if (!webrtcDetectedBrowser) {
  2293. webrtcDetectedVersion = checkMatch[1];
  2294. }
  2295. if (!webrtcDetectedVersion) {
  2296. try {
  2297. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  2298. [navigator.appName, navigator.appVersion, '-?'];
  2299. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  2300. checkMatch.splice(1, 1, hasMatch[1]);
  2301. }
  2302. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  2303. } catch (error) { }
  2304. }
  2305. };
  2306. // To fix configuration as some browsers does not support
  2307. // the 'urls' attribute.
  2308. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  2309. if (pcConfig === null) {
  2310. return;
  2311. }
  2312. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  2313. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  2314. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  2315. delete pcConfig.iceServers[i].urls;
  2316. }
  2317. }
  2318. };
  2319. AdapterJS.addEvent = function(elem, evnt, func) {
  2320. if (elem.addEventListener) { // W3C DOM
  2321. elem.addEventListener(evnt, func, false);
  2322. } else if (elem.attachEvent) {// OLD IE DOM
  2323. elem.attachEvent('on'+evnt, func);
  2324. } else { // No much to do
  2325. elem[evnt] = func;
  2326. }
  2327. };
  2328. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  2329. // only inject once the page is ready
  2330. if (document.readyState !== 'complete') {
  2331. return;
  2332. }
  2333. var w = window;
  2334. var i = document.createElement('iframe');
  2335. i.style.position = 'fixed';
  2336. i.style.top = '-41px';
  2337. i.style.left = 0;
  2338. i.style.right = 0;
  2339. i.style.width = '100%';
  2340. i.style.height = '40px';
  2341. i.style.backgroundColor = '#ffffe1';
  2342. i.style.border = 'none';
  2343. i.style.borderBottom = '1px solid #888888';
  2344. i.style.zIndex = '9999999';
  2345. if(typeof i.style.webkitTransition === 'string') {
  2346. i.style.webkitTransition = 'all .5s ease-out';
  2347. } else if(typeof i.style.transition === 'string') {
  2348. i.style.transition = 'all .5s ease-out';
  2349. }
  2350. document.body.appendChild(i);
  2351. c = (i.contentWindow) ? i.contentWindow :
  2352. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  2353. c.document.open();
  2354. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  2355. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  2356. 'middle; cursor: default;">' + text + '</span>');
  2357. if(buttonText && buttonLink) {
  2358. c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
  2359. c.document.close();
  2360. // On click on okay
  2361. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  2362. if (!!displayRefreshBar) {
  2363. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  2364. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  2365. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  2366. }
  2367. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  2368. e.preventDefault();
  2369. try {
  2370. event.cancelBubble = true;
  2371. } catch(error) { }
  2372. var pluginInstallInterval = setInterval(function(){
  2373. if(! isIE) {
  2374. navigator.plugins.refresh(false);
  2375. }
  2376. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2377. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2378. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2379. function() { // plugin now installed
  2380. clearInterval(pluginInstallInterval);
  2381. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  2382. },
  2383. function() {
  2384. // still no plugin detected, nothing to do
  2385. });
  2386. } , 500);
  2387. });
  2388. // On click on Cancel
  2389. AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
  2390. w.document.body.removeChild(i);
  2391. });
  2392. } else {
  2393. c.document.close();
  2394. }
  2395. setTimeout(function() {
  2396. if(typeof i.style.webkitTransform === 'string') {
  2397. i.style.webkitTransform = 'translateY(40px)';
  2398. } else if(typeof i.style.transform === 'string') {
  2399. i.style.transform = 'translateY(40px)';
  2400. } else {
  2401. i.style.top = '0px';
  2402. }
  2403. }, 300);
  2404. };
  2405. // -----------------------------------------------------------
  2406. // Detected webrtc implementation. Types are:
  2407. // - 'moz': Mozilla implementation of webRTC.
  2408. // - 'webkit': WebKit implementation of webRTC.
  2409. // - 'plugin': Using the plugin implementation.
  2410. webrtcDetectedType = null;
  2411. // Detected webrtc datachannel support. Types are:
  2412. // - 'SCTP': SCTP datachannel support.
  2413. // - 'RTP': RTP datachannel support.
  2414. webrtcDetectedDCSupport = null;
  2415. // Set the settings for creating DataChannels, MediaStream for
  2416. // Cross-browser compability.
  2417. // - This is only for SCTP based support browsers.
  2418. // the 'urls' attribute.
  2419. checkMediaDataChannelSettings =
  2420. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  2421. if (typeof callback !== 'function') {
  2422. return;
  2423. }
  2424. var beOfferer = true;
  2425. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  2426. // Nightly version does not require MozDontOfferDataChannel for interop
  2427. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  2428. var isPeerFirefox = peerBrowserAgent === 'firefox';
  2429. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  2430. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  2431. // Resends an updated version of constraints for MozDataChannel to work
  2432. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  2433. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  2434. try {
  2435. delete constraints.mandatory.MozDontOfferDataChannel;
  2436. } catch (error) {
  2437. console.error('Failed deleting MozDontOfferDataChannel');
  2438. console.error(error);
  2439. }
  2440. } else if ((isLocalFirefox && !isPeerFirefox)) {
  2441. constraints.mandatory.MozDontOfferDataChannel = true;
  2442. }
  2443. if (!isLocalFirefox) {
  2444. // temporary measure to remove Moz* constraints in non Firefox browsers
  2445. for (var prop in constraints.mandatory) {
  2446. if (constraints.mandatory.hasOwnProperty(prop)) {
  2447. if (prop.indexOf('Moz') !== -1) {
  2448. delete constraints.mandatory[prop];
  2449. }
  2450. }
  2451. }
  2452. }
  2453. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  2454. // interopability of the media stream
  2455. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  2456. beOfferer = false;
  2457. }
  2458. callback(beOfferer, constraints);
  2459. };
  2460. // Handles the differences for all browsers ice connection state output.
  2461. // - Tested outcomes are:
  2462. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  2463. // - Chrome (answerer) : 'checking' > 'connected'
  2464. // - Firefox (offerer) : 'checking' > 'connected'
  2465. // - Firefox (answerer): 'checking' > 'connected'
  2466. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  2467. if (typeof callback !== 'function') {
  2468. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  2469. return;
  2470. }
  2471. peerId = (peerId) ? peerId : 'peer';
  2472. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  2473. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  2474. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  2475. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  2476. AdapterJS._iceConnectionFiredStates[peerId] = [];
  2477. }
  2478. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  2479. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  2480. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  2481. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  2482. setTimeout(function () {
  2483. AdapterJS._iceConnectionFiredStates[peerId]
  2484. .push(AdapterJS._iceConnectionStates.done);
  2485. callback(AdapterJS._iceConnectionStates.done);
  2486. }, 1000);
  2487. }
  2488. callback(iceConnectionState);
  2489. }
  2490. return;
  2491. };
  2492. // Firefox:
  2493. // - Creates iceServer from the url for Firefox.
  2494. // - Create iceServer with stun url.
  2495. // - Create iceServer with turn url.
  2496. // - Ignore the transport parameter from TURN url for FF version <=27.
  2497. // - Return null for createIceServer if transport=tcp.
  2498. // - FF 27 and above supports transport parameters in TURN url,
  2499. // - So passing in the full url to create iceServer.
  2500. // Chrome:
  2501. // - Creates iceServer from the url for Chrome M33 and earlier.
  2502. // - Create iceServer with stun url.
  2503. // - Chrome M28 & above uses below TURN format.
  2504. // Plugin:
  2505. // - Creates Ice Server for Plugin Browsers
  2506. // - If Stun - Create iceServer with stun url.
  2507. // - Else - Create iceServer with turn url
  2508. // - This is a WebRTC Function
  2509. createIceServer = null;
  2510. // Firefox:
  2511. // - Creates IceServers for Firefox
  2512. // - Use .url for FireFox.
  2513. // - Multiple Urls support
  2514. // Chrome:
  2515. // - Creates iceServers from the urls for Chrome M34 and above.
  2516. // - .urls is supported since Chrome M34.
  2517. // - Multiple Urls support
  2518. // Plugin:
  2519. // - Creates Ice Servers for Plugin Browsers
  2520. // - Multiple Urls support
  2521. // - This is a WebRTC Function
  2522. createIceServers = null;
  2523. //------------------------------------------------------------
  2524. //The RTCPeerConnection object.
  2525. RTCPeerConnection = null;
  2526. // Creates RTCSessionDescription object for Plugin Browsers
  2527. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  2528. RTCSessionDescription : null;
  2529. // Creates RTCIceCandidate object for Plugin Browsers
  2530. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  2531. RTCIceCandidate : null;
  2532. // Get UserMedia (only difference is the prefix).
  2533. // Code from Adam Barth.
  2534. getUserMedia = null;
  2535. // Attach a media stream to an element.
  2536. attachMediaStream = null;
  2537. // Re-attach a media stream to an element.
  2538. reattachMediaStream = null;
  2539. // Detected browser agent name. Types are:
  2540. // - 'firefox': Firefox browser.
  2541. // - 'chrome': Chrome browser.
  2542. // - 'opera': Opera browser.
  2543. // - 'safari': Safari browser.
  2544. // - 'IE' - Internet Explorer browser.
  2545. webrtcDetectedBrowser = null;
  2546. // Detected browser version.
  2547. webrtcDetectedVersion = null;
  2548. // Check for browser types and react accordingly
  2549. if (navigator.mozGetUserMedia) {
  2550. webrtcDetectedBrowser = 'firefox';
  2551. webrtcDetectedVersion = parseInt(navigator
  2552. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2553. webrtcDetectedType = 'moz';
  2554. webrtcDetectedDCSupport = 'SCTP';
  2555. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2556. AdapterJS.maybeFixConfiguration(pcConfig);
  2557. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  2558. };
  2559. // The RTCSessionDescription object.
  2560. RTCSessionDescription = mozRTCSessionDescription;
  2561. window.RTCSessionDescription = RTCSessionDescription;
  2562. // The RTCIceCandidate object.
  2563. RTCIceCandidate = mozRTCIceCandidate;
  2564. window.RTCIceCandidate = RTCIceCandidate;
  2565. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  2566. navigator.getUserMedia = window.getUserMedia;
  2567. // Shim for MediaStreamTrack.getSources.
  2568. MediaStreamTrack.getSources = function(successCb) {
  2569. setTimeout(function() {
  2570. var infos = [
  2571. { kind: 'audio', id: 'default', label:'', facing:'' },
  2572. { kind: 'video', id: 'default', label:'', facing:'' }
  2573. ];
  2574. successCb(infos);
  2575. }, 0);
  2576. };
  2577. createIceServer = function (url, username, password) {
  2578. var iceServer = null;
  2579. var url_parts = url.split(':');
  2580. if (url_parts[0].indexOf('stun') === 0) {
  2581. iceServer = { url : url };
  2582. } else if (url_parts[0].indexOf('turn') === 0) {
  2583. if (webrtcDetectedVersion < 27) {
  2584. var turn_url_parts = url.split('?');
  2585. if (turn_url_parts.length === 1 ||
  2586. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2587. iceServer = {
  2588. url : turn_url_parts[0],
  2589. credential : password,
  2590. username : username
  2591. };
  2592. }
  2593. } else {
  2594. iceServer = {
  2595. url : url,
  2596. credential : password,
  2597. username : username
  2598. };
  2599. }
  2600. }
  2601. return iceServer;
  2602. };
  2603. createIceServers = function (urls, username, password) {
  2604. var iceServers = [];
  2605. for (i = 0; i < urls.length; i++) {
  2606. var iceServer = createIceServer(urls[i], username, password);
  2607. if (iceServer !== null) {
  2608. iceServers.push(iceServer);
  2609. }
  2610. }
  2611. return iceServers;
  2612. };
  2613. attachMediaStream = function (element, stream) {
  2614. element.mozSrcObject = stream;
  2615. if (stream !== null)
  2616. element.play();
  2617. return element;
  2618. };
  2619. reattachMediaStream = function (to, from) {
  2620. to.mozSrcObject = from.mozSrcObject;
  2621. to.play();
  2622. return to;
  2623. };
  2624. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2625. if (!callback) {
  2626. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2627. ': 1 argument required, but only 0 present.');
  2628. }
  2629. return callback([]);
  2630. };
  2631. // Fake get{Video,Audio}Tracks
  2632. if (!MediaStream.prototype.getVideoTracks) {
  2633. MediaStream.prototype.getVideoTracks = function () {
  2634. return [];
  2635. };
  2636. }
  2637. if (!MediaStream.prototype.getAudioTracks) {
  2638. MediaStream.prototype.getAudioTracks = function () {
  2639. return [];
  2640. };
  2641. }
  2642. AdapterJS.maybeThroughWebRTCReady();
  2643. } else if (navigator.webkitGetUserMedia) {
  2644. webrtcDetectedBrowser = 'chrome';
  2645. webrtcDetectedType = 'webkit';
  2646. webrtcDetectedVersion = parseInt(navigator
  2647. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2648. // check if browser is opera 20+
  2649. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2650. if (checkIfOpera !== null) {
  2651. webrtcDetectedBrowser = 'opera';
  2652. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2653. }
  2654. // check browser datachannel support
  2655. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2656. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2657. webrtcDetectedDCSupport = 'SCTP';
  2658. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2659. webrtcDetectedVersion > 24) {
  2660. webrtcDetectedDCSupport = 'RTP';
  2661. } else {
  2662. webrtcDetectedDCSupport = '';
  2663. }
  2664. createIceServer = function (url, username, password) {
  2665. var iceServer = null;
  2666. var url_parts = url.split(':');
  2667. if (url_parts[0].indexOf('stun') === 0) {
  2668. iceServer = { 'url' : url };
  2669. } else if (url_parts[0].indexOf('turn') === 0) {
  2670. iceServer = {
  2671. 'url' : url,
  2672. 'credential' : password,
  2673. 'username' : username
  2674. };
  2675. }
  2676. return iceServer;
  2677. };
  2678. createIceServers = function (urls, username, password) {
  2679. var iceServers = [];
  2680. if (webrtcDetectedVersion >= 34) {
  2681. iceServers = {
  2682. 'urls' : urls,
  2683. 'credential' : password,
  2684. 'username' : username
  2685. };
  2686. } else {
  2687. for (i = 0; i < urls.length; i++) {
  2688. var iceServer = createIceServer(urls[i], username, password);
  2689. if (iceServer !== null) {
  2690. iceServers.push(iceServer);
  2691. }
  2692. }
  2693. }
  2694. return iceServers;
  2695. };
  2696. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2697. if (webrtcDetectedVersion < 34) {
  2698. AdapterJS.maybeFixConfiguration(pcConfig);
  2699. }
  2700. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2701. };
  2702. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2703. navigator.getUserMedia = window.getUserMedia;
  2704. attachMediaStream = function (element, stream) {
  2705. if (typeof element.srcObject !== 'undefined') {
  2706. element.srcObject = stream;
  2707. } else if (typeof element.mozSrcObject !== 'undefined') {
  2708. element.mozSrcObject = stream;
  2709. } else if (typeof element.src !== 'undefined') {
  2710. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2711. } else {
  2712. console.log('Error attaching stream to element.');
  2713. }
  2714. return element;
  2715. };
  2716. reattachMediaStream = function (to, from) {
  2717. to.src = from.src;
  2718. return to;
  2719. };
  2720. AdapterJS.maybeThroughWebRTCReady();
  2721. } else if (navigator.mediaDevices && navigator.userAgent.match(
  2722. /Edge\/(\d+).(\d+)$/)) {
  2723. webrtcDetectedBrowser = 'edge';
  2724. webrtcDetectedVersion =
  2725. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  2726. // the minimum version still supported by adapter.
  2727. webrtcMinimumVersion = 12;
  2728. window.getUserMedia = navigator.getUserMedia.bind(navigator);
  2729. attachMediaStream = function(element, stream) {
  2730. element.srcObject = stream;
  2731. return element;
  2732. };
  2733. reattachMediaStream = function(to, from) {
  2734. to.srcObject = from.srcObject;
  2735. return to;
  2736. };
  2737. AdapterJS.maybeThroughWebRTCReady();
  2738. } else { // TRY TO USE PLUGIN
  2739. // IE 9 is not offering an implementation of console.log until you open a console
  2740. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2741. /* jshint -W020 */
  2742. console = {} || console;
  2743. // Implemented based on console specs from MDN
  2744. // You may override these functions
  2745. console.log = function (arg) {};
  2746. console.info = function (arg) {};
  2747. console.error = function (arg) {};
  2748. console.dir = function (arg) {};
  2749. console.exception = function (arg) {};
  2750. console.trace = function (arg) {};
  2751. console.warn = function (arg) {};
  2752. console.count = function (arg) {};
  2753. console.debug = function (arg) {};
  2754. console.count = function (arg) {};
  2755. console.time = function (arg) {};
  2756. console.timeEnd = function (arg) {};
  2757. console.group = function (arg) {};
  2758. console.groupCollapsed = function (arg) {};
  2759. console.groupEnd = function (arg) {};
  2760. /* jshint +W020 */
  2761. }
  2762. webrtcDetectedType = 'plugin';
  2763. webrtcDetectedDCSupport = 'plugin';
  2764. AdapterJS.parseWebrtcDetectedBrowser();
  2765. isIE = webrtcDetectedBrowser === 'IE';
  2766. /* jshint -W035 */
  2767. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2768. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2769. /* empty because it needs to prevent the function from running. */
  2770. }
  2771. };
  2772. /* jshint +W035 */
  2773. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2774. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2775. // Call immediately if possible
  2776. // Once the plugin is set, the code will always take this path
  2777. callback();
  2778. } else {
  2779. // otherwise start a 100ms interval
  2780. var checkPluginReadyState = setInterval(function () {
  2781. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2782. clearInterval(checkPluginReadyState);
  2783. callback();
  2784. }
  2785. }, 100);
  2786. }
  2787. };
  2788. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2789. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2790. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2791. });
  2792. };
  2793. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2794. // only inject once the page is ready
  2795. if (document.readyState !== 'complete') {
  2796. return;
  2797. }
  2798. // Prevent multiple injections
  2799. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2800. return;
  2801. }
  2802. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2803. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2804. var frag = document.createDocumentFragment();
  2805. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2806. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2807. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2808. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2809. '<param name="pluginId" value="' +
  2810. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2811. '<param name="windowless" value="false" /> ' +
  2812. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2813. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  2814. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  2815. // uncomment to be able to use virtual cams
  2816. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2817. '</object>';
  2818. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2819. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2820. }
  2821. document.body.appendChild(frag);
  2822. // Need to re-fetch the plugin
  2823. AdapterJS.WebRTCPlugin.plugin =
  2824. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2825. } else {
  2826. // Load Plugin
  2827. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2828. AdapterJS.WebRTCPlugin.plugin.id =
  2829. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2830. // IE will only start the plugin if it's ACTUALLY visible
  2831. if (isIE) {
  2832. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2833. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2834. } else { // The size of the plugin on Safari should be 0x0px
  2835. // so that the autorisation prompt is at the top
  2836. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2837. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2838. }
  2839. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2840. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2841. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2842. '<param name="pluginId" value="' +
  2843. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2844. '<param name="windowless" value="false" /> ' +
  2845. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2846. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  2847. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  2848. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2849. }
  2850. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2851. };
  2852. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2853. function (comName, plugName, installedCb, notInstalledCb) {
  2854. if (!isIE) {
  2855. var pluginArray = navigator.plugins;
  2856. for (var i = 0; i < pluginArray.length; i++) {
  2857. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2858. installedCb();
  2859. return;
  2860. }
  2861. }
  2862. notInstalledCb();
  2863. } else {
  2864. try {
  2865. var axo = new ActiveXObject(comName + '.' + plugName);
  2866. } catch (e) {
  2867. notInstalledCb();
  2868. return;
  2869. }
  2870. installedCb();
  2871. }
  2872. };
  2873. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2874. if (AdapterJS.WebRTCPlugin.pluginState ===
  2875. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2876. console.error("AdapterJS - WebRTC interface has already been defined");
  2877. return;
  2878. }
  2879. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2880. AdapterJS.isDefined = function (variable) {
  2881. return variable !== null && variable !== undefined;
  2882. };
  2883. createIceServer = function (url, username, password) {
  2884. var iceServer = null;
  2885. var url_parts = url.split(':');
  2886. if (url_parts[0].indexOf('stun') === 0) {
  2887. iceServer = {
  2888. 'url' : url,
  2889. 'hasCredentials' : false
  2890. };
  2891. } else if (url_parts[0].indexOf('turn') === 0) {
  2892. iceServer = {
  2893. 'url' : url,
  2894. 'hasCredentials' : true,
  2895. 'credential' : password,
  2896. 'username' : username
  2897. };
  2898. }
  2899. return iceServer;
  2900. };
  2901. createIceServers = function (urls, username, password) {
  2902. var iceServers = [];
  2903. for (var i = 0; i < urls.length; ++i) {
  2904. iceServers.push(createIceServer(urls[i], username, password));
  2905. }
  2906. return iceServers;
  2907. };
  2908. RTCSessionDescription = function (info) {
  2909. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2910. return AdapterJS.WebRTCPlugin.plugin.
  2911. ConstructSessionDescription(info.type, info.sdp);
  2912. };
  2913. RTCPeerConnection = function (servers, constraints) {
  2914. var iceServers = null;
  2915. if (servers) {
  2916. iceServers = servers.iceServers;
  2917. for (var i = 0; i < iceServers.length; i++) {
  2918. if (iceServers[i].urls && !iceServers[i].url) {
  2919. iceServers[i].url = iceServers[i].urls;
  2920. }
  2921. iceServers[i].hasCredentials = AdapterJS.
  2922. isDefined(iceServers[i].username) &&
  2923. AdapterJS.isDefined(iceServers[i].credential);
  2924. }
  2925. }
  2926. var mandatory = (constraints && constraints.mandatory) ?
  2927. constraints.mandatory : null;
  2928. var optional = (constraints && constraints.optional) ?
  2929. constraints.optional : null;
  2930. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2931. return AdapterJS.WebRTCPlugin.plugin.
  2932. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2933. iceServers, mandatory, optional);
  2934. };
  2935. MediaStreamTrack = {};
  2936. MediaStreamTrack.getSources = function (callback) {
  2937. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2938. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2939. });
  2940. };
  2941. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2942. constraints.audio = constraints.audio || false;
  2943. constraints.video = constraints.video || false;
  2944. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2945. AdapterJS.WebRTCPlugin.plugin.
  2946. getUserMedia(constraints, successCallback, failureCallback);
  2947. });
  2948. };
  2949. window.navigator.getUserMedia = window.getUserMedia;
  2950. attachMediaStream = function (element, stream) {
  2951. if (!element || !element.parentNode) {
  2952. return;
  2953. }
  2954. var streamId
  2955. if (stream === null) {
  2956. streamId = '';
  2957. }
  2958. else {
  2959. stream.enableSoundTracks(true); // TODO: remove on 0.12.0
  2960. streamId = stream.id;
  2961. }
  2962. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2963. var nodeName = element.nodeName.toLowerCase();
  2964. if (nodeName !== 'object') { // not a plugin <object> tag yet
  2965. var tag;
  2966. switch(nodeName) {
  2967. case 'audio':
  2968. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  2969. break;
  2970. case 'video':
  2971. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  2972. break;
  2973. default:
  2974. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  2975. }
  2976. var frag = document.createDocumentFragment();
  2977. var temp = document.createElement('div');
  2978. var classHTML = '';
  2979. if (element.className) {
  2980. classHTML = 'class="' + element.className + '" ';
  2981. } else if (element.attributes && element.attributes['class']) {
  2982. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2983. }
  2984. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2985. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2986. '<param name="pluginId" value="' + elementId + '" /> ' +
  2987. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2988. '<param name="windowless" value="true" /> ' +
  2989. '<param name="streamId" value="' + streamId + '" /> ' +
  2990. '<param name="tag" value="' + tag + '" /> ' +
  2991. '</object>';
  2992. while (temp.firstChild) {
  2993. frag.appendChild(temp.firstChild);
  2994. }
  2995. var height = '';
  2996. var width = '';
  2997. if (element.getBoundingClientRect) {
  2998. var rectObject = element.getBoundingClientRect();
  2999. width = rectObject.width + 'px';
  3000. height = rectObject.height + 'px';
  3001. }
  3002. else if (element.width) {
  3003. width = element.width;
  3004. height = element.height;
  3005. } else {
  3006. // TODO: What scenario could bring us here?
  3007. }
  3008. element.parentNode.insertBefore(frag, element);
  3009. frag = document.getElementById(elementId);
  3010. frag.width = width;
  3011. frag.height = height;
  3012. element.parentNode.removeChild(element);
  3013. } else { // already an <object> tag, just change the stream id
  3014. var children = element.children;
  3015. for (var i = 0; i !== children.length; ++i) {
  3016. if (children[i].name === 'streamId') {
  3017. children[i].value = streamId;
  3018. break;
  3019. }
  3020. }
  3021. element.setStreamId(streamId);
  3022. }
  3023. var newElement = document.getElementById(elementId);
  3024. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  3025. newElement.onplay = (element.onplay) ? element.onplay : function (arg) {};
  3026. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  3027. if (isIE) { // on IE the event needs to be plugged manually
  3028. newElement.attachEvent('onplaying', newElement.onplaying);
  3029. newElement.attachEvent('onplay', newElement.onplay);
  3030. newElement._TemOnClick = function (id) {
  3031. var arg = {
  3032. srcElement : document.getElementById(id)
  3033. };
  3034. newElement.onclick(arg);
  3035. };
  3036. }
  3037. return newElement;
  3038. };
  3039. reattachMediaStream = function (to, from) {
  3040. var stream = null;
  3041. var children = from.children;
  3042. for (var i = 0; i !== children.length; ++i) {
  3043. if (children[i].name === 'streamId') {
  3044. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3045. stream = AdapterJS.WebRTCPlugin.plugin
  3046. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  3047. break;
  3048. }
  3049. }
  3050. if (stream !== null) {
  3051. return attachMediaStream(to, stream);
  3052. } else {
  3053. console.log('Could not find the stream associated with this element');
  3054. }
  3055. };
  3056. RTCIceCandidate = function (candidate) {
  3057. if (!candidate.sdpMid) {
  3058. candidate.sdpMid = '';
  3059. }
  3060. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3061. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  3062. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  3063. );
  3064. };
  3065. // inject plugin
  3066. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  3067. AdapterJS.WebRTCPlugin.injectPlugin();
  3068. };
  3069. // This function will be called if the plugin is needed (browser different
  3070. // from Chrome or Firefox), but the plugin is not installed.
  3071. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  3072. function() {
  3073. AdapterJS.addEvent(document,
  3074. 'readystatechange',
  3075. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  3076. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  3077. };
  3078. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  3079. if (AdapterJS.options.hidePluginInstallPrompt) {
  3080. return;
  3081. }
  3082. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  3083. if(downloadLink) { // if download link
  3084. var popupString;
  3085. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  3086. popupString = 'This website requires you to install the ' +
  3087. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  3088. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  3089. ' WebRTC Plugin</a>' +
  3090. ' to work on this browser.';
  3091. } else { // no portal link, just print a generic explanation
  3092. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  3093. }
  3094. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  3095. } else { // no download link, just print a generic explanation
  3096. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  3097. }
  3098. };
  3099. // Try to detect the plugin and act accordingly
  3100. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3101. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3102. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3103. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  3104. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  3105. }
  3106. },{}],17:[function(require,module,exports){
  3107. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  3108. getUserMediaWithConstraints */
  3109. /**
  3110. * Indicates that desktop stream is currently in use(for toggle purpose).
  3111. * @type {boolean}
  3112. */
  3113. var isUsingScreenStream = false;
  3114. /**
  3115. * Indicates that switch stream operation is in progress and prevent from
  3116. * triggering new events.
  3117. * @type {boolean}
  3118. */
  3119. var switchInProgress = false;
  3120. /**
  3121. * Method used to get screen sharing stream.
  3122. *
  3123. * @type {function (stream_callback, failure_callback}
  3124. */
  3125. var obtainDesktopStream = null;
  3126. /**
  3127. * Indicates whether desktop sharing extension is installed.
  3128. * @type {boolean}
  3129. */
  3130. var extInstalled = false;
  3131. /**
  3132. * Indicates whether update of desktop sharing extension is required.
  3133. * @type {boolean}
  3134. */
  3135. var extUpdateRequired = false;
  3136. var AdapterJS = require("../RTC/adapter.screenshare");
  3137. var EventEmitter = require("events");
  3138. var eventEmitter = new EventEmitter();
  3139. var DesktopSharingEventTypes
  3140. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  3141. var RTCBrowserType = require("../RTC/RTCBrowserType");
  3142. var RTCEvents = require("../../service/RTC/RTCEvents");
  3143. /**
  3144. * Method obtains desktop stream from WebRTC 'screen' source.
  3145. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  3146. */
  3147. function obtainWebRTCScreen(streamCallback, failCallback) {
  3148. APP.RTC.getUserMediaWithConstraints(
  3149. ['screen'],
  3150. streamCallback,
  3151. failCallback
  3152. );
  3153. }
  3154. /**
  3155. * Constructs inline install URL for Chrome desktop streaming extension.
  3156. * The 'chromeExtensionId' must be defined in config.js.
  3157. * @returns {string}
  3158. */
  3159. function getWebStoreInstallUrl()
  3160. {
  3161. return "https://chrome.google.com/webstore/detail/" +
  3162. config.chromeExtensionId;
  3163. }
  3164. /**
  3165. * Checks whether extension update is required.
  3166. * @param minVersion minimal required version
  3167. * @param extVersion current extension version
  3168. * @returns {boolean}
  3169. */
  3170. function isUpdateRequired(minVersion, extVersion)
  3171. {
  3172. try
  3173. {
  3174. var s1 = minVersion.split('.');
  3175. var s2 = extVersion.split('.');
  3176. var len = Math.max(s1.length, s2.length);
  3177. for (var i = 0; i < len; i++)
  3178. {
  3179. var n1 = 0,
  3180. n2 = 0;
  3181. if (i < s1.length)
  3182. n1 = parseInt(s1[i]);
  3183. if (i < s2.length)
  3184. n2 = parseInt(s2[i]);
  3185. if (isNaN(n1) || isNaN(n2))
  3186. {
  3187. return true;
  3188. }
  3189. else if (n1 !== n2)
  3190. {
  3191. return n1 > n2;
  3192. }
  3193. }
  3194. // will happen if boths version has identical numbers in
  3195. // their components (even if one of them is longer, has more components)
  3196. return false;
  3197. }
  3198. catch (e)
  3199. {
  3200. console.error("Failed to parse extension version", e);
  3201. APP.UI.messageHandler.showError("dialog.error",
  3202. "dialog.detectext");
  3203. return true;
  3204. }
  3205. }
  3206. function checkChromeExtInstalled(callback) {
  3207. if (!chrome.runtime) {
  3208. // No API, so no extension for sure
  3209. callback(false, false);
  3210. return;
  3211. }
  3212. chrome.runtime.sendMessage(
  3213. config.chromeExtensionId,
  3214. { getVersion: true },
  3215. function (response) {
  3216. if (!response || !response.version) {
  3217. // Communication failure - assume that no endpoint exists
  3218. console.warn(
  3219. "Extension not installed?: ", chrome.runtime.lastError);
  3220. callback(false, false);
  3221. return;
  3222. }
  3223. // Check installed extension version
  3224. var extVersion = response.version;
  3225. console.log('Extension version is: ' + extVersion);
  3226. var updateRequired
  3227. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  3228. callback(!updateRequired, updateRequired);
  3229. }
  3230. );
  3231. }
  3232. function doGetStreamFromExtension(streamCallback, failCallback) {
  3233. // Sends 'getStream' msg to the extension.
  3234. // Extension id must be defined in the config.
  3235. chrome.runtime.sendMessage(
  3236. config.chromeExtensionId,
  3237. { getStream: true, sources: config.desktopSharingSources },
  3238. function (response) {
  3239. if (!response) {
  3240. failCallback(chrome.runtime.lastError);
  3241. return;
  3242. }
  3243. console.log("Response from extension: " + response);
  3244. if (response.streamId) {
  3245. APP.RTC.getUserMediaWithConstraints(
  3246. ['desktop'],
  3247. function (stream) {
  3248. streamCallback(stream);
  3249. },
  3250. failCallback,
  3251. null, null, null,
  3252. response.streamId);
  3253. } else {
  3254. failCallback("Extension failed to get the stream");
  3255. }
  3256. }
  3257. );
  3258. }
  3259. /**
  3260. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  3261. * stream for returned stream token.
  3262. */
  3263. function obtainScreenFromExtension(streamCallback, failCallback) {
  3264. if (extInstalled) {
  3265. doGetStreamFromExtension(streamCallback, failCallback);
  3266. } else {
  3267. if (extUpdateRequired) {
  3268. alert(
  3269. 'Jitsi Desktop Streamer requires update. ' +
  3270. 'Changes will take effect after next Chrome restart.');
  3271. }
  3272. chrome.webstore.install(
  3273. getWebStoreInstallUrl(),
  3274. function (arg) {
  3275. console.log("Extension installed successfully", arg);
  3276. extInstalled = true;
  3277. // We need to give a moment for the endpoint to become available
  3278. window.setTimeout(function () {
  3279. doGetStreamFromExtension(streamCallback, failCallback);
  3280. }, 500);
  3281. },
  3282. function (arg) {
  3283. console.log("Failed to install the extension", arg);
  3284. failCallback(arg);
  3285. APP.UI.messageHandler.showError("dialog.error",
  3286. "dialog.failtoinstall");
  3287. }
  3288. );
  3289. }
  3290. }
  3291. /**
  3292. * Call this method to toggle desktop sharing feature.
  3293. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  3294. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  3295. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  3296. * enabled), pass any other string or nothing in order to disable this
  3297. * feature completely.
  3298. */
  3299. function setDesktopSharing(method) {
  3300. obtainDesktopStream = null;
  3301. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  3302. // care about 'method' parameter
  3303. if (RTCBrowserType.isTemasysPluginUsed()) {
  3304. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  3305. console.info("Screensharing not supported by this plugin version");
  3306. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3307. console.info(
  3308. "Screensharing not available with Temasys plugin on this site");
  3309. } else {
  3310. obtainDesktopStream = obtainWebRTCScreen;
  3311. console.info("Using Temasys plugin for desktop sharing");
  3312. }
  3313. } else if (RTCBrowserType.isChrome()) {
  3314. if (method == "ext") {
  3315. if (RTCBrowserType.getChromeVersion() >= 34) {
  3316. obtainDesktopStream = obtainScreenFromExtension;
  3317. console.info("Using Chrome extension for desktop sharing");
  3318. initChromeExtension();
  3319. } else {
  3320. console.info("Chrome extension not supported until ver 34");
  3321. }
  3322. } else if (method == "webrtc") {
  3323. obtainDesktopStream = obtainWebRTCScreen;
  3324. console.info("Using Chrome WebRTC for desktop sharing");
  3325. }
  3326. }
  3327. if (!obtainDesktopStream) {
  3328. console.info("Desktop sharing disabled");
  3329. }
  3330. }
  3331. /**
  3332. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3333. * config.js to support inline installs. Host site must be selected as main
  3334. * website of published extension.
  3335. */
  3336. function initInlineInstalls()
  3337. {
  3338. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  3339. }
  3340. function initChromeExtension() {
  3341. // Initialize Chrome extension inline installs
  3342. initInlineInstalls();
  3343. // Check if extension is installed
  3344. checkChromeExtInstalled(function (installed, updateRequired) {
  3345. extInstalled = installed;
  3346. extUpdateRequired = updateRequired;
  3347. console.info(
  3348. "Chrome extension installed: " + extInstalled +
  3349. " updateRequired: " + extUpdateRequired);
  3350. });
  3351. }
  3352. function getVideoStreamFailed(error) {
  3353. console.error("Failed to obtain the stream to switch to", error);
  3354. switchInProgress = false;
  3355. isUsingScreenStream = false;
  3356. newStreamCreated(null);
  3357. }
  3358. function getDesktopStreamFailed(error) {
  3359. console.error("Failed to obtain the stream to switch to", error);
  3360. switchInProgress = false;
  3361. }
  3362. function streamSwitchDone() {
  3363. switchInProgress = false;
  3364. eventEmitter.emit(
  3365. DesktopSharingEventTypes.SWITCHING_DONE,
  3366. isUsingScreenStream);
  3367. }
  3368. function newStreamCreated(stream)
  3369. {
  3370. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  3371. stream, isUsingScreenStream, streamSwitchDone);
  3372. }
  3373. function onEndedHandler(stream) {
  3374. if (!switchInProgress && isUsingScreenStream) {
  3375. APP.desktopsharing.toggleScreenSharing();
  3376. }
  3377. //FIXME: to be verified
  3378. if (stream.removeEventListener) {
  3379. stream.removeEventListener('ended', onEndedHandler);
  3380. } else {
  3381. stream.detachEvent('ended', onEndedHandler);
  3382. }
  3383. }
  3384. // Called when RTC finishes initialization
  3385. function onWebRtcReady() {
  3386. setDesktopSharing(config.desktopSharing);
  3387. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  3388. }
  3389. module.exports = {
  3390. isUsingScreenStream: function () {
  3391. return isUsingScreenStream;
  3392. },
  3393. /**
  3394. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  3395. * and enabled.
  3396. */
  3397. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  3398. init: function () {
  3399. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  3400. },
  3401. addListener: function (listener, type)
  3402. {
  3403. eventEmitter.on(type, listener);
  3404. },
  3405. removeListener: function (listener, type) {
  3406. eventEmitter.removeListener(type, listener);
  3407. },
  3408. /*
  3409. * Toggles screen sharing.
  3410. */
  3411. toggleScreenSharing: function () {
  3412. if (switchInProgress || !obtainDesktopStream) {
  3413. console.warn("Switch in progress or no method defined");
  3414. return;
  3415. }
  3416. switchInProgress = true;
  3417. if (!isUsingScreenStream)
  3418. {
  3419. // Switch to desktop stream
  3420. obtainDesktopStream(
  3421. function (stream) {
  3422. // We now use screen stream
  3423. isUsingScreenStream = true;
  3424. // Hook 'ended' event to restore camera
  3425. // when screen stream stops
  3426. //FIXME: to be verified
  3427. if (stream.addEventListener) {
  3428. stream.addEventListener('ended', function () {
  3429. onEndedHandler(stream);
  3430. });
  3431. } else {
  3432. stream.attachEvent('ended', function () {
  3433. onEndedHandler(stream);
  3434. });
  3435. }
  3436. newStreamCreated(stream);
  3437. },
  3438. getDesktopStreamFailed);
  3439. } else {
  3440. // Disable screen stream
  3441. APP.RTC.getUserMediaWithConstraints(
  3442. ['video'],
  3443. function (stream) {
  3444. // We are now using camera stream
  3445. isUsingScreenStream = false;
  3446. newStreamCreated(stream);
  3447. },
  3448. getVideoStreamFailed, config.resolution || '360'
  3449. );
  3450. }
  3451. }
  3452. };
  3453. },{"../../service/RTC/RTCEvents":77,"../../service/desktopsharing/DesktopSharingEventTypes":81,"../RTC/RTCBrowserType":14,"../RTC/adapter.screenshare":16,"events":39}],18:[function(require,module,exports){
  3454. function supportsLocalStorage() {
  3455. try {
  3456. return 'localStorage' in window && window.localStorage !== null;
  3457. } catch (e) {
  3458. console.log("localstorage is not supported");
  3459. return false;
  3460. }
  3461. }
  3462. function generateUniqueId() {
  3463. function _p8() {
  3464. return (Math.random().toString(16) + "000000000").substr(2, 8);
  3465. }
  3466. return _p8() + _p8() + _p8() + _p8();
  3467. }
  3468. function Settings(conferenceID) {
  3469. this.email = '';
  3470. this.displayName = '';
  3471. this.userId;
  3472. this.language = null;
  3473. this.confSettings = null;
  3474. this.conferenceID = conferenceID;
  3475. if (supportsLocalStorage()) {
  3476. if(!window.localStorage.getItem(conferenceID))
  3477. this.confSettings = {};
  3478. else
  3479. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  3480. if(!this.confSettings.jitsiMeetId) {
  3481. this.confSettings.jitsiMeetId = generateUniqueId();
  3482. console.log("generated id",
  3483. this.confSettings.jitsiMeetId);
  3484. this.save();
  3485. }
  3486. this.userId = this.confSettings.jitsiMeetId || '';
  3487. this.email = this.confSettings.email || '';
  3488. this.displayName = this.confSettings.displayname || '';
  3489. this.language = this.confSettings.language;
  3490. } else {
  3491. console.log("local storage is not supported");
  3492. this.userId = generateUniqueId();
  3493. }
  3494. }
  3495. Settings.prototype.save = function () {
  3496. if(!supportsLocalStorage())
  3497. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  3498. }
  3499. Settings.prototype.setDisplayName = function (newDisplayName) {
  3500. this.displayName = newDisplayName;
  3501. if(this.confSettings != null)
  3502. this.confSettings.displayname = displayName;
  3503. this.save();
  3504. return this.displayName;
  3505. },
  3506. Settings.prototype.setEmail = function (newEmail) {
  3507. this.email = newEmail;
  3508. if(this.confSettings != null)
  3509. this.confSettings.email = newEmail;
  3510. this.save();
  3511. return this.email;
  3512. },
  3513. Settings.prototype.getSettings = function () {
  3514. return {
  3515. email: this.email,
  3516. displayName: this.displayName,
  3517. uid: this.userId,
  3518. language: this.language
  3519. };
  3520. },
  3521. Settings.prototype.setLanguage = function (lang) {
  3522. this.language = lang;
  3523. if(this.confSettings != null)
  3524. this.confSettings.language = lang;
  3525. this.save();
  3526. }
  3527. module.exports = Settings;
  3528. },{}],19:[function(require,module,exports){
  3529. /* global config */
  3530. /**
  3531. * Provides statistics for the local stream.
  3532. */
  3533. var RTCBrowserType = require('../RTC/RTCBrowserType');
  3534. var LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  3535. /**
  3536. * Size of the webaudio analyzer buffer.
  3537. * @type {number}
  3538. */
  3539. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  3540. /**
  3541. * Value of the webaudio analyzer smoothing time parameter.
  3542. * @type {number}
  3543. */
  3544. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  3545. /**
  3546. * Converts time domain data array to audio level.
  3547. * @param samples the time domain data array.
  3548. * @returns {number} the audio level
  3549. */
  3550. function timeDomainDataToAudioLevel(samples) {
  3551. var maxVolume = 0;
  3552. var length = samples.length;
  3553. for (var i = 0; i < length; i++) {
  3554. if (maxVolume < samples[i])
  3555. maxVolume = samples[i];
  3556. }
  3557. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  3558. }
  3559. /**
  3560. * Animates audio level change
  3561. * @param newLevel the new audio level
  3562. * @param lastLevel the last audio level
  3563. * @returns {Number} the audio level to be set
  3564. */
  3565. function animateLevel(newLevel, lastLevel) {
  3566. var value = 0;
  3567. var diff = lastLevel - newLevel;
  3568. if(diff > 0.2) {
  3569. value = lastLevel - 0.2;
  3570. }
  3571. else if(diff < -0.4) {
  3572. value = lastLevel + 0.4;
  3573. }
  3574. else {
  3575. value = newLevel;
  3576. }
  3577. return parseFloat(value.toFixed(3));
  3578. }
  3579. /**
  3580. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  3581. *
  3582. * @param stream the local stream
  3583. * @param interval stats refresh interval given in ms.
  3584. * @constructor
  3585. */
  3586. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  3587. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  3588. this.stream = stream;
  3589. this.intervalId = null;
  3590. this.intervalMilis = interval;
  3591. this.eventEmitter = eventEmitter;
  3592. this.audioLevel = 0;
  3593. this.statisticsService = statisticsService;
  3594. }
  3595. /**
  3596. * Starts the collecting the statistics.
  3597. */
  3598. LocalStatsCollector.prototype.start = function () {
  3599. if (!window.AudioContext ||
  3600. RTCBrowserType.isTemasysPluginUsed())
  3601. return;
  3602. var context = new AudioContext();
  3603. var analyser = context.createAnalyser();
  3604. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  3605. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  3606. var source = context.createMediaStreamSource(this.stream);
  3607. source.connect(analyser);
  3608. var self = this;
  3609. this.intervalId = setInterval(
  3610. function () {
  3611. var array = new Uint8Array(analyser.frequencyBinCount);
  3612. analyser.getByteTimeDomainData(array);
  3613. var audioLevel = timeDomainDataToAudioLevel(array);
  3614. if (audioLevel != self.audioLevel) {
  3615. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  3616. self.eventEmitter.emit(
  3617. "statistics.audioLevel",
  3618. LOCAL_JID,
  3619. self.audioLevel);
  3620. }
  3621. },
  3622. this.intervalMilis
  3623. );
  3624. };
  3625. /**
  3626. * Stops collecting the statistics.
  3627. */
  3628. LocalStatsCollector.prototype.stop = function () {
  3629. if (this.intervalId) {
  3630. clearInterval(this.intervalId);
  3631. this.intervalId = null;
  3632. }
  3633. };
  3634. module.exports = LocalStatsCollector;
  3635. },{"../../service/statistics/constants":82,"../RTC/RTCBrowserType":14}],20:[function(require,module,exports){
  3636. /* global require, ssrc2jid */
  3637. /* jshint -W117 */
  3638. var RTCBrowserType = require("../RTC/RTCBrowserType");
  3639. /* Whether we support the browser we are running into for logging statistics */
  3640. var browserSupported = RTCBrowserType.isChrome() ||
  3641. RTCBrowserType.isOpera();
  3642. var keyMap = {};
  3643. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  3644. "ssrc": "ssrc",
  3645. "packetsReceived": "packetsReceived",
  3646. "packetsLost": "packetsLost",
  3647. "packetsSent": "packetsSent",
  3648. "bytesReceived": "bytesReceived",
  3649. "bytesSent": "bytesSent"
  3650. };
  3651. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  3652. "receiveBandwidth": "googAvailableReceiveBandwidth",
  3653. "sendBandwidth": "googAvailableSendBandwidth",
  3654. "remoteAddress": "googRemoteAddress",
  3655. "transportType": "googTransportType",
  3656. "localAddress": "googLocalAddress",
  3657. "activeConnection": "googActiveConnection",
  3658. "ssrc": "ssrc",
  3659. "packetsReceived": "packetsReceived",
  3660. "packetsSent": "packetsSent",
  3661. "packetsLost": "packetsLost",
  3662. "bytesReceived": "bytesReceived",
  3663. "bytesSent": "bytesSent",
  3664. "googFrameHeightReceived": "googFrameHeightReceived",
  3665. "googFrameWidthReceived": "googFrameWidthReceived",
  3666. "googFrameHeightSent": "googFrameHeightSent",
  3667. "googFrameWidthSent": "googFrameWidthSent",
  3668. "audioInputLevel": "audioInputLevel",
  3669. "audioOutputLevel": "audioOutputLevel"
  3670. };
  3671. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  3672. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  3673. /**
  3674. * Calculates packet lost percent using the number of lost packets and the
  3675. * number of all packet.
  3676. * @param lostPackets the number of lost packets
  3677. * @param totalPackets the number of all packets.
  3678. * @returns {number} packet loss percent
  3679. */
  3680. function calculatePacketLoss(lostPackets, totalPackets) {
  3681. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  3682. return 0;
  3683. return Math.round((lostPackets/totalPackets)*100);
  3684. }
  3685. function getStatValue(item, name) {
  3686. var browserType = RTCBrowserType.getBrowserType();
  3687. if (!keyMap[browserType][name])
  3688. throw "The property isn't supported!";
  3689. var key = keyMap[browserType][name];
  3690. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  3691. item.stat(key) : item[key];
  3692. }
  3693. function formatAudioLevel(audioLevel) {
  3694. return Math.min(Math.max(audioLevel, 0), 1);
  3695. }
  3696. /**
  3697. * Checks whether a certain record should be included in the logged statistics.
  3698. */
  3699. function acceptStat(reportId, reportType, statName) {
  3700. if (reportType == "googCandidatePair" && statName == "googChannelId")
  3701. return false;
  3702. if (reportType == "ssrc") {
  3703. if (statName == "googTrackId" ||
  3704. statName == "transportId" ||
  3705. statName == "ssrc")
  3706. return false;
  3707. }
  3708. return true;
  3709. }
  3710. /**
  3711. * Checks whether a certain record should be included in the logged statistics.
  3712. */
  3713. function acceptReport(id, type) {
  3714. if (id.substring(0, 15) == "googCertificate" ||
  3715. id.substring(0, 9) == "googTrack" ||
  3716. id.substring(0, 20) == "googLibjingleSession")
  3717. return false;
  3718. if (type == "googComponent")
  3719. return false;
  3720. return true;
  3721. }
  3722. /**
  3723. * Peer statistics data holder.
  3724. * @constructor
  3725. */
  3726. function PeerStats()
  3727. {
  3728. this.ssrc2Loss = {};
  3729. this.ssrc2AudioLevel = {};
  3730. this.ssrc2bitrate = {};
  3731. this.ssrc2resolution = {};
  3732. }
  3733. /**
  3734. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  3735. * represented by this instance.
  3736. * @param lossRate new packet loss rate value to be set.
  3737. */
  3738. PeerStats.prototype.setSsrcLoss = function (lossRate)
  3739. {
  3740. this.ssrc2Loss = lossRate;
  3741. };
  3742. /**
  3743. * Sets resolution that belong to the ssrc
  3744. * represented by this instance.
  3745. * @param resolution new resolution value to be set.
  3746. */
  3747. PeerStats.prototype.setSsrcResolution = function (resolution)
  3748. {
  3749. if(resolution === null && this.ssrc2resolution[ssrc])
  3750. {
  3751. delete this.ssrc2resolution[ssrc];
  3752. }
  3753. else if(resolution !== null)
  3754. this.ssrc2resolution[ssrc] = resolution;
  3755. };
  3756. /**
  3757. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  3758. * represented by this instance.
  3759. * @param ssrc audio or video RTP stream SSRC.
  3760. * @param bitrate new bitrate value to be set.
  3761. */
  3762. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  3763. {
  3764. if(this.ssrc2bitrate[ssrc])
  3765. {
  3766. this.ssrc2bitrate[ssrc].download += bitrate.download;
  3767. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  3768. }
  3769. else {
  3770. this.ssrc2bitrate[ssrc] = bitrate;
  3771. }
  3772. };
  3773. /**
  3774. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  3775. * the stream which belongs to the peer represented by this instance.
  3776. * @param ssrc RTP stream SSRC for which current audio level value will be
  3777. * updated.
  3778. * @param audioLevel the new audio level value to be set. Value is truncated to
  3779. * fit the range from 0 to 1.
  3780. */
  3781. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  3782. {
  3783. // Range limit 0 - 1
  3784. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  3785. };
  3786. function ConferenceStats() {
  3787. /**
  3788. * The bandwidth
  3789. * @type {{}}
  3790. */
  3791. this.bandwidth = {};
  3792. /**
  3793. * The bit rate
  3794. * @type {{}}
  3795. */
  3796. this.bitrate = {};
  3797. /**
  3798. * The packet loss rate
  3799. * @type {{}}
  3800. */
  3801. this.packetLoss = null;
  3802. /**
  3803. * Array with the transport information.
  3804. * @type {Array}
  3805. */
  3806. this.transport = [];
  3807. }
  3808. /**
  3809. * <tt>StatsCollector</tt> registers for stats updates of given
  3810. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  3811. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  3812. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  3813. * instance as an event source.
  3814. *
  3815. * @param peerconnection webRTC peer connection object.
  3816. * @param interval stats refresh interval given in ms.
  3817. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  3818. * called on stats update.
  3819. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  3820. * @constructor
  3821. */
  3822. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  3823. {
  3824. this.peerconnection = peerconnection;
  3825. this.baselineAudioLevelsReport = null;
  3826. this.currentAudioLevelsReport = null;
  3827. this.currentStatsReport = null;
  3828. this.baselineStatsReport = null;
  3829. this.audioLevelsIntervalId = null;
  3830. this.eventEmitter = eventEmitter;
  3831. this.config = config || {};
  3832. this.conferenceStats = new ConferenceStats();
  3833. /**
  3834. * Gather PeerConnection stats once every this many milliseconds.
  3835. */
  3836. this.GATHER_INTERVAL = 15000;
  3837. /**
  3838. * Log stats via the focus once every this many milliseconds.
  3839. */
  3840. this.LOG_INTERVAL = 60000;
  3841. /**
  3842. * Gather stats and store them in this.statsToBeLogged.
  3843. */
  3844. this.gatherStatsIntervalId = null;
  3845. /**
  3846. * Send the stats already saved in this.statsToBeLogged to be logged via
  3847. * the focus.
  3848. */
  3849. this.logStatsIntervalId = null;
  3850. /**
  3851. * Stores the statistics which will be send to the focus to be logged.
  3852. */
  3853. this.statsToBeLogged =
  3854. {
  3855. timestamps: [],
  3856. stats: {}
  3857. };
  3858. // Updates stats interval
  3859. this.audioLevelsIntervalMilis = audioLevelsInterval;
  3860. this.statsIntervalId = null;
  3861. this.statsIntervalMilis = statsInterval;
  3862. // Map of ssrcs to PeerStats
  3863. this.ssrc2stats = {};
  3864. }
  3865. module.exports = StatsCollector;
  3866. /**
  3867. * Stops stats updates.
  3868. */
  3869. StatsCollector.prototype.stop = function () {
  3870. if (this.audioLevelsIntervalId) {
  3871. clearInterval(this.audioLevelsIntervalId);
  3872. this.audioLevelsIntervalId = null;
  3873. }
  3874. if (this.statsIntervalId)
  3875. {
  3876. clearInterval(this.statsIntervalId);
  3877. this.statsIntervalId = null;
  3878. }
  3879. if(this.logStatsIntervalId)
  3880. {
  3881. clearInterval(this.logStatsIntervalId);
  3882. this.logStatsIntervalId = null;
  3883. }
  3884. if(this.gatherStatsIntervalId)
  3885. {
  3886. clearInterval(this.gatherStatsIntervalId);
  3887. this.gatherStatsIntervalId = null;
  3888. }
  3889. };
  3890. /**
  3891. * Callback passed to <tt>getStats</tt> method.
  3892. * @param error an error that occurred on <tt>getStats</tt> call.
  3893. */
  3894. StatsCollector.prototype.errorCallback = function (error)
  3895. {
  3896. console.error("Get stats error", error);
  3897. this.stop();
  3898. };
  3899. /**
  3900. * Starts stats updates.
  3901. */
  3902. StatsCollector.prototype.start = function ()
  3903. {
  3904. var self = this;
  3905. this.audioLevelsIntervalId = setInterval(
  3906. function () {
  3907. // Interval updates
  3908. self.peerconnection.getStats(
  3909. function (report) {
  3910. var results = null;
  3911. if (!report || !report.result ||
  3912. typeof report.result != 'function') {
  3913. results = report;
  3914. }
  3915. else {
  3916. results = report.result();
  3917. }
  3918. //console.error("Got interval report", results);
  3919. self.currentAudioLevelsReport = results;
  3920. self.processAudioLevelReport();
  3921. self.baselineAudioLevelsReport =
  3922. self.currentAudioLevelsReport;
  3923. },
  3924. self.errorCallback
  3925. );
  3926. },
  3927. self.audioLevelsIntervalMilis
  3928. );
  3929. // if (!this.config.disableStats && browserSupported) {
  3930. // this.statsIntervalId = setInterval(
  3931. // function () {
  3932. // // Interval updates
  3933. // self.peerconnection.getStats(
  3934. // function (report) {
  3935. // var results = null;
  3936. // if (!report || !report.result ||
  3937. // typeof report.result != 'function') {
  3938. // //firefox
  3939. // results = report;
  3940. // }
  3941. // else {
  3942. // //chrome
  3943. // results = report.result();
  3944. // }
  3945. // //console.error("Got interval report", results);
  3946. // self.currentStatsReport = results;
  3947. // try {
  3948. // self.processStatsReport();
  3949. // }
  3950. // catch (e) {
  3951. // console.error("Unsupported key:" + e, e);
  3952. // }
  3953. //
  3954. // self.baselineStatsReport = self.currentStatsReport;
  3955. // },
  3956. // self.errorCallback
  3957. // );
  3958. // },
  3959. // self.statsIntervalMilis
  3960. // );
  3961. // }
  3962. //
  3963. // if (this.config.logStats && browserSupported) {
  3964. // this.gatherStatsIntervalId = setInterval(
  3965. // function () {
  3966. // self.peerconnection.getStats(
  3967. // function (report) {
  3968. // self.addStatsToBeLogged(report.result());
  3969. // },
  3970. // function () {
  3971. // }
  3972. // );
  3973. // },
  3974. // this.GATHER_INTERVAL
  3975. // );
  3976. //
  3977. // this.logStatsIntervalId = setInterval(
  3978. // function() { self.logStats(); },
  3979. // this.LOG_INTERVAL);
  3980. // }
  3981. };
  3982. /**
  3983. * Converts the stats to the format used for logging, and saves the data in
  3984. * this.statsToBeLogged.
  3985. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  3986. */
  3987. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  3988. var self = this;
  3989. var num_records = this.statsToBeLogged.timestamps.length;
  3990. this.statsToBeLogged.timestamps.push(new Date().getTime());
  3991. reports.map(function (report) {
  3992. if (!acceptReport(report.id, report.type))
  3993. return;
  3994. var stat = self.statsToBeLogged.stats[report.id];
  3995. if (!stat) {
  3996. stat = self.statsToBeLogged.stats[report.id] = {};
  3997. }
  3998. stat.type = report.type;
  3999. report.names().map(function (name) {
  4000. if (!acceptStat(report.id, report.type, name))
  4001. return;
  4002. var values = stat[name];
  4003. if (!values) {
  4004. values = stat[name] = [];
  4005. }
  4006. while (values.length < num_records) {
  4007. values.push(null);
  4008. }
  4009. values.push(report.stat(name));
  4010. });
  4011. });
  4012. };
  4013. //FIXME:
  4014. //StatsCollector.prototype.logStats = function () {
  4015. //
  4016. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  4017. // return;
  4018. // // Reset the stats
  4019. // this.statsToBeLogged.stats = {};
  4020. // this.statsToBeLogged.timestamps = [];
  4021. //};
  4022. /**
  4023. * Stats processing logic.
  4024. */
  4025. StatsCollector.prototype.processStatsReport = function () {
  4026. if (!this.baselineStatsReport) {
  4027. return;
  4028. }
  4029. for (var idx in this.currentStatsReport) {
  4030. var now = this.currentStatsReport[idx];
  4031. try {
  4032. if (getStatValue(now, 'receiveBandwidth') ||
  4033. getStatValue(now, 'sendBandwidth')) {
  4034. this.conferenceStats.bandwidth = {
  4035. "download": Math.round(
  4036. (getStatValue(now, 'receiveBandwidth')) / 1000),
  4037. "upload": Math.round(
  4038. (getStatValue(now, 'sendBandwidth')) / 1000)
  4039. };
  4040. }
  4041. }
  4042. catch(e){/*not supported*/}
  4043. if(now.type == 'googCandidatePair')
  4044. {
  4045. var ip, type, localIP, active;
  4046. try {
  4047. ip = getStatValue(now, 'remoteAddress');
  4048. type = getStatValue(now, "transportType");
  4049. localIP = getStatValue(now, "localAddress");
  4050. active = getStatValue(now, "activeConnection");
  4051. }
  4052. catch(e){/*not supported*/}
  4053. if(!ip || !type || !localIP || active != "true")
  4054. continue;
  4055. var addressSaved = false;
  4056. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  4057. {
  4058. if(this.conferenceStats.transport[i].ip == ip &&
  4059. this.conferenceStats.transport[i].type == type &&
  4060. this.conferenceStats.transport[i].localip == localIP)
  4061. {
  4062. addressSaved = true;
  4063. }
  4064. }
  4065. if(addressSaved)
  4066. continue;
  4067. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  4068. continue;
  4069. }
  4070. if(now.type == "candidatepair")
  4071. {
  4072. if(now.state == "succeeded")
  4073. continue;
  4074. var local = this.currentStatsReport[now.localCandidateId];
  4075. var remote = this.currentStatsReport[now.remoteCandidateId];
  4076. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  4077. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  4078. }
  4079. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  4080. now.type != "inboundrtp") {
  4081. continue;
  4082. }
  4083. var before = this.baselineStatsReport[idx];
  4084. if (!before) {
  4085. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  4086. continue;
  4087. }
  4088. var ssrc = getStatValue(now, 'ssrc');
  4089. if(!ssrc)
  4090. continue;
  4091. var ssrcStats = this.ssrc2stats[ssrc];
  4092. if (!ssrcStats) {
  4093. ssrcStats = new PeerStats();
  4094. this.ssrc2stats[ssrc] = ssrcStats;
  4095. }
  4096. var isDownloadStream = true;
  4097. var key = 'packetsReceived';
  4098. if (!getStatValue(now, key))
  4099. {
  4100. isDownloadStream = false;
  4101. key = 'packetsSent';
  4102. if (!getStatValue(now, key))
  4103. {
  4104. console.warn("No packetsReceived nor packetSent stat found");
  4105. continue;
  4106. }
  4107. }
  4108. var packetsNow = getStatValue(now, key);
  4109. if(!packetsNow || packetsNow < 0)
  4110. packetsNow = 0;
  4111. var packetsBefore = getStatValue(before, key);
  4112. if(!packetsBefore || packetsBefore < 0)
  4113. packetsBefore = 0;
  4114. var packetRate = packetsNow - packetsBefore;
  4115. if(!packetRate || packetRate < 0)
  4116. packetRate = 0;
  4117. var currentLoss = getStatValue(now, 'packetsLost');
  4118. if(!currentLoss || currentLoss < 0)
  4119. currentLoss = 0;
  4120. var previousLoss = getStatValue(before, 'packetsLost');
  4121. if(!previousLoss || previousLoss < 0)
  4122. previousLoss = 0;
  4123. var lossRate = currentLoss - previousLoss;
  4124. if(!lossRate || lossRate < 0)
  4125. lossRate = 0;
  4126. var packetsTotal = (packetRate + lossRate);
  4127. ssrcStats.setSsrcLoss(ssrc,
  4128. {"packetsTotal": packetsTotal,
  4129. "packetsLost": lossRate,
  4130. "isDownloadStream": isDownloadStream});
  4131. var bytesReceived = 0, bytesSent = 0;
  4132. if(getStatValue(now, "bytesReceived"))
  4133. {
  4134. bytesReceived = getStatValue(now, "bytesReceived") -
  4135. getStatValue(before, "bytesReceived");
  4136. }
  4137. if(getStatValue(now, "bytesSent"))
  4138. {
  4139. bytesSent = getStatValue(now, "bytesSent") -
  4140. getStatValue(before, "bytesSent");
  4141. }
  4142. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  4143. if(bytesReceived <= 0 || time <= 0)
  4144. {
  4145. bytesReceived = 0;
  4146. }
  4147. else
  4148. {
  4149. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  4150. }
  4151. if(bytesSent <= 0 || time <= 0)
  4152. {
  4153. bytesSent = 0;
  4154. }
  4155. else
  4156. {
  4157. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  4158. }
  4159. ssrcStats.setSsrcBitrate(ssrc, {
  4160. "download": bytesReceived,
  4161. "upload": bytesSent});
  4162. var resolution = {height: null, width: null};
  4163. try {
  4164. if (getStatValue(now, "googFrameHeightReceived") &&
  4165. getStatValue(now, "googFrameWidthReceived")) {
  4166. resolution.height = getStatValue(now, "googFrameHeightReceived");
  4167. resolution.width = getStatValue(now, "googFrameWidthReceived");
  4168. }
  4169. else if (getStatValue(now, "googFrameHeightSent") &&
  4170. getStatValue(now, "googFrameWidthSent")) {
  4171. resolution.height = getStatValue(now, "googFrameHeightSent");
  4172. resolution.width = getStatValue(now, "googFrameWidthSent");
  4173. }
  4174. }
  4175. catch(e){/*not supported*/}
  4176. if(resolution.height && resolution.width)
  4177. {
  4178. ssrcStats.setSsrcResolution(ssrc, resolution);
  4179. }
  4180. else
  4181. {
  4182. ssrcStats.setSsrcResolution(ssrc, null);
  4183. }
  4184. }
  4185. var self = this;
  4186. // Jid stats
  4187. var totalPackets = {download: 0, upload: 0};
  4188. var lostPackets = {download: 0, upload: 0};
  4189. var bitrateDownload = 0;
  4190. var bitrateUpload = 0;
  4191. var resolutions = {};
  4192. Object.keys(this.ssrc2stats).forEach(
  4193. function (jid)
  4194. {
  4195. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  4196. function (ssrc)
  4197. {
  4198. var type = "upload";
  4199. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  4200. type = "download";
  4201. totalPackets[type] +=
  4202. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  4203. lostPackets[type] +=
  4204. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  4205. }
  4206. );
  4207. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  4208. function (ssrc) {
  4209. bitrateDownload +=
  4210. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  4211. bitrateUpload +=
  4212. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  4213. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  4214. }
  4215. );
  4216. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  4217. }
  4218. );
  4219. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  4220. this.conferenceStats.packetLoss = {
  4221. total:
  4222. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  4223. totalPackets.download + totalPackets.upload),
  4224. download:
  4225. calculatePacketLoss(lostPackets.download, totalPackets.download),
  4226. upload:
  4227. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  4228. };
  4229. this.eventEmitter.emit("statistics.connectionstats",
  4230. {
  4231. "bitrate": this.conferenceStats.bitrate,
  4232. "packetLoss": this.conferenceStats.packetLoss,
  4233. "bandwidth": this.conferenceStats.bandwidth,
  4234. "resolution": resolutions,
  4235. "transport": this.conferenceStats.transport
  4236. });
  4237. this.conferenceStats.transport = [];
  4238. };
  4239. /**
  4240. * Stats processing logic.
  4241. */
  4242. StatsCollector.prototype.processAudioLevelReport = function () {
  4243. if (!this.baselineAudioLevelsReport) {
  4244. return;
  4245. }
  4246. for (var idx in this.currentAudioLevelsReport) {
  4247. var now = this.currentAudioLevelsReport[idx];
  4248. //if we don't have "packetsReceived" this is local stream
  4249. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  4250. continue;
  4251. }
  4252. var before = this.baselineAudioLevelsReport[idx];
  4253. if (!before) {
  4254. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  4255. continue;
  4256. }
  4257. var ssrc = getStatValue(now, 'ssrc');
  4258. if (!ssrc) {
  4259. if((Date.now() - now.timestamp) < 3000)
  4260. console.warn("No ssrc: ");
  4261. continue;
  4262. }
  4263. var ssrcStats = this.ssrc2stats[ssrc];
  4264. if (!ssrcStats) {
  4265. ssrcStats = new PeerStats();
  4266. this.ssrc2stats[ssrc] = ssrcStats;
  4267. }
  4268. // Audio level
  4269. var audioLevel = null;
  4270. try {
  4271. audioLevel = getStatValue(now, 'audioInputLevel');
  4272. if (!audioLevel)
  4273. audioLevel = getStatValue(now, 'audioOutputLevel');
  4274. }
  4275. catch(e) {/*not supported*/
  4276. console.warn("Audio Levels are not available in the statistics.");
  4277. clearInterval(this.audioLevelsIntervalId);
  4278. return;
  4279. }
  4280. if (audioLevel) {
  4281. // TODO: can't find specs about what this value really is,
  4282. // but it seems to vary between 0 and around 32k.
  4283. audioLevel = audioLevel / 32767;
  4284. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  4285. this.eventEmitter.emit("statistics.audioLevel", ssrc, audioLevel);
  4286. }
  4287. }
  4288. };
  4289. },{"../RTC/RTCBrowserType":14}],21:[function(require,module,exports){
  4290. /* global require, APP */
  4291. var LocalStats = require("./LocalStatsCollector.js");
  4292. var RTPStats = require("./RTPStatsCollector.js");
  4293. var EventEmitter = require("events");
  4294. //var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  4295. //var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  4296. //var CallStats = require("./CallStats");
  4297. //var RTCEvents = require("../../service/RTC/RTCEvents");
  4298. //
  4299. //function onDisposeConference(onUnload) {
  4300. // CallStats.sendTerminateEvent();
  4301. // stopRemote();
  4302. // if(onUnload) {
  4303. // stopLocal();
  4304. // eventEmitter.removeAllListeners();
  4305. // }
  4306. //}
  4307. function Statistics() {
  4308. this.localStats = null;
  4309. this.rtpStats = null;
  4310. this.eventEmitter = new EventEmitter();
  4311. }
  4312. Statistics.prototype.startRemoteStats = function (peerconnection) {
  4313. if (this.rtpStats) {
  4314. this.rtpStats.stop();
  4315. }
  4316. this.rtpStats = new RTPStats(peerconnection, 200, 2000, this.eventEmitter);
  4317. this.rtpStats.start();
  4318. }
  4319. Statistics.prototype.startLocalStats = function (stream) {
  4320. if(stream.getType() !== "audio")
  4321. return;
  4322. this.localStats = new LocalStats(stream.getOriginalStream(), 200, this,
  4323. this.eventEmitter);
  4324. this.localStats.start();
  4325. }
  4326. Statistics.prototype.addAudioLevelListener = function(listener)
  4327. {
  4328. this.eventEmitter.on("statistics.audioLevel", listener);
  4329. }
  4330. Statistics.prototype.removeAudioLevelListener = function(listener)
  4331. {
  4332. this.eventEmitter.removeListener("statistics.audioLevel", listener);
  4333. }
  4334. Statistics.prototype.dispose = function () {
  4335. this.stopLocal();
  4336. this.stopRemote();
  4337. if(this.eventEmitter)
  4338. {
  4339. this.eventEmitter.removeAllListeners();
  4340. }
  4341. }
  4342. Statistics.prototype.stopLocal = function () {
  4343. if (this.localStats) {
  4344. this.localStats.stop();
  4345. this.localStats = null;
  4346. }
  4347. }
  4348. Statistics.prototype.stopRemote = function () {
  4349. if (this.rtpStats) {
  4350. this.rtpStats.stop();
  4351. this.eventEmitter.emit("statistics.stop");
  4352. this.rtpStats = null;
  4353. }
  4354. }
  4355. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  4356. //
  4357. //var statistics = {
  4358. // /**
  4359. // * Indicates that this audio level is for local jid.
  4360. // * @type {string}
  4361. // */
  4362. // LOCAL_JID: 'local',
  4363. //
  4364. // addConnectionStatsListener: function(listener)
  4365. // {
  4366. // eventEmitter.on("statistics.connectionstats", listener);
  4367. // },
  4368. //
  4369. // removeConnectionStatsListener: function(listener)
  4370. // {
  4371. // eventEmitter.removeListener("statistics.connectionstats", listener);
  4372. // },
  4373. //
  4374. //
  4375. // addRemoteStatsStopListener: function(listener)
  4376. // {
  4377. // eventEmitter.on("statistics.stop", listener);
  4378. // },
  4379. //
  4380. // removeRemoteStatsStopListener: function(listener)
  4381. // {
  4382. // eventEmitter.removeListener("statistics.stop", listener);
  4383. // },
  4384. //
  4385. //
  4386. // stopRemoteStatistics: function()
  4387. // {
  4388. // stopRemote();
  4389. // },
  4390. //
  4391. //// Already implemented with the constructor
  4392. // start: function () {
  4393. // APP.RTC.addStreamListener(onStreamCreated,
  4394. // StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  4395. // APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  4396. // //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  4397. // APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  4398. // startRemoteStats(event.peerconnection);
  4399. //// CallStats.init(event);
  4400. // });
  4401. //// APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  4402. //// CallStats.init(session);
  4403. //// });
  4404. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  4405. //// APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  4406. //// CallStats.sendMuteEvent(mute, "audio");
  4407. //// });
  4408. //// APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  4409. //// CallStats.sendSetupFailedEvent();
  4410. //// });
  4411. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  4412. //// APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  4413. //// CallStats.sendMuteEvent(mute, "video");
  4414. //// });
  4415. // }
  4416. //};
  4417. module.exports = Statistics;
  4418. },{"../../service/statistics/constants":82,"./LocalStatsCollector.js":19,"./RTPStatsCollector.js":20,"events":39}],22:[function(require,module,exports){
  4419. /**
  4420. * Generates random hex number within the range [min, max]
  4421. * @param max the maximum value for the generated number
  4422. * @param min the minimum value for the generated number
  4423. * @returns random hex number
  4424. */
  4425. function rangeRandomHex(min, max)
  4426. {
  4427. return Math.floor(Math.random() * (max - min) + min).toString(16);
  4428. }
  4429. /**
  4430. * Exported interface.
  4431. */
  4432. var RandomUtil = {
  4433. /**
  4434. * Generates hex number with length 4
  4435. */
  4436. random4digitsHex: function() {
  4437. return rangeRandomHex(4096, 65535);
  4438. },
  4439. /**
  4440. * Generates hex number with length 8
  4441. */
  4442. random8digitsHex: function() {
  4443. return rangeRandomHex(268435456, 4294967295);
  4444. },
  4445. /**
  4446. * Generates hex number with length 12
  4447. */
  4448. random12digitsHex: function() {
  4449. return rangeRandomHex(17592186044416, 281474976710655);
  4450. }
  4451. };
  4452. module.exports = RandomUtil;
  4453. },{}],23:[function(require,module,exports){
  4454. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  4455. var Moderator = require("./moderator");
  4456. var EventEmitter = require("events");
  4457. var parser = {
  4458. packet2JSON: function (packet, nodes) {
  4459. var self = this;
  4460. $(packet).children().each(function (index) {
  4461. var tagName = $(this).prop("tagName");
  4462. var node = {}
  4463. node["tagName"] = tagName;
  4464. node.attributes = {};
  4465. $($(this)[0].attributes).each(function( index, attr ) {
  4466. node.attributes[ attr.name ] = attr.value;
  4467. } );
  4468. var text = Strophe.getText($(this)[0]);
  4469. if(text)
  4470. node.value = text;
  4471. node.children = [];
  4472. nodes.push(node);
  4473. self.packet2JSON($(this), node.children);
  4474. })
  4475. },
  4476. JSON2packet: function (nodes, packet) {
  4477. for(var i = 0; i < nodes.length; i++)
  4478. {
  4479. var node = nodes[i];
  4480. if(!node || node === null){
  4481. continue;
  4482. }
  4483. packet.c(node.tagName, node.attributes);
  4484. if(node.value)
  4485. packet.t(node.value);
  4486. if(node.children)
  4487. this.JSON2packet(node.children, packet);
  4488. packet.up();
  4489. }
  4490. packet.up();
  4491. }
  4492. };
  4493. /**
  4494. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  4495. * @param pres the presence JSON
  4496. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  4497. */
  4498. function filterNodeFromPresenceJSON(pres, nodeName){
  4499. var res = [];
  4500. for(var i = 0; i < pres.length; i++)
  4501. if(pres[i].tagName === nodeName)
  4502. res.push(pres[i]);
  4503. return res;
  4504. }
  4505. function ChatRoom(connection, jid, password, XMPP, options) {
  4506. this.eventEmitter = new EventEmitter();
  4507. this.xmpp = XMPP;
  4508. this.connection = connection;
  4509. this.roomjid = Strophe.getBareJidFromJid(jid);
  4510. this.myroomjid = jid;
  4511. this.password = password;
  4512. console.info("Joined MUC as " + this.myroomjid);
  4513. this.members = {};
  4514. this.presMap = {};
  4515. this.presHandlers = {};
  4516. this.joined = false;
  4517. this.role = null;
  4518. this.focusMucJid = null;
  4519. this.bridgeIsDown = false;
  4520. this.options = options || {};
  4521. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter);
  4522. this.initPresenceMap();
  4523. this.session = null;
  4524. var self = this;
  4525. this.lastPresences = {};
  4526. }
  4527. ChatRoom.prototype.initPresenceMap = function () {
  4528. this.presMap['to'] = this.myroomjid;
  4529. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  4530. this.presMap["nodes"] = [];
  4531. this.presMap["nodes"].push( {
  4532. "tagName": "user-agent",
  4533. "value": navigator.userAgent,
  4534. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  4535. });
  4536. };
  4537. ChatRoom.prototype.join = function (password) {
  4538. if(password)
  4539. this.password = password;
  4540. this.moderator.allocateConferenceFocus(function()
  4541. {
  4542. this.sendPresence();
  4543. }.bind(this));
  4544. }
  4545. ChatRoom.prototype.sendPresence = function () {
  4546. if (!this.presMap['to']) {
  4547. // Too early to send presence - not initialized
  4548. return;
  4549. }
  4550. var pres = $pres({to: this.presMap['to'] });
  4551. pres.c('x', {xmlns: this.presMap['xns']});
  4552. if (this.password) {
  4553. pres.c('password').t(this.password).up();
  4554. }
  4555. pres.up();
  4556. // Send XEP-0115 'c' stanza that contains our capabilities info
  4557. if (this.connection.caps) {
  4558. this.connection.caps.node = this.xmpp.options.clientNode;
  4559. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  4560. }
  4561. parser.JSON2packet(this.presMap.nodes, pres);
  4562. this.connection.send(pres);
  4563. };
  4564. ChatRoom.prototype.doLeave = function () {
  4565. console.log("do leave", this.myroomjid);
  4566. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  4567. this.presMap.length = 0;
  4568. this.connection.send(pres);
  4569. };
  4570. ChatRoom.prototype.createNonAnonymousRoom = function () {
  4571. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  4572. var getForm = $iq({type: 'get', to: this.roomjid})
  4573. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  4574. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  4575. var self = this;
  4576. this.connection.sendIQ(getForm, function (form) {
  4577. if (!$(form).find(
  4578. '>query>x[xmlns="jabber:x:data"]' +
  4579. '>field[var="muc#roomconfig_whois"]').length) {
  4580. console.error('non-anonymous rooms not supported');
  4581. return;
  4582. }
  4583. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  4584. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  4585. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  4586. formSubmit.c('field', {'var': 'FORM_TYPE'})
  4587. .c('value')
  4588. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  4589. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  4590. .c('value').t('anyone').up().up();
  4591. self.connection.sendIQ(formSubmit);
  4592. }, function (error) {
  4593. console.error("Error getting room configuration form");
  4594. });
  4595. };
  4596. ChatRoom.prototype.onPresence = function (pres) {
  4597. var from = pres.getAttribute('from');
  4598. // Parse roles.
  4599. var member = {};
  4600. member.show = $(pres).find('>show').text();
  4601. member.status = $(pres).find('>status').text();
  4602. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  4603. member.affiliation = tmp.attr('affiliation');
  4604. member.role = tmp.attr('role');
  4605. // Focus recognition
  4606. member.jid = tmp.attr('jid');
  4607. member.isFocus = false;
  4608. if (member.jid
  4609. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") == 0) {
  4610. member.isFocus = true;
  4611. }
  4612. $(pres).find(">x").remove();
  4613. var nodes = [];
  4614. parser.packet2JSON(pres, nodes);
  4615. this.lastPresences[from] = nodes;
  4616. for(var i = 0; i < nodes.length; i++)
  4617. {
  4618. var node = nodes[i];
  4619. switch(node.tagName)
  4620. {
  4621. case "nick":
  4622. member.nick = node.value;
  4623. if(!member.isFocus) {
  4624. var displayName = !this.xmpp.options.displayJids
  4625. ? member.nick : Strophe.getResourceFromJid(from);
  4626. if (displayName && displayName.length > 0) {
  4627. this.eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  4628. }
  4629. console.info("Display name: " + displayName, pres);
  4630. }
  4631. break;
  4632. case "userId":
  4633. member.id = node.value;
  4634. break;
  4635. case "email":
  4636. member.email = node.value;
  4637. break;
  4638. case "bridgeIsDown":
  4639. if(!this.bridgeIsDown) {
  4640. this.bridgeIsDown = true;
  4641. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  4642. }
  4643. break;
  4644. default :
  4645. this.processNode(node, from);
  4646. }
  4647. }
  4648. if (from == this.myroomjid) {
  4649. if (member.affiliation == 'owner')
  4650. if (this.role !== member.role) {
  4651. this.role = member.role;
  4652. this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  4653. member, this.isModerator());
  4654. }
  4655. if (!this.joined) {
  4656. this.joined = true;
  4657. this.eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  4658. }
  4659. } else if (this.members[from] === undefined) {
  4660. // new participant
  4661. this.members[from] = member;
  4662. console.log('entered', from, member);
  4663. if (member.isFocus) {
  4664. this.focusMucJid = from;
  4665. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  4666. }
  4667. else {
  4668. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, member.id || member.email, member.nick);
  4669. }
  4670. } else {
  4671. // Presence update for existing participant
  4672. // Watch role change:
  4673. if (this.members[from].role != member.role) {
  4674. this.members[from].role = member.role;
  4675. this.eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  4676. member.role, member.nick);
  4677. }
  4678. }
  4679. if(!member.isFocus)
  4680. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id || member.email);
  4681. // Trigger status message update
  4682. if (member.status) {
  4683. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  4684. }
  4685. };
  4686. ChatRoom.prototype.processNode = function (node, from) {
  4687. if(this.presHandlers[node.tagName])
  4688. this.presHandlers[node.tagName](node, from);
  4689. };
  4690. ChatRoom.prototype.sendMessage = function (body, nickname) {
  4691. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  4692. msg.c('body', body).up();
  4693. if (nickname) {
  4694. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  4695. }
  4696. this.connection.send(msg);
  4697. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  4698. };
  4699. ChatRoom.prototype.setSubject = function (subject) {
  4700. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  4701. msg.c('subject', subject);
  4702. this.connection.send(msg);
  4703. console.log("topic changed to " + subject);
  4704. };
  4705. ChatRoom.prototype.onParticipantLeft = function (jid) {
  4706. delete this.lastPresences[jid];
  4707. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  4708. this.moderator.onMucMemberLeft(jid);
  4709. };
  4710. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  4711. // room destroyed ?
  4712. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  4713. '>destroy').length) {
  4714. var reason;
  4715. var reasonSelect = $(pres).find(
  4716. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  4717. '>destroy>reason');
  4718. if (reasonSelect.length) {
  4719. reason = reasonSelect.text();
  4720. }
  4721. this.xmpp.disposeConference(false);
  4722. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  4723. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(jid)];
  4724. return true;
  4725. }
  4726. // Status code 110 indicates that this notification is "self-presence".
  4727. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  4728. delete this.members[from];
  4729. this.onParticipantLeft(from);
  4730. }
  4731. // If the status code is 110 this means we're leaving and we would like
  4732. // to remove everyone else from our view, so we trigger the event.
  4733. else if (Object.keys(this.members).length > 1) {
  4734. for (var i in this.members) {
  4735. var member = this.members[i];
  4736. delete this.members[i];
  4737. this.onParticipantLeft(member);
  4738. }
  4739. }
  4740. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  4741. if (this.myroomjid === from) {
  4742. this.xmpp.disposeConference(false);
  4743. this.eventEmitter.emit(XMPPEvents.KICKED);
  4744. }
  4745. }
  4746. };
  4747. ChatRoom.prototype.onMessage = function (msg, from) {
  4748. var nick =
  4749. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  4750. .text() ||
  4751. Strophe.getResourceFromJid(from);
  4752. var txt = $(msg).find('>body').text();
  4753. var type = msg.getAttribute("type");
  4754. if (type == "error") {
  4755. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  4756. $(msg).find('>text').text(), txt);
  4757. return true;
  4758. }
  4759. var subject = $(msg).find('>subject');
  4760. if (subject.length) {
  4761. var subjectText = subject.text();
  4762. if (subjectText || subjectText == "") {
  4763. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  4764. console.log("Subject is changed to " + subjectText);
  4765. }
  4766. }
  4767. // xep-0203 delay
  4768. var stamp = $(msg).find('>delay').attr('stamp');
  4769. if (!stamp) {
  4770. // or xep-0091 delay, UTC timestamp
  4771. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  4772. if (stamp) {
  4773. // the format is CCYYMMDDThh:mm:ss
  4774. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  4775. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  4776. }
  4777. }
  4778. if (txt) {
  4779. console.log('chat', nick, txt);
  4780. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  4781. from, nick, txt, this.myroomjid, stamp);
  4782. }
  4783. }
  4784. ChatRoom.prototype.onPresenceError = function (pres, from) {
  4785. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  4786. console.log('on password required', from);
  4787. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  4788. } else if ($(pres).find(
  4789. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  4790. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  4791. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  4792. // enter the room by replying with 'not-authorized'. This would
  4793. // result in reconnection from authorized domain.
  4794. // We're either missing Jicofo/Prosody config for anonymous
  4795. // domains or something is wrong.
  4796. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  4797. } else {
  4798. console.warn('onPresError ', pres);
  4799. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  4800. }
  4801. } else {
  4802. console.warn('onPresError ', pres);
  4803. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  4804. }
  4805. };
  4806. ChatRoom.prototype.kick = function (jid) {
  4807. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  4808. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  4809. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  4810. .c('reason').t('You have been kicked.').up().up().up();
  4811. this.connection.sendIQ(
  4812. kickIQ,
  4813. function (result) {
  4814. console.log('Kick participant with jid: ', jid, result);
  4815. },
  4816. function (error) {
  4817. console.log('Kick participant error: ', error);
  4818. });
  4819. };
  4820. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  4821. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  4822. var ob = this;
  4823. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  4824. function (res) {
  4825. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  4826. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  4827. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  4828. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  4829. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  4830. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  4831. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  4832. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  4833. ob.connection.sendIQ(formsubmit,
  4834. onSuccess,
  4835. onError);
  4836. } else {
  4837. onNotSupported();
  4838. }
  4839. }, onError);
  4840. };
  4841. ChatRoom.prototype.addToPresence = function (key, values) {
  4842. values.tagName = key;
  4843. this.presMap["nodes"].push(values);
  4844. };
  4845. ChatRoom.prototype.removeFromPresence = function (key) {
  4846. for(var i = 0; i < this.presMap.nodes.length; i++)
  4847. {
  4848. if(key === this.presMap.nodes[i].tagName)
  4849. this.presMap.nodes.splice(i, 1);
  4850. }
  4851. };
  4852. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  4853. this.presHandlers[name] = handler;
  4854. }
  4855. ChatRoom.prototype.removePresenceListener = function (name) {
  4856. delete this.presHandlers[name];
  4857. }
  4858. ChatRoom.prototype.isModerator = function (jid) {
  4859. return this.role === 'moderator';
  4860. };
  4861. ChatRoom.prototype.getMemberRole = function (peerJid) {
  4862. if (this.members[peerJid]) {
  4863. return this.members[peerJid].role;
  4864. }
  4865. return null;
  4866. };
  4867. ChatRoom.prototype.setJingleSession = function(session){
  4868. this.session = session;
  4869. this.session.room = this;
  4870. };
  4871. ChatRoom.prototype.removeStream = function (stream) {
  4872. if(!this.session)
  4873. return;
  4874. this.session.peerconnection.removeStream(stream)
  4875. }
  4876. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  4877. if(this.session) {
  4878. // FIXME: will block switchInProgress on true value in case of exception
  4879. this.session.switchStreams(stream, oldStream, callback, isAudio);
  4880. } else {
  4881. // We are done immediately
  4882. console.warn("No conference handler or conference not started yet");
  4883. callback();
  4884. }
  4885. };
  4886. ChatRoom.prototype.addStream = function (stream, callback) {
  4887. if(this.session) {
  4888. // FIXME: will block switchInProgress on true value in case of exception
  4889. this.session.addStream(stream, callback);
  4890. } else {
  4891. // We are done immediately
  4892. console.warn("No conference handler or conference not started yet");
  4893. callback();
  4894. }
  4895. }
  4896. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  4897. var self = this;
  4898. var localCallback = function (mute) {
  4899. self.sendVideoInfoPresence(mute);
  4900. if(callback)
  4901. callback(mute)
  4902. };
  4903. if(this.session)
  4904. {
  4905. this.session.setVideoMute(
  4906. mute, localCallback, options);
  4907. }
  4908. else {
  4909. localCallback(mute);
  4910. }
  4911. };
  4912. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  4913. //This will be for remote streams only
  4914. // if (this.forceMuted && !mute) {
  4915. // console.info("Asking focus for unmute");
  4916. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  4917. // // FIXME: wait for result before resetting muted status
  4918. // this.forceMuted = false;
  4919. // }
  4920. return this.sendAudioInfoPresence(mute, callback);
  4921. };
  4922. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  4923. this.removeFromPresence("audiomuted");
  4924. this.addToPresence("audiomuted",
  4925. {attributes:
  4926. {"audions": "http://jitsi.org/jitmeet/audio"},
  4927. value: mute.toString()});
  4928. }
  4929. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  4930. this.addAudioInfoToPresence(mute);
  4931. if(this.connection) {
  4932. this.sendPresence();
  4933. }
  4934. if(callback)
  4935. callback();
  4936. };
  4937. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  4938. this.removeFromPresence("videomuted");
  4939. this.addToPresence("videomuted",
  4940. {attributes:
  4941. {"videons": "http://jitsi.org/jitmeet/video"},
  4942. value: mute.toString()});
  4943. }
  4944. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  4945. this.addVideoInfoToPresence(mute);
  4946. if(!this.connection)
  4947. return;
  4948. this.sendPresence();
  4949. };
  4950. ChatRoom.prototype.addListener = function(type, listener) {
  4951. this.eventEmitter.on(type, listener);
  4952. };
  4953. ChatRoom.prototype.removeListener = function (type, listener) {
  4954. this.eventEmitter.removeListener(type, listener);
  4955. };
  4956. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  4957. if(this.lastPresences[data.peerjid])
  4958. {
  4959. var pres = this.lastPresences[data.peerjid];
  4960. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  4961. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  4962. data.videomuted = ((videomuted.length > 0
  4963. && videomuted[0]
  4964. && videomuted[0]["value"] === "true")? true : false);
  4965. data.audiomuted = ((audiomuted.length > 0
  4966. && audiomuted[0]
  4967. && audiomuted[0]["value"] === "true")? true : false);
  4968. }
  4969. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  4970. }
  4971. ChatRoom.prototype.addLocalStreams = function (localStreams) {
  4972. this.session.addLocalStreams(localStreams);
  4973. }
  4974. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  4975. if (!this.session)
  4976. return null;
  4977. return this.session.getSsrcOwner(ssrc);
  4978. };
  4979. module.exports = ChatRoom;
  4980. },{"../../service/xmpp/XMPPEvents":83,"./moderator":31,"events":39}],24:[function(require,module,exports){
  4981. /*
  4982. * JingleSession provides an API to manage a single Jingle session. We will
  4983. * have different implementations depending on the underlying interface used
  4984. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  4985. */
  4986. function JingleSession(me, sid, connection, service, eventEmitter) {
  4987. /**
  4988. * Our JID.
  4989. */
  4990. this.me = me;
  4991. /**
  4992. * The Jingle session identifier.
  4993. */
  4994. this.sid = sid;
  4995. /**
  4996. * The XMPP connection.
  4997. */
  4998. this.connection = connection;
  4999. /**
  5000. * The XMPP service.
  5001. */
  5002. this.service = service;
  5003. /**
  5004. * The event emitter.
  5005. */
  5006. this.eventEmitter = eventEmitter;
  5007. /**
  5008. * Whether to use dripping or not. Dripping is sending trickle candidates
  5009. * not one-by-one.
  5010. * Note: currently we do not support 'false'.
  5011. */
  5012. this.usedrip = true;
  5013. /**
  5014. * When dripping is used, stores ICE candidates which are to be sent.
  5015. */
  5016. this.drip_container = [];
  5017. // Media constraints. Is this WebRTC only?
  5018. this.media_constraints = null;
  5019. // ICE servers config (RTCConfiguration?).
  5020. this.ice_config = {};
  5021. // The chat room instance associated with the session.
  5022. this.room = null;
  5023. }
  5024. /**
  5025. * Prepares this object to initiate a session.
  5026. * @param peerjid the JID of the remote peer.
  5027. * @param isInitiator whether we will be the Jingle initiator.
  5028. * @param media_constraints
  5029. * @param ice_config
  5030. */
  5031. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  5032. media_constraints, ice_config) {
  5033. this.media_constraints = media_constraints;
  5034. this.ice_config = ice_config;
  5035. if (this.state !== null) {
  5036. console.error('attempt to initiate on session ' + this.sid +
  5037. 'in state ' + this.state);
  5038. return;
  5039. }
  5040. this.state = 'pending';
  5041. this.initiator = isInitiator ? this.me : peerjid;
  5042. this.responder = !isInitiator ? this.me : peerjid;
  5043. this.peerjid = peerjid;
  5044. this.doInitialize();
  5045. };
  5046. /**
  5047. * Finishes initialization.
  5048. */
  5049. JingleSession.prototype.doInitialize = function() {};
  5050. /**
  5051. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  5052. * Note: currently only used on transport-info
  5053. */
  5054. JingleSession.prototype.addIceCandidates = function(contents) {};
  5055. /**
  5056. * Handles an 'add-source' event.
  5057. *
  5058. * @param contents an array of Jingle 'content' elements.
  5059. */
  5060. JingleSession.prototype.addSources = function(contents) {};
  5061. /**
  5062. * Handles a 'remove-source' event.
  5063. *
  5064. * @param contents an array of Jingle 'content' elements.
  5065. */
  5066. JingleSession.prototype.removeSources = function(contents) {};
  5067. /**
  5068. * Terminates this Jingle session (stops sending media and closes the streams?)
  5069. */
  5070. JingleSession.prototype.terminate = function() {};
  5071. /**
  5072. * Sends a Jingle session-terminate message to the peer and terminates the
  5073. * session.
  5074. * @param reason
  5075. * @param text
  5076. */
  5077. JingleSession.prototype.sendTerminate = function(reason, text) {};
  5078. /**
  5079. * Handles an offer from the remote peer (prepares to accept a session).
  5080. * @param jingle the 'jingle' XML element.
  5081. */
  5082. JingleSession.prototype.setOffer = function(jingle) {};
  5083. /**
  5084. * Handles an answer from the remote peer (prepares to accept a session).
  5085. * @param jingle the 'jingle' XML element.
  5086. */
  5087. JingleSession.prototype.setAnswer = function(jingle) {};
  5088. module.exports = JingleSession;
  5089. },{}],25:[function(require,module,exports){
  5090. /* jshint -W117 */
  5091. var JingleSession = require("./JingleSession");
  5092. var TraceablePeerConnection = require("./TraceablePeerConnection");
  5093. var SDPDiffer = require("./SDPDiffer");
  5094. var SDPUtil = require("./SDPUtil");
  5095. var SDP = require("./SDP");
  5096. var async = require("async");
  5097. var transform = require("sdp-transform");
  5098. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5099. var RTCBrowserType = require("../RTC/RTCBrowserType");
  5100. var SSRCReplacement = require("./LocalSSRCReplacement");
  5101. var RTC = require("../RTC/RTC");
  5102. // Jingle stuff
  5103. function JingleSessionPC(me, sid, connection, service) {
  5104. JingleSession.call(this, me, sid, connection, service);
  5105. this.initiator = null;
  5106. this.responder = null;
  5107. this.peerjid = null;
  5108. this.state = null;
  5109. this.localSDP = null;
  5110. this.remoteSDP = null;
  5111. this.relayedStreams = [];
  5112. this.usetrickle = true;
  5113. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  5114. this.hadstuncandidate = false;
  5115. this.hadturncandidate = false;
  5116. this.lasticecandidate = false;
  5117. this.statsinterval = null;
  5118. this.reason = null;
  5119. this.addssrc = [];
  5120. this.removessrc = [];
  5121. this.pendingop = null;
  5122. this.switchstreams = false;
  5123. this.addingStreams = false;
  5124. this.wait = true;
  5125. this.localStreamsSSRC = null;
  5126. this.ssrcOwners = {};
  5127. this.ssrcVideoTypes = {};
  5128. /**
  5129. * The indicator which determines whether the (local) video has been muted
  5130. * in response to a user command in contrast to an automatic decision made
  5131. * by the application logic.
  5132. */
  5133. this.videoMuteByUser = false;
  5134. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  5135. // We start with the queue paused. We resume it when the signaling state is
  5136. // stable and the ice connection state is connected.
  5137. this.modifySourcesQueue.pause();
  5138. }
  5139. JingleSessionPC.prototype = JingleSession.prototype;
  5140. JingleSessionPC.prototype.constructor = JingleSessionPC;
  5141. JingleSessionPC.prototype.setOffer = function(offer) {
  5142. this.setRemoteDescription(offer, 'offer');
  5143. };
  5144. JingleSessionPC.prototype.setAnswer = function(answer) {
  5145. this.setRemoteDescription(answer, 'answer');
  5146. };
  5147. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  5148. var signalingState = this.peerconnection.signalingState;
  5149. var iceConnectionState = this.peerconnection.iceConnectionState;
  5150. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  5151. this.modifySourcesQueue.resume();
  5152. } else {
  5153. this.modifySourcesQueue.pause();
  5154. }
  5155. };
  5156. JingleSessionPC.prototype.doInitialize = function () {
  5157. var self = this;
  5158. this.hadstuncandidate = false;
  5159. this.hadturncandidate = false;
  5160. this.lasticecandidate = false;
  5161. this.isreconnect = false;
  5162. this.peerconnection = new TraceablePeerConnection(
  5163. this.connection.jingle.ice_config,
  5164. RTC.getPCConstraints(),
  5165. this);
  5166. this.peerconnection.onicecandidate = function (event) {
  5167. self.sendIceCandidate(event.candidate);
  5168. };
  5169. this.peerconnection.onaddstream = function (event) {
  5170. if (event.stream.id !== 'default') {
  5171. console.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  5172. self.remoteStreamAdded(event);
  5173. } else {
  5174. // This is a recvonly stream. Clients that implement Unified Plan,
  5175. // such as Firefox use recvonly "streams/channels/tracks" for
  5176. // receiving remote stream/tracks, as opposed to Plan B where there
  5177. // are only 3 channels: audio, video and data.
  5178. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  5179. }
  5180. };
  5181. this.peerconnection.onremovestream = function (event) {
  5182. // Remove the stream from remoteStreams
  5183. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  5184. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  5185. };
  5186. this.peerconnection.onsignalingstatechange = function (event) {
  5187. if (!(self && self.peerconnection)) return;
  5188. self.updateModifySourcesQueue();
  5189. };
  5190. /**
  5191. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  5192. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  5193. * RTCPeerConnection.iceConnectionState changes.
  5194. *
  5195. * @param event the event containing information about the change
  5196. */
  5197. this.peerconnection.oniceconnectionstatechange = function (event) {
  5198. if (!(self && self.peerconnection)) return;
  5199. self.updateModifySourcesQueue();
  5200. switch (self.peerconnection.iceConnectionState) {
  5201. case 'connected':
  5202. // Informs interested parties that the connection has been restored.
  5203. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  5204. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  5205. self.isreconnect = false;
  5206. break;
  5207. case 'disconnected':
  5208. self.isreconnect = true;
  5209. // Informs interested parties that the connection has been interrupted.
  5210. if (self.peerconnection.signalingState === 'stable')
  5211. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  5212. break;
  5213. case 'failed':
  5214. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5215. break;
  5216. }
  5217. onIceConnectionStateChange(self.sid, self);
  5218. };
  5219. this.peerconnection.onnegotiationneeded = function (event) {
  5220. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  5221. };
  5222. this.relayedStreams.forEach(function(stream) {
  5223. self.peerconnection.addStream(stream);
  5224. });
  5225. };
  5226. JingleSessionPC.prototype.addLocalStreams = function (localStreams) {
  5227. var self = this;
  5228. // add any local and relayed stream
  5229. localStreams.forEach(function(stream) {
  5230. if(!stream.isStarted())
  5231. return;
  5232. self.peerconnection.addStream(stream.getOriginalStream());
  5233. });
  5234. }
  5235. function onIceConnectionStateChange(sid, session) {
  5236. switch (session.peerconnection.iceConnectionState) {
  5237. case 'checking':
  5238. session.timeChecking = (new Date()).getTime();
  5239. session.firstconnect = true;
  5240. break;
  5241. case 'completed': // on caller side
  5242. case 'connected':
  5243. if (session.firstconnect) {
  5244. session.firstconnect = false;
  5245. var metadata = {};
  5246. metadata.setupTime
  5247. = (new Date()).getTime() - session.timeChecking;
  5248. session.peerconnection.getStats(function (res) {
  5249. if(res && res.result) {
  5250. res.result().forEach(function (report) {
  5251. if (report.type == 'googCandidatePair' &&
  5252. report.stat('googActiveConnection') == 'true') {
  5253. metadata.localCandidateType
  5254. = report.stat('googLocalCandidateType');
  5255. metadata.remoteCandidateType
  5256. = report.stat('googRemoteCandidateType');
  5257. // log pair as well so we can get nice pie
  5258. // charts
  5259. metadata.candidatePair
  5260. = report.stat('googLocalCandidateType') +
  5261. ';' +
  5262. report.stat('googRemoteCandidateType');
  5263. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  5264. {
  5265. metadata.ipv6 = true;
  5266. }
  5267. }
  5268. });
  5269. }
  5270. });
  5271. }
  5272. break;
  5273. }
  5274. }
  5275. JingleSessionPC.prototype.accept = function () {
  5276. this.state = 'active';
  5277. var pranswer = this.peerconnection.localDescription;
  5278. if (!pranswer || pranswer.type != 'pranswer') {
  5279. return;
  5280. }
  5281. console.log('going from pranswer to answer');
  5282. if (this.usetrickle) {
  5283. // remove candidates already sent from session-accept
  5284. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  5285. for (var i = 0; i < lines.length; i++) {
  5286. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  5287. }
  5288. }
  5289. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  5290. // FIXME: change any inactive to sendrecv or whatever they were originally
  5291. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  5292. }
  5293. var prsdp = new SDP(pranswer.sdp);
  5294. var accept = $iq({to: this.peerjid,
  5295. type: 'set'})
  5296. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5297. action: 'session-accept',
  5298. initiator: this.initiator,
  5299. responder: this.responder,
  5300. sid: this.sid });
  5301. // FIXME why do we generate session-accept in 3 different places ?
  5302. prsdp.toJingle(
  5303. accept,
  5304. this.initiator == this.me ? 'initiator' : 'responder',
  5305. this.localStreamsSSRC);
  5306. var sdp = this.peerconnection.localDescription.sdp;
  5307. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  5308. // FIXME: change any inactive to sendrecv or whatever they were originally
  5309. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  5310. }
  5311. var self = this;
  5312. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  5313. function () {
  5314. //console.log('setLocalDescription success');
  5315. self.setLocalDescription();
  5316. SSRCReplacement.processSessionInit(accept);
  5317. self.connection.sendIQ(accept,
  5318. function () {
  5319. var ack = {};
  5320. ack.source = 'answer';
  5321. $(document).trigger('ack.jingle', [self.sid, ack]);
  5322. },
  5323. function (stanza) {
  5324. var error = ($(stanza).find('error').length) ? {
  5325. code: $(stanza).find('error').attr('code'),
  5326. reason: $(stanza).find('error :first')[0].tagName
  5327. }:{};
  5328. error.source = 'answer';
  5329. JingleSessionPC.onJingleError(self.sid, error);
  5330. },
  5331. 10000);
  5332. },
  5333. function (e) {
  5334. console.error('setLocalDescription failed', e);
  5335. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5336. }
  5337. );
  5338. };
  5339. JingleSessionPC.prototype.terminate = function (reason) {
  5340. this.state = 'ended';
  5341. this.reason = reason;
  5342. this.peerconnection.close();
  5343. if (this.statsinterval !== null) {
  5344. window.clearInterval(this.statsinterval);
  5345. this.statsinterval = null;
  5346. }
  5347. };
  5348. JingleSessionPC.prototype.active = function () {
  5349. return this.state == 'active';
  5350. };
  5351. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  5352. var self = this;
  5353. if (candidate && !this.lasticecandidate) {
  5354. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  5355. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  5356. if (!(ice && jcand)) {
  5357. console.error('failed to get ice && jcand');
  5358. return;
  5359. }
  5360. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  5361. if (jcand.type === 'srflx') {
  5362. this.hadstuncandidate = true;
  5363. } else if (jcand.type === 'relay') {
  5364. this.hadturncandidate = true;
  5365. }
  5366. if (this.usetrickle) {
  5367. if (this.usedrip) {
  5368. if (this.drip_container.length === 0) {
  5369. // start 20ms callout
  5370. window.setTimeout(function () {
  5371. if (self.drip_container.length === 0) return;
  5372. self.sendIceCandidates(self.drip_container);
  5373. self.drip_container = [];
  5374. }, 20);
  5375. }
  5376. this.drip_container.push(candidate);
  5377. return;
  5378. } else {
  5379. self.sendIceCandidate([candidate]);
  5380. }
  5381. }
  5382. } else {
  5383. //console.log('sendIceCandidate: last candidate.');
  5384. if (!this.usetrickle) {
  5385. //console.log('should send full offer now...');
  5386. //FIXME why do we generate session-accept in 3 different places ?
  5387. var init = $iq({to: this.peerjid,
  5388. type: 'set'})
  5389. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5390. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  5391. initiator: this.initiator,
  5392. sid: this.sid});
  5393. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  5394. var sendJingle = function (ssrc) {
  5395. if(!ssrc)
  5396. ssrc = {};
  5397. self.localSDP.toJingle(
  5398. init,
  5399. self.initiator == self.me ? 'initiator' : 'responder',
  5400. ssrc);
  5401. SSRCReplacement.processSessionInit(init);
  5402. self.connection.sendIQ(init,
  5403. function () {
  5404. //console.log('session initiate ack');
  5405. var ack = {};
  5406. ack.source = 'offer';
  5407. $(document).trigger('ack.jingle', [self.sid, ack]);
  5408. },
  5409. function (stanza) {
  5410. self.state = 'error';
  5411. self.peerconnection.close();
  5412. var error = ($(stanza).find('error').length) ? {
  5413. code: $(stanza).find('error').attr('code'),
  5414. reason: $(stanza).find('error :first')[0].tagName,
  5415. }:{};
  5416. error.source = 'offer';
  5417. JingleSessionPC.onJingleError(self.sid, error);
  5418. },
  5419. 10000);
  5420. };
  5421. sendJingle();
  5422. }
  5423. this.lasticecandidate = true;
  5424. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  5425. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  5426. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  5427. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  5428. }
  5429. }
  5430. };
  5431. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  5432. console.log('sendIceCandidates', candidates);
  5433. var cand = $iq({to: this.peerjid, type: 'set'})
  5434. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5435. action: 'transport-info',
  5436. initiator: this.initiator,
  5437. sid: this.sid});
  5438. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  5439. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  5440. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  5441. if (cands.length > 0) {
  5442. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  5443. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  5444. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  5445. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  5446. }).c('transport', ice);
  5447. for (var i = 0; i < cands.length; i++) {
  5448. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  5449. }
  5450. // add fingerprint
  5451. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  5452. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  5453. tmp.required = true;
  5454. cand.c(
  5455. 'fingerprint',
  5456. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  5457. .t(tmp.fingerprint);
  5458. delete tmp.fingerprint;
  5459. cand.attrs(tmp);
  5460. cand.up();
  5461. }
  5462. cand.up(); // transport
  5463. cand.up(); // content
  5464. }
  5465. }
  5466. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  5467. //console.log('was this the last candidate', this.lasticecandidate);
  5468. this.connection.sendIQ(cand,
  5469. function () {
  5470. var ack = {};
  5471. ack.source = 'transportinfo';
  5472. $(document).trigger('ack.jingle', [this.sid, ack]);
  5473. },
  5474. function (stanza) {
  5475. var error = ($(stanza).find('error').length) ? {
  5476. code: $(stanza).find('error').attr('code'),
  5477. reason: $(stanza).find('error :first')[0].tagName,
  5478. }:{};
  5479. error.source = 'transportinfo';
  5480. JingleSessionPC.onJingleError(this.sid, error);
  5481. },
  5482. 10000);
  5483. };
  5484. JingleSessionPC.prototype.sendOffer = function () {
  5485. //console.log('sendOffer...');
  5486. var self = this;
  5487. this.peerconnection.createOffer(function (sdp) {
  5488. self.createdOffer(sdp);
  5489. },
  5490. function (e) {
  5491. console.error('createOffer failed', e);
  5492. },
  5493. this.media_constraints
  5494. );
  5495. };
  5496. // FIXME createdOffer is never used in jitsi-meet
  5497. JingleSessionPC.prototype.createdOffer = function (sdp) {
  5498. //console.log('createdOffer', sdp);
  5499. var self = this;
  5500. this.localSDP = new SDP(sdp.sdp);
  5501. //this.localSDP.mangle();
  5502. var sendJingle = function () {
  5503. var init = $iq({to: this.peerjid,
  5504. type: 'set'})
  5505. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5506. action: 'session-initiate',
  5507. initiator: this.initiator,
  5508. sid: this.sid});
  5509. self.localSDP.toJingle(
  5510. init,
  5511. this.initiator == this.me ? 'initiator' : 'responder',
  5512. this.localStreamsSSRC);
  5513. SSRCReplacement.processSessionInit(init);
  5514. self.connection.sendIQ(init,
  5515. function () {
  5516. var ack = {};
  5517. ack.source = 'offer';
  5518. $(document).trigger('ack.jingle', [self.sid, ack]);
  5519. },
  5520. function (stanza) {
  5521. self.state = 'error';
  5522. self.peerconnection.close();
  5523. var error = ($(stanza).find('error').length) ? {
  5524. code: $(stanza).find('error').attr('code'),
  5525. reason: $(stanza).find('error :first')[0].tagName,
  5526. }:{};
  5527. error.source = 'offer';
  5528. JingleSessionPC.onJingleError(self.sid, error);
  5529. },
  5530. 10000);
  5531. }
  5532. sdp.sdp = this.localSDP.raw;
  5533. this.peerconnection.setLocalDescription(sdp,
  5534. function () {
  5535. if(self.usetrickle)
  5536. {
  5537. sendJingle();
  5538. }
  5539. self.setLocalDescription();
  5540. //console.log('setLocalDescription success');
  5541. },
  5542. function (e) {
  5543. console.error('setLocalDescription failed', e);
  5544. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5545. }
  5546. );
  5547. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  5548. for (var i = 0; i < cands.length; i++) {
  5549. var cand = SDPUtil.parse_icecandidate(cands[i]);
  5550. if (cand.type == 'srflx') {
  5551. this.hadstuncandidate = true;
  5552. } else if (cand.type == 'relay') {
  5553. this.hadturncandidate = true;
  5554. }
  5555. }
  5556. };
  5557. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  5558. var self = this;
  5559. $(contents).each(function (idx, content) {
  5560. var name = $(content).attr('name');
  5561. var mediaType = this.getAttribute('name');
  5562. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  5563. ssrcs.each(function () {
  5564. var ssrc = this.getAttribute('ssrc');
  5565. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  5566. function () {
  5567. var owner = this.getAttribute('owner');
  5568. self.ssrcOwners[ssrc] = owner;
  5569. }
  5570. );
  5571. });
  5572. });
  5573. };
  5574. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  5575. return this.ssrcOwners[ssrc];
  5576. };
  5577. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  5578. //console.log('setting remote description... ', desctype);
  5579. this.remoteSDP = new SDP('');
  5580. this.remoteSDP.fromJingle(elem);
  5581. this.readSsrcInfo($(elem).find(">content"));
  5582. if (this.peerconnection.remoteDescription !== null) {
  5583. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  5584. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  5585. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  5586. for (var i = 0; i < pranswer.media.length; i++) {
  5587. // make sure we have ice ufrag and pwd
  5588. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  5589. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  5590. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  5591. } else {
  5592. console.warn('no ice ufrag?');
  5593. }
  5594. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  5595. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  5596. } else {
  5597. console.warn('no ice pwd?');
  5598. }
  5599. }
  5600. // copy over candidates
  5601. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  5602. for (var j = 0; j < lines.length; j++) {
  5603. this.remoteSDP.media[i] += lines[j] + '\r\n';
  5604. }
  5605. }
  5606. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  5607. }
  5608. }
  5609. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  5610. this.peerconnection.setRemoteDescription(remotedesc,
  5611. function () {
  5612. //console.log('setRemoteDescription success');
  5613. },
  5614. function (e) {
  5615. console.error('setRemoteDescription error', e);
  5616. JingleSessionPC.onJingleFatalError(self, e);
  5617. }
  5618. );
  5619. };
  5620. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  5621. var self = this;
  5622. if (this.peerconnection.signalingState == 'closed') {
  5623. return;
  5624. }
  5625. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  5626. console.log('trickle ice candidate arriving before session accept...');
  5627. // create a PRANSWER for setRemoteDescription
  5628. if (!this.remoteSDP) {
  5629. var cobbled = 'v=0\r\n' +
  5630. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  5631. 's=-\r\n' +
  5632. 't=0 0\r\n';
  5633. // first, take some things from the local description
  5634. for (var i = 0; i < this.localSDP.media.length; i++) {
  5635. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  5636. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  5637. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  5638. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  5639. }
  5640. cobbled += 'a=inactive\r\n';
  5641. }
  5642. this.remoteSDP = new SDP(cobbled);
  5643. }
  5644. // then add things like ice and dtls from remote candidate
  5645. elem.each(function () {
  5646. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  5647. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  5648. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  5649. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  5650. var tmp = $(this).find('transport');
  5651. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  5652. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  5653. tmp = $(this).find('transport>fingerprint');
  5654. if (tmp.length) {
  5655. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  5656. } else {
  5657. console.log('no dtls fingerprint (webrtc issue #1718?)');
  5658. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  5659. }
  5660. break;
  5661. }
  5662. }
  5663. }
  5664. });
  5665. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  5666. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  5667. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  5668. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  5669. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  5670. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  5671. }).length == this.remoteSDP.media.length;
  5672. if (iscomplete) {
  5673. console.log('setting pranswer');
  5674. try {
  5675. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  5676. function() {
  5677. },
  5678. function(e) {
  5679. console.log('setRemoteDescription pranswer failed', e.toString());
  5680. });
  5681. } catch (e) {
  5682. console.error('setting pranswer failed', e);
  5683. }
  5684. } else {
  5685. //console.log('not yet setting pranswer');
  5686. }
  5687. }
  5688. // operate on each content element
  5689. elem.each(function () {
  5690. // would love to deactivate this, but firefox still requires it
  5691. var idx = -1;
  5692. var i;
  5693. for (i = 0; i < self.remoteSDP.media.length; i++) {
  5694. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  5695. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  5696. idx = i;
  5697. break;
  5698. }
  5699. }
  5700. if (idx == -1) { // fall back to localdescription
  5701. for (i = 0; i < self.localSDP.media.length; i++) {
  5702. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  5703. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  5704. idx = i;
  5705. break;
  5706. }
  5707. }
  5708. }
  5709. var name = $(this).attr('name');
  5710. // TODO: check ice-pwd and ice-ufrag?
  5711. $(this).find('transport>candidate').each(function () {
  5712. var line, candidate;
  5713. line = SDPUtil.candidateFromJingle(this);
  5714. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  5715. sdpMid: name,
  5716. candidate: line});
  5717. try {
  5718. self.peerconnection.addIceCandidate(candidate);
  5719. } catch (e) {
  5720. console.error('addIceCandidate failed', e.toString(), line);
  5721. }
  5722. });
  5723. });
  5724. };
  5725. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  5726. //console.log('createAnswer', provisional);
  5727. var self = this;
  5728. this.peerconnection.createAnswer(
  5729. function (sdp) {
  5730. self.createdAnswer(sdp, provisional);
  5731. },
  5732. function (e) {
  5733. console.error('createAnswer failed', e);
  5734. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5735. },
  5736. this.media_constraints
  5737. );
  5738. };
  5739. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  5740. //console.log('createAnswer callback');
  5741. var self = this;
  5742. this.localSDP = new SDP(sdp.sdp);
  5743. //this.localSDP.mangle();
  5744. this.usepranswer = provisional === true;
  5745. if (this.usetrickle) {
  5746. if (this.usepranswer) {
  5747. sdp.type = 'pranswer';
  5748. for (var i = 0; i < this.localSDP.media.length; i++) {
  5749. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  5750. }
  5751. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  5752. }
  5753. }
  5754. var self = this;
  5755. var sendJingle = function (ssrcs) {
  5756. // FIXME why do we generate session-accept in 3 different places ?
  5757. var accept = $iq({to: self.peerjid,
  5758. type: 'set'})
  5759. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5760. action: 'session-accept',
  5761. initiator: self.initiator,
  5762. responder: self.responder,
  5763. sid: self.sid });
  5764. self.localSDP.toJingle(
  5765. accept,
  5766. self.initiator == self.me ? 'initiator' : 'responder',
  5767. ssrcs);
  5768. SSRCReplacement.processSessionInit(accept);
  5769. self.connection.sendIQ(accept,
  5770. function () {
  5771. var ack = {};
  5772. ack.source = 'answer';
  5773. $(document).trigger('ack.jingle', [self.sid, ack]);
  5774. },
  5775. function (stanza) {
  5776. var error = ($(stanza).find('error').length) ? {
  5777. code: $(stanza).find('error').attr('code'),
  5778. reason: $(stanza).find('error :first')[0].tagName,
  5779. }:{};
  5780. error.source = 'answer';
  5781. JingleSessionPC.onJingleError(self.sid, error);
  5782. },
  5783. 10000);
  5784. }
  5785. sdp.sdp = this.localSDP.raw;
  5786. this.peerconnection.setLocalDescription(sdp,
  5787. function () {
  5788. //console.log('setLocalDescription success');
  5789. if (self.usetrickle && !self.usepranswer) {
  5790. sendJingle();
  5791. }
  5792. self.setLocalDescription();
  5793. },
  5794. function (e) {
  5795. console.error('setLocalDescription failed', e);
  5796. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5797. }
  5798. );
  5799. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  5800. for (var j = 0; j < cands.length; j++) {
  5801. var cand = SDPUtil.parse_icecandidate(cands[j]);
  5802. if (cand.type == 'srflx') {
  5803. this.hadstuncandidate = true;
  5804. } else if (cand.type == 'relay') {
  5805. this.hadturncandidate = true;
  5806. }
  5807. }
  5808. };
  5809. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  5810. var self = this,
  5811. term = $iq({to: this.peerjid,
  5812. type: 'set'})
  5813. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5814. action: 'session-terminate',
  5815. initiator: this.initiator,
  5816. sid: this.sid})
  5817. .c('reason')
  5818. .c(reason || 'success');
  5819. if (text) {
  5820. term.up().c('text').t(text);
  5821. }
  5822. this.connection.sendIQ(term,
  5823. function () {
  5824. self.peerconnection.close();
  5825. self.peerconnection = null;
  5826. self.terminate();
  5827. var ack = {};
  5828. ack.source = 'terminate';
  5829. $(document).trigger('ack.jingle', [self.sid, ack]);
  5830. },
  5831. function (stanza) {
  5832. var error = ($(stanza).find('error').length) ? {
  5833. code: $(stanza).find('error').attr('code'),
  5834. reason: $(stanza).find('error :first')[0].tagName,
  5835. }:{};
  5836. $(document).trigger('ack.jingle', [self.sid, error]);
  5837. },
  5838. 10000);
  5839. if (this.statsinterval !== null) {
  5840. window.clearInterval(this.statsinterval);
  5841. this.statsinterval = null;
  5842. }
  5843. };
  5844. JingleSessionPC.prototype.addSource = function (elem, fromJid) {
  5845. var self = this;
  5846. // FIXME: dirty waiting
  5847. if (!this.peerconnection.localDescription)
  5848. {
  5849. console.warn("addSource - localDescription not ready yet")
  5850. setTimeout(function()
  5851. {
  5852. self.addSource(elem, fromJid);
  5853. },
  5854. 200
  5855. );
  5856. return;
  5857. }
  5858. console.log('addssrc', new Date().getTime());
  5859. console.log('ice', this.peerconnection.iceConnectionState);
  5860. this.readSsrcInfo(elem);
  5861. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  5862. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  5863. $(elem).each(function (idx, content) {
  5864. var name = $(content).attr('name');
  5865. var lines = '';
  5866. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  5867. var semantics = this.getAttribute('semantics');
  5868. var ssrcs = $(this).find('>source').map(function () {
  5869. return this.getAttribute('ssrc');
  5870. }).get();
  5871. if (ssrcs.length != 0) {
  5872. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  5873. }
  5874. });
  5875. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  5876. tmp.each(function () {
  5877. var ssrc = $(this).attr('ssrc');
  5878. if(mySdp.containsSSRC(ssrc)){
  5879. /**
  5880. * This happens when multiple participants change their streams at the same time and
  5881. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  5882. * addssrc are scheduled for update IQ. See
  5883. */
  5884. console.warn("Got add stream request for my own ssrc: "+ssrc);
  5885. return;
  5886. }
  5887. if (sdp.containsSSRC(ssrc)) {
  5888. console.warn("Source-add request for existing SSRC: " + ssrc);
  5889. return;
  5890. }
  5891. $(this).find('>parameter').each(function () {
  5892. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  5893. if ($(this).attr('value') && $(this).attr('value').length)
  5894. lines += ':' + $(this).attr('value');
  5895. lines += '\r\n';
  5896. });
  5897. });
  5898. sdp.media.forEach(function(media, idx) {
  5899. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  5900. return;
  5901. sdp.media[idx] += lines;
  5902. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  5903. self.addssrc[idx] += lines;
  5904. });
  5905. sdp.raw = sdp.session + sdp.media.join('');
  5906. });
  5907. this.modifySourcesQueue.push(function() {
  5908. // When a source is added and if this is FF, a new channel is allocated
  5909. // for receiving the added source. We need to diffuse the SSRC of this
  5910. // new recvonly channel to the rest of the peers.
  5911. console.log('modify sources done');
  5912. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  5913. console.log("SDPs", mySdp, newSdp);
  5914. self.notifyMySSRCUpdate(mySdp, newSdp);
  5915. });
  5916. };
  5917. JingleSessionPC.prototype.removeSource = function (elem, fromJid) {
  5918. var self = this;
  5919. // FIXME: dirty waiting
  5920. if (!this.peerconnection.localDescription)
  5921. {
  5922. console.warn("removeSource - localDescription not ready yet")
  5923. setTimeout(function()
  5924. {
  5925. self.removeSource(elem, fromJid);
  5926. },
  5927. 200
  5928. );
  5929. return;
  5930. }
  5931. console.log('removessrc', new Date().getTime());
  5932. console.log('ice', this.peerconnection.iceConnectionState);
  5933. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  5934. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  5935. $(elem).each(function (idx, content) {
  5936. var name = $(content).attr('name');
  5937. var lines = '';
  5938. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  5939. var semantics = this.getAttribute('semantics');
  5940. var ssrcs = $(this).find('>source').map(function () {
  5941. return this.getAttribute('ssrc');
  5942. }).get();
  5943. if (ssrcs.length != 0) {
  5944. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  5945. }
  5946. });
  5947. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  5948. tmp.each(function () {
  5949. var ssrc = $(this).attr('ssrc');
  5950. // This should never happen, but can be useful for bug detection
  5951. if(mySdp.containsSSRC(ssrc)){
  5952. console.error("Got remove stream request for my own ssrc: "+ssrc);
  5953. return;
  5954. }
  5955. $(this).find('>parameter').each(function () {
  5956. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  5957. if ($(this).attr('value') && $(this).attr('value').length)
  5958. lines += ':' + $(this).attr('value');
  5959. lines += '\r\n';
  5960. });
  5961. });
  5962. sdp.media.forEach(function(media, idx) {
  5963. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  5964. return;
  5965. sdp.media[idx] += lines;
  5966. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  5967. self.removessrc[idx] += lines;
  5968. });
  5969. sdp.raw = sdp.session + sdp.media.join('');
  5970. });
  5971. this.modifySourcesQueue.push(function() {
  5972. // When a source is removed and if this is FF, the recvonly channel that
  5973. // receives the remote stream is deactivated . We need to diffuse the
  5974. // recvonly SSRC removal to the rest of the peers.
  5975. console.log('modify sources done');
  5976. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  5977. console.log("SDPs", mySdp, newSdp);
  5978. self.notifyMySSRCUpdate(mySdp, newSdp);
  5979. });
  5980. };
  5981. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  5982. var self = this;
  5983. if (this.peerconnection.signalingState == 'closed') return;
  5984. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  5985. || this.switchstreams || this.addingStreams)){
  5986. // There is nothing to do since scheduled job might have been executed by another succeeding call
  5987. this.setLocalDescription();
  5988. if(successCallback){
  5989. successCallback();
  5990. }
  5991. queueCallback();
  5992. return;
  5993. }
  5994. // Reset switch streams flags
  5995. this.switchstreams = false;
  5996. this.addingStreams = false;
  5997. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  5998. // add sources
  5999. this.addssrc.forEach(function(lines, idx) {
  6000. sdp.media[idx] += lines;
  6001. });
  6002. this.addssrc = [];
  6003. // remove sources
  6004. this.removessrc.forEach(function(lines, idx) {
  6005. lines = lines.split('\r\n');
  6006. lines.pop(); // remove empty last element;
  6007. lines.forEach(function(line) {
  6008. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  6009. });
  6010. });
  6011. this.removessrc = [];
  6012. sdp.raw = sdp.session + sdp.media.join('');
  6013. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  6014. function() {
  6015. if(self.signalingState == 'closed') {
  6016. console.error("createAnswer attempt on closed state");
  6017. queueCallback("createAnswer attempt on closed state");
  6018. return;
  6019. }
  6020. self.peerconnection.createAnswer(
  6021. function(modifiedAnswer) {
  6022. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  6023. if (self.pendingop !== null) {
  6024. var sdp = new SDP(modifiedAnswer.sdp);
  6025. if (sdp.media.length > 1) {
  6026. switch(self.pendingop) {
  6027. case 'mute':
  6028. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  6029. break;
  6030. case 'unmute':
  6031. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  6032. break;
  6033. }
  6034. sdp.raw = sdp.session + sdp.media.join('');
  6035. modifiedAnswer.sdp = sdp.raw;
  6036. }
  6037. self.pendingop = null;
  6038. }
  6039. // FIXME: pushing down an answer while ice connection state
  6040. // is still checking is bad...
  6041. //console.log(self.peerconnection.iceConnectionState);
  6042. // trying to work around another chrome bug
  6043. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  6044. self.peerconnection.setLocalDescription(modifiedAnswer,
  6045. function() {
  6046. //console.log('modified setLocalDescription ok');
  6047. self.setLocalDescription();
  6048. if(successCallback){
  6049. successCallback();
  6050. }
  6051. queueCallback();
  6052. },
  6053. function(error) {
  6054. console.error('modified setLocalDescription failed', error);
  6055. queueCallback(error);
  6056. }
  6057. );
  6058. },
  6059. function(error) {
  6060. console.error('modified answer failed', error);
  6061. queueCallback(error);
  6062. }
  6063. );
  6064. },
  6065. function(error) {
  6066. console.error('modify failed', error);
  6067. queueCallback(error);
  6068. }
  6069. );
  6070. };
  6071. /**
  6072. * Switches video streams.
  6073. * @param new_stream new stream that will be used as video of this session.
  6074. * @param oldStream old video stream of this session.
  6075. * @param success_callback callback executed after successful stream switch.
  6076. */
  6077. JingleSessionPC.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  6078. var self = this;
  6079. // Remember SDP to figure out added/removed SSRCs
  6080. var oldSdp = null;
  6081. if(self.peerconnection) {
  6082. if(self.peerconnection.localDescription) {
  6083. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  6084. }
  6085. self.peerconnection.removeStream(oldStream, true);
  6086. if(new_stream)
  6087. self.peerconnection.addStream(new_stream);
  6088. }
  6089. // Conference is not active
  6090. if(!oldSdp || !self.peerconnection) {
  6091. success_callback();
  6092. return;
  6093. }
  6094. self.switchstreams = true;
  6095. self.modifySourcesQueue.push(function() {
  6096. console.log('modify sources done');
  6097. success_callback();
  6098. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6099. console.log("SDPs", oldSdp, newSdp);
  6100. self.notifyMySSRCUpdate(oldSdp, newSdp);
  6101. });
  6102. };
  6103. /**
  6104. * Adds streams.
  6105. * @param stream new stream that will be added.
  6106. * @param success_callback callback executed after successful stream addition.
  6107. */
  6108. JingleSessionPC.prototype.addStream = function (stream, callback) {
  6109. var self = this;
  6110. // Remember SDP to figure out added/removed SSRCs
  6111. var oldSdp = null;
  6112. if(this.peerconnection) {
  6113. if(this.peerconnection.localDescription) {
  6114. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  6115. }
  6116. if(stream)
  6117. this.peerconnection.addStream(stream);
  6118. }
  6119. // Conference is not active
  6120. if(!oldSdp || !this.peerconnection) {
  6121. callback();
  6122. return;
  6123. }
  6124. this.addingStreams = true;
  6125. this.modifySourcesQueue.push(function() {
  6126. console.log('modify sources done');
  6127. callback();
  6128. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6129. console.log("SDPs", oldSdp, newSdp);
  6130. self.notifyMySSRCUpdate(oldSdp, newSdp);
  6131. });
  6132. }
  6133. /**
  6134. * Figures out added/removed ssrcs and send update IQs.
  6135. * @param old_sdp SDP object for old description.
  6136. * @param new_sdp SDP object for new description.
  6137. */
  6138. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  6139. if (!(this.peerconnection.signalingState == 'stable' &&
  6140. this.peerconnection.iceConnectionState == 'connected')){
  6141. console.log("Too early to send updates");
  6142. return;
  6143. }
  6144. // send source-remove IQ.
  6145. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  6146. var remove = $iq({to: this.peerjid, type: 'set'})
  6147. .c('jingle', {
  6148. xmlns: 'urn:xmpp:jingle:1',
  6149. action: 'source-remove',
  6150. initiator: this.initiator,
  6151. sid: this.sid
  6152. }
  6153. );
  6154. var removed = sdpDiffer.toJingle(remove);
  6155. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  6156. // it in the current form
  6157. if (removed)
  6158. remove = SSRCReplacement.processSourceRemove(remove);
  6159. if (removed && remove) {
  6160. console.info("Sending source-remove", remove);
  6161. this.connection.sendIQ(remove,
  6162. function (res) {
  6163. console.info('got remove result', res);
  6164. },
  6165. function (err) {
  6166. console.error('got remove error', err);
  6167. }
  6168. );
  6169. } else {
  6170. console.log('removal not necessary');
  6171. }
  6172. // send source-add IQ.
  6173. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  6174. var add = $iq({to: this.peerjid, type: 'set'})
  6175. .c('jingle', {
  6176. xmlns: 'urn:xmpp:jingle:1',
  6177. action: 'source-add',
  6178. initiator: this.initiator,
  6179. sid: this.sid
  6180. }
  6181. );
  6182. var added = sdpDiffer.toJingle(add);
  6183. // Let 'source-add' IQ through the hack and see if we're allowed to send
  6184. // it in the current form
  6185. if (added)
  6186. add = SSRCReplacement.processSourceAdd(add);
  6187. if (added && add) {
  6188. console.info("Sending source-add", add);
  6189. this.connection.sendIQ(add,
  6190. function (res) {
  6191. console.info('got add result', res);
  6192. },
  6193. function (err) {
  6194. console.error('got add error', err);
  6195. }
  6196. );
  6197. } else {
  6198. console.log('addition not necessary');
  6199. }
  6200. };
  6201. /**
  6202. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  6203. *
  6204. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  6205. * tracks; otherwise, <tt>false</tt>
  6206. * @param callback a function to be invoked with <tt>mute</tt> after all video
  6207. * tracks have been enabled/disabled. The function may, optionally, return
  6208. * another function which is to be invoked after the whole mute/unmute operation
  6209. * has completed successfully.
  6210. * @param options an object which specifies optional arguments such as the
  6211. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  6212. * specifies whether the method was initiated in response to a user command (in
  6213. * contrast to an automatic decision made by the application logic)
  6214. */
  6215. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  6216. var byUser;
  6217. if (options) {
  6218. byUser = options.byUser;
  6219. if (typeof byUser === 'undefined') {
  6220. byUser = true;
  6221. }
  6222. } else {
  6223. byUser = true;
  6224. }
  6225. // The user's command to mute the (local) video takes precedence over any
  6226. // automatic decision made by the application logic.
  6227. if (byUser) {
  6228. this.videoMuteByUser = mute;
  6229. } else if (this.videoMuteByUser) {
  6230. return;
  6231. }
  6232. this.hardMuteVideo(mute);
  6233. var self = this;
  6234. var oldSdp = null;
  6235. if(self.peerconnection) {
  6236. if(self.peerconnection.localDescription) {
  6237. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  6238. }
  6239. }
  6240. this.modifySourcesQueue.push(function() {
  6241. console.log('modify sources done');
  6242. callback(mute);
  6243. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6244. console.log("SDPs", oldSdp, newSdp);
  6245. self.notifyMySSRCUpdate(oldSdp, newSdp);
  6246. });
  6247. };
  6248. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  6249. this.pendingop = muted ? 'mute' : 'unmute';
  6250. };
  6251. JingleSessionPC.prototype.sendMute = function (muted, content) {
  6252. var info = $iq({to: this.peerjid,
  6253. type: 'set'})
  6254. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6255. action: 'session-info',
  6256. initiator: this.initiator,
  6257. sid: this.sid });
  6258. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  6259. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  6260. if (content) {
  6261. info.attrs({'name': content});
  6262. }
  6263. this.connection.send(info);
  6264. };
  6265. JingleSessionPC.prototype.sendRinging = function () {
  6266. var info = $iq({to: this.peerjid,
  6267. type: 'set'})
  6268. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6269. action: 'session-info',
  6270. initiator: this.initiator,
  6271. sid: this.sid });
  6272. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  6273. this.connection.send(info);
  6274. };
  6275. JingleSessionPC.prototype.getStats = function (interval) {
  6276. var self = this;
  6277. var recv = {audio: 0, video: 0};
  6278. var lost = {audio: 0, video: 0};
  6279. var lastrecv = {audio: 0, video: 0};
  6280. var lastlost = {audio: 0, video: 0};
  6281. var loss = {audio: 0, video: 0};
  6282. var delta = {audio: 0, video: 0};
  6283. this.statsinterval = window.setInterval(function () {
  6284. if (self && self.peerconnection && self.peerconnection.getStats) {
  6285. self.peerconnection.getStats(function (stats) {
  6286. var results = stats.result();
  6287. // TODO: there are so much statistics you can get from this..
  6288. for (var i = 0; i < results.length; ++i) {
  6289. if (results[i].type == 'ssrc') {
  6290. var packetsrecv = results[i].stat('packetsReceived');
  6291. var packetslost = results[i].stat('packetsLost');
  6292. if (packetsrecv && packetslost) {
  6293. packetsrecv = parseInt(packetsrecv, 10);
  6294. packetslost = parseInt(packetslost, 10);
  6295. if (results[i].stat('googFrameRateReceived')) {
  6296. lastlost.video = lost.video;
  6297. lastrecv.video = recv.video;
  6298. recv.video = packetsrecv;
  6299. lost.video = packetslost;
  6300. } else {
  6301. lastlost.audio = lost.audio;
  6302. lastrecv.audio = recv.audio;
  6303. recv.audio = packetsrecv;
  6304. lost.audio = packetslost;
  6305. }
  6306. }
  6307. }
  6308. }
  6309. delta.audio = recv.audio - lastrecv.audio;
  6310. delta.video = recv.video - lastrecv.video;
  6311. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  6312. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  6313. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  6314. });
  6315. }
  6316. }, interval || 3000);
  6317. return this.statsinterval;
  6318. };
  6319. JingleSessionPC.onJingleError = function (session, error)
  6320. {
  6321. console.error("Jingle error", error);
  6322. }
  6323. JingleSessionPC.onJingleFatalError = function (session, error)
  6324. {
  6325. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6326. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  6327. }
  6328. JingleSessionPC.prototype.setLocalDescription = function () {
  6329. var self = this;
  6330. var newssrcs = [];
  6331. var session = transform.parse(this.peerconnection.localDescription.sdp);
  6332. session.media.forEach(function (media) {
  6333. if (media.ssrcs != null && media.ssrcs.length > 0) {
  6334. // TODO(gp) maybe exclude FID streams?
  6335. media.ssrcs.forEach(function (ssrc) {
  6336. if (ssrc.attribute !== 'cname') {
  6337. return;
  6338. }
  6339. newssrcs.push({
  6340. 'ssrc': ssrc.id,
  6341. 'type': media.type
  6342. });
  6343. });
  6344. }
  6345. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  6346. {
  6347. newssrcs.push({
  6348. 'ssrc': self.localStreamsSSRC[media.type],
  6349. 'type': media.type
  6350. });
  6351. }
  6352. });
  6353. console.log('new ssrcs', newssrcs);
  6354. // Bind us as local SSRCs owner
  6355. if (newssrcs.length > 0) {
  6356. for (var i = 1; i <= newssrcs.length; i ++) {
  6357. var ssrc = newssrcs[i-1].ssrc;
  6358. var myJid = self.connection.emuc.myroomjid;
  6359. self.ssrcOwners[ssrc] = myJid;
  6360. }
  6361. }
  6362. }
  6363. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  6364. JingleSessionPC.prototype.sendKeyframe = function () {
  6365. var pc = this.peerconnection;
  6366. console.log('sendkeyframe', pc.iceConnectionState);
  6367. if (pc.iceConnectionState !== 'connected') return; // safe...
  6368. var self = this;
  6369. pc.setRemoteDescription(
  6370. pc.remoteDescription,
  6371. function () {
  6372. pc.createAnswer(
  6373. function (modifiedAnswer) {
  6374. pc.setLocalDescription(
  6375. modifiedAnswer,
  6376. function () {
  6377. // noop
  6378. },
  6379. function (error) {
  6380. console.log('triggerKeyframe setLocalDescription failed', error);
  6381. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  6382. }
  6383. );
  6384. },
  6385. function (error) {
  6386. console.log('triggerKeyframe createAnswer failed', error);
  6387. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  6388. }
  6389. );
  6390. },
  6391. function (error) {
  6392. console.log('triggerKeyframe setRemoteDescription failed', error);
  6393. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  6394. }
  6395. );
  6396. }
  6397. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  6398. var self = this;
  6399. var thessrc;
  6400. var streamId = RTC.getStreamID(data.stream);
  6401. // look up an associated JID for a stream id
  6402. if (!streamId) {
  6403. console.error("No stream ID for", data.stream);
  6404. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  6405. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  6406. var ssrclines
  6407. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  6408. ssrclines = ssrclines.filter(function (line) {
  6409. // NOTE(gp) previously we filtered on the mslabel, but that property
  6410. // is not always present.
  6411. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  6412. if (RTCBrowserType.isTemasysPluginUsed()) {
  6413. return ((line.indexOf('mslabel:' + streamId) !== -1));
  6414. } else {
  6415. return ((line.indexOf('msid:' + streamId) !== -1));
  6416. }
  6417. });
  6418. if (ssrclines.length) {
  6419. thessrc = ssrclines[0].substring(7).split(' ')[0];
  6420. if (!self.ssrcOwners[thessrc]) {
  6421. console.error("No SSRC owner known for: " + thessrc);
  6422. return;
  6423. }
  6424. data.peerjid = self.ssrcOwners[thessrc];
  6425. console.log('associated jid', self.ssrcOwners[thessrc]);
  6426. } else {
  6427. console.error("No SSRC lines for ", streamId);
  6428. }
  6429. }
  6430. this.room.remoteStreamAdded(data, this.sid, thessrc);
  6431. var isVideo = data.stream.getVideoTracks().length > 0;
  6432. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  6433. if (isVideo &&
  6434. data.peerjid && this.peerjid === data.peerjid &&
  6435. data.stream.getVideoTracks().length === 0 &&
  6436. RTC.localVideo.getTracks().length > 0) {
  6437. window.setTimeout(function () {
  6438. self.sendKeyframe();
  6439. }, 3000);
  6440. }
  6441. }
  6442. module.exports = JingleSessionPC;
  6443. },{"../../service/xmpp/XMPPEvents":83,"../RTC/RTC":13,"../RTC/RTCBrowserType":14,"./JingleSession":24,"./LocalSSRCReplacement":26,"./SDP":27,"./SDPDiffer":28,"./SDPUtil":29,"./TraceablePeerConnection":30,"async":38,"sdp-transform":73}],26:[function(require,module,exports){
  6444. /* global $ */
  6445. /*
  6446. Here we do modifications of local video SSRCs. There are 2 situations we have
  6447. to handle:
  6448. 1. We generate SSRC for local recvonly video stream. This is the case when we
  6449. have no local camera and it is not generated automatically, but SSRC=1 is
  6450. used implicitly. If that happens RTCP packets will be dropped by the JVB
  6451. and we won't be able to request video key frames correctly.
  6452. 2. A hack to re-use SSRC of the first video stream for any new stream created
  6453. in future. It turned out that Chrome may keep on using the SSRC of removed
  6454. video stream in RTCP even though a new one has been created. So we just
  6455. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  6456. notifications are blocked once first video SSRC is advertised to the focus.
  6457. What this hack does:
  6458. 1. Stores the SSRC of the first video stream created by
  6459. a) scanning Jingle session-accept/session-invite for existing video SSRC
  6460. b) watching for 'source-add' for new video stream if it has not been
  6461. created in step a)
  6462. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  6463. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  6464. returned to the other parts of the application.
  6465. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  6466. blocks those notifications. This makes Jicofo and all participants think
  6467. that it exists all the time even if the video stream has been removed or
  6468. replaced locally. Thanks to that there is no additional signaling activity
  6469. on video mute or when switching to the desktop stream.
  6470. */
  6471. var SDP = require('./SDP');
  6472. var RandomUtil = require('../util/RandomUtil');
  6473. var RTCBrowserType = require('../RTC/RTCBrowserType');
  6474. /**
  6475. * The hack is enabled on all browsers except FF by default
  6476. * FIXME finish the hack once removeStream method is implemented in FF
  6477. * @type {boolean}
  6478. */
  6479. var isEnabled = !RTCBrowserType.isFirefox();
  6480. /**
  6481. * Stored SSRC of local video stream.
  6482. */
  6483. var localVideoSSRC;
  6484. /**
  6485. * SSRC, msid, mslabel, label used for recvonly video stream when we have no local camera.
  6486. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  6487. * instead of 1.
  6488. */
  6489. var localRecvOnlySSRC, localRecvOnlyMSID, localRecvOnlyMSLabel, localRecvOnlyLabel;
  6490. /**
  6491. * cname for <tt>localRecvOnlySSRC</tt>
  6492. */
  6493. var localRecvOnlyCName;
  6494. /**
  6495. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  6496. * from given Jingle IQ.
  6497. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  6498. * @param actionName display name of the action which will be printed in log
  6499. * messages.
  6500. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  6501. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  6502. * other SSRCs left to be signaled after removing it.
  6503. */
  6504. var filterOutSource = function (modifyIq, actionName) {
  6505. var modifyIqTree = $(modifyIq.tree());
  6506. if (!localVideoSSRC)
  6507. return modifyIqTree[0];
  6508. var videoSSRC = modifyIqTree.find(
  6509. '>jingle>content[name="video"]' +
  6510. '>description>source[ssrc="' + localVideoSSRC + '"]');
  6511. if (!videoSSRC.length) {
  6512. return modifyIqTree[0];
  6513. }
  6514. console.info(
  6515. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  6516. videoSSRC.remove();
  6517. // Check if any sources still left to be added/removed
  6518. if (modifyIqTree.find('>jingle>content>description>source').length) {
  6519. return modifyIqTree[0];
  6520. } else {
  6521. return null;
  6522. }
  6523. };
  6524. /**
  6525. * Scans given Jingle IQ for video SSRC and stores it.
  6526. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  6527. */
  6528. var storeLocalVideoSSRC = function (jingleIq) {
  6529. var videoSSRCs =
  6530. $(jingleIq.tree())
  6531. .find('>jingle>content[name="video"]>description>source');
  6532. videoSSRCs.each(function (idx, ssrcElem) {
  6533. if (localVideoSSRC)
  6534. return;
  6535. // We consider SSRC real only if it has msid attribute
  6536. // recvonly streams in FF do not have it as well as local SSRCs
  6537. // we generate for recvonly streams in Chrome
  6538. var ssrSel = $(ssrcElem);
  6539. var msid = ssrSel.find('>parameter[name="msid"]');
  6540. if (msid.length) {
  6541. var ssrcVal = ssrSel.attr('ssrc');
  6542. if (ssrcVal) {
  6543. localVideoSSRC = ssrcVal;
  6544. console.info('Stored local video SSRC' +
  6545. ' for future re-use: ' + localVideoSSRC);
  6546. }
  6547. }
  6548. });
  6549. };
  6550. /**
  6551. * Generates new label/mslabel attribute
  6552. * @returns {string} label/mslabel attribute
  6553. */
  6554. function generateLabel() {
  6555. return RandomUtil.random8digitsHex() + "-" + RandomUtil.random4digitsHex() + "-" +
  6556. RandomUtil.random4digitsHex() + "-" + RandomUtil.random4digitsHex() + "-" + RandomUtil.random12digitsHex();
  6557. }
  6558. /**
  6559. * Generates new SSRC, CNAME, mslabel, label and msid for local video recvonly stream.
  6560. * FIXME what about eventual SSRC collision ?
  6561. */
  6562. function generateRecvonlySSRC() {
  6563. localRecvOnlySSRC =
  6564. Math.random().toString(10).substring(2, 11);
  6565. localRecvOnlyCName =
  6566. Math.random().toString(36).substring(2);
  6567. localRecvOnlyMSLabel = generateLabel();
  6568. localRecvOnlyLabel = generateLabel();
  6569. localRecvOnlyMSID = localRecvOnlyMSLabel + " " + localRecvOnlyLabel;
  6570. console.info(
  6571. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  6572. ", cname: " + localRecvOnlyCName);
  6573. }
  6574. var LocalSSRCReplacement = {
  6575. /**
  6576. * Method must be called before 'session-initiate' or 'session-invite' is
  6577. * sent. Scans the IQ for local video SSRC and stores it if detected.
  6578. *
  6579. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  6580. * which will be scanned for local video SSRC.
  6581. */
  6582. processSessionInit: function (sessionInit) {
  6583. if (!isEnabled)
  6584. return;
  6585. if (localVideoSSRC) {
  6586. console.error("Local SSRC stored already: " + localVideoSSRC);
  6587. return;
  6588. }
  6589. storeLocalVideoSSRC(sessionInit);
  6590. },
  6591. /**
  6592. * If we have local video SSRC stored searched given
  6593. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  6594. * with the stored one.
  6595. * @param localDescription local description object that will have local
  6596. * video SSRC replaced with the stored one
  6597. * @returns modified <tt>localDescription</tt> object.
  6598. */
  6599. mungeLocalVideoSSRC: function (localDescription) {
  6600. if (!isEnabled)
  6601. return localDescription;
  6602. if (!localDescription) {
  6603. console.warn("localDescription is null or undefined");
  6604. return localDescription;
  6605. }
  6606. // IF we have local video SSRC stored make sure it is replaced
  6607. // with old SSRC
  6608. if (localVideoSSRC) {
  6609. var newSdp = new SDP(localDescription.sdp);
  6610. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  6611. !newSdp.containsSSRC(localVideoSSRC)) {
  6612. // Get new video SSRC
  6613. var map = newSdp.getMediaSsrcMap();
  6614. var videoPart = map[1];
  6615. var videoSSRCs = videoPart.ssrcs;
  6616. var newSSRC = Object.keys(videoSSRCs)[0];
  6617. console.info(
  6618. "Replacing new video SSRC: " + newSSRC +
  6619. " with " + localVideoSSRC);
  6620. localDescription.sdp =
  6621. newSdp.raw.replace(
  6622. new RegExp('a=ssrc:' + newSSRC, 'g'),
  6623. 'a=ssrc:' + localVideoSSRC);
  6624. }
  6625. } else {
  6626. // Make sure we have any SSRC for recvonly video stream
  6627. var sdp = new SDP(localDescription.sdp);
  6628. if (sdp.media[1] && sdp.media[1].indexOf('a=ssrc:') === -1 &&
  6629. sdp.media[1].indexOf('a=recvonly') !== -1) {
  6630. if (!localRecvOnlySSRC) {
  6631. generateRecvonlySSRC();
  6632. }
  6633. localVideoSSRC = localRecvOnlySSRC;
  6634. console.info('No SSRC in video recvonly stream' +
  6635. ' - adding SSRC: ' + localRecvOnlySSRC);
  6636. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  6637. ' cname:' + localRecvOnlyCName + '\r\n' +
  6638. 'a=ssrc:' + localRecvOnlySSRC +
  6639. ' msid:' + localRecvOnlyMSID + '\r\n' +
  6640. 'a=ssrc:' + localRecvOnlySSRC +
  6641. ' mslabel:' + localRecvOnlyMSLabel + '\r\n' +
  6642. 'a=ssrc:' + localRecvOnlySSRC +
  6643. ' label:' + localRecvOnlyLabel + '\r\n';
  6644. localDescription.sdp = sdp.session + sdp.media.join('');
  6645. }
  6646. }
  6647. return localDescription;
  6648. },
  6649. /**
  6650. * Method must be called before 'source-add' notification is sent. In case
  6651. * we have local video SSRC advertised already it will be removed from the
  6652. * notification. If no other SSRCs are described by given IQ null will be
  6653. * returned which means that there is no point in sending the notification.
  6654. * @param sourceAdd 'source-add' Jingle IQ to be processed
  6655. * @returns modified 'source-add' IQ which can be sent to the focus or
  6656. * <tt>null</tt> if no notification shall be sent. It is no longer
  6657. * a Strophe IQ Builder instance, but DOM element tree.
  6658. */
  6659. processSourceAdd: function (sourceAdd) {
  6660. if (!isEnabled)
  6661. return sourceAdd;
  6662. if (!localVideoSSRC) {
  6663. // Store local SSRC if available
  6664. storeLocalVideoSSRC(sourceAdd);
  6665. return sourceAdd;
  6666. } else {
  6667. return filterOutSource(sourceAdd, 'source-add');
  6668. }
  6669. },
  6670. /**
  6671. * Method must be called before 'source-remove' notification is sent.
  6672. * Removes local video SSRC from the notification. If there are no other
  6673. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  6674. * means that there is no point in sending the notification.
  6675. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  6676. * @returns modified 'source-remove' IQ which can be sent to the focus or
  6677. * <tt>null</tt> if no notification shall be sent. It is no longer
  6678. * a Strophe IQ Builder instance, but DOM element tree.
  6679. */
  6680. processSourceRemove: function (sourceRemove) {
  6681. if (!isEnabled)
  6682. return sourceRemove;
  6683. return filterOutSource(sourceRemove, 'source-remove');
  6684. },
  6685. /**
  6686. * Turns the hack on or off
  6687. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  6688. * to disable it
  6689. */
  6690. setEnabled: function (enabled) {
  6691. isEnabled = enabled;
  6692. }
  6693. };
  6694. module.exports = LocalSSRCReplacement;
  6695. },{"../RTC/RTCBrowserType":14,"../util/RandomUtil":22,"./SDP":27}],27:[function(require,module,exports){
  6696. /* jshint -W117 */
  6697. var SDPUtil = require("./SDPUtil");
  6698. // SDP STUFF
  6699. function SDP(sdp) {
  6700. this.media = sdp.split('\r\nm=');
  6701. for (var i = 1; i < this.media.length; i++) {
  6702. this.media[i] = 'm=' + this.media[i];
  6703. if (i != this.media.length - 1) {
  6704. this.media[i] += '\r\n';
  6705. }
  6706. }
  6707. this.session = this.media.shift() + '\r\n';
  6708. this.raw = this.session + this.media.join('');
  6709. }
  6710. /**
  6711. * Returns map of MediaChannel mapped per channel idx.
  6712. */
  6713. SDP.prototype.getMediaSsrcMap = function() {
  6714. var self = this;
  6715. var media_ssrcs = {};
  6716. var tmp;
  6717. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  6718. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  6719. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  6720. var media = {
  6721. mediaindex: mediaindex,
  6722. mid: mid,
  6723. ssrcs: {},
  6724. ssrcGroups: []
  6725. };
  6726. media_ssrcs[mediaindex] = media;
  6727. tmp.forEach(function (line) {
  6728. var linessrc = line.substring(7).split(' ')[0];
  6729. // allocate new ChannelSsrc
  6730. if(!media.ssrcs[linessrc]) {
  6731. media.ssrcs[linessrc] = {
  6732. ssrc: linessrc,
  6733. lines: []
  6734. };
  6735. }
  6736. media.ssrcs[linessrc].lines.push(line);
  6737. });
  6738. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  6739. tmp.forEach(function(line){
  6740. var semantics = line.substr(0, idx).substr(13);
  6741. var ssrcs = line.substr(14 + semantics.length).split(' ');
  6742. if (ssrcs.length != 0) {
  6743. media.ssrcGroups.push({
  6744. semantics: semantics,
  6745. ssrcs: ssrcs
  6746. });
  6747. }
  6748. });
  6749. }
  6750. return media_ssrcs;
  6751. };
  6752. /**
  6753. * Returns <tt>true</tt> if this SDP contains given SSRC.
  6754. * @param ssrc the ssrc to check.
  6755. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  6756. */
  6757. SDP.prototype.containsSSRC = function(ssrc) {
  6758. var medias = this.getMediaSsrcMap();
  6759. var contains = false;
  6760. Object.keys(medias).forEach(function(mediaindex){
  6761. var media = medias[mediaindex];
  6762. //console.log("Check", channel, ssrc);
  6763. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  6764. contains = true;
  6765. }
  6766. });
  6767. return contains;
  6768. };
  6769. // remove iSAC and CN from SDP
  6770. SDP.prototype.mangle = function () {
  6771. var i, j, mline, lines, rtpmap, newdesc;
  6772. for (i = 0; i < this.media.length; i++) {
  6773. lines = this.media[i].split('\r\n');
  6774. lines.pop(); // remove empty last element
  6775. mline = SDPUtil.parse_mline(lines.shift());
  6776. if (mline.media != 'audio')
  6777. continue;
  6778. newdesc = '';
  6779. mline.fmt.length = 0;
  6780. for (j = 0; j < lines.length; j++) {
  6781. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  6782. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  6783. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  6784. continue;
  6785. mline.fmt.push(rtpmap.id);
  6786. newdesc += lines[j] + '\r\n';
  6787. } else {
  6788. newdesc += lines[j] + '\r\n';
  6789. }
  6790. }
  6791. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  6792. this.media[i] += newdesc;
  6793. }
  6794. this.raw = this.session + this.media.join('');
  6795. };
  6796. // remove lines matching prefix from session section
  6797. SDP.prototype.removeSessionLines = function(prefix) {
  6798. var self = this;
  6799. var lines = SDPUtil.find_lines(this.session, prefix);
  6800. lines.forEach(function(line) {
  6801. self.session = self.session.replace(line + '\r\n', '');
  6802. });
  6803. this.raw = this.session + this.media.join('');
  6804. return lines;
  6805. }
  6806. // remove lines matching prefix from a media section specified by mediaindex
  6807. // TODO: non-numeric mediaindex could match mid
  6808. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  6809. var self = this;
  6810. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  6811. lines.forEach(function(line) {
  6812. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  6813. });
  6814. this.raw = this.session + this.media.join('');
  6815. return lines;
  6816. }
  6817. // add content's to a jingle element
  6818. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  6819. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  6820. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  6821. var self = this;
  6822. // new bundle plan
  6823. if (SDPUtil.find_line(this.session, 'a=group:')) {
  6824. lines = SDPUtil.find_lines(this.session, 'a=group:');
  6825. for (i = 0; i < lines.length; i++) {
  6826. tmp = lines[i].split(' ');
  6827. var semantics = tmp.shift().substr(8);
  6828. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  6829. for (j = 0; j < tmp.length; j++) {
  6830. elem.c('content', {name: tmp[j]}).up();
  6831. }
  6832. elem.up();
  6833. }
  6834. }
  6835. for (i = 0; i < this.media.length; i++) {
  6836. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  6837. if (!(mline.media === 'audio' ||
  6838. mline.media === 'video' ||
  6839. mline.media === 'application'))
  6840. {
  6841. continue;
  6842. }
  6843. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  6844. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  6845. } else {
  6846. if(ssrcs && ssrcs[mline.media])
  6847. {
  6848. ssrc = ssrcs[mline.media];
  6849. }
  6850. else
  6851. ssrc = false;
  6852. }
  6853. elem.c('content', {creator: thecreator, name: mline.media});
  6854. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  6855. // prefer identifier from a=mid if present
  6856. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  6857. elem.attrs({ name: mid });
  6858. }
  6859. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  6860. {
  6861. elem.c('description',
  6862. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  6863. media: mline.media });
  6864. if (ssrc) {
  6865. elem.attrs({ssrc: ssrc});
  6866. }
  6867. for (j = 0; j < mline.fmt.length; j++) {
  6868. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  6869. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  6870. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  6871. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  6872. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  6873. for (k = 0; k < tmp.length; k++) {
  6874. elem.c('parameter', tmp[k]).up();
  6875. }
  6876. }
  6877. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  6878. elem.up();
  6879. }
  6880. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  6881. elem.c('encryption', {required: 1});
  6882. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  6883. crypto.forEach(function(line) {
  6884. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  6885. });
  6886. elem.up(); // end of encryption
  6887. }
  6888. if (ssrc) {
  6889. // new style mapping
  6890. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  6891. // FIXME: group by ssrc and support multiple different ssrcs
  6892. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  6893. if(ssrclines.length > 0) {
  6894. ssrclines.forEach(function (line) {
  6895. idx = line.indexOf(' ');
  6896. var linessrc = line.substr(0, idx).substr(7);
  6897. if (linessrc != ssrc) {
  6898. elem.up();
  6899. ssrc = linessrc;
  6900. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  6901. }
  6902. var kv = line.substr(idx + 1);
  6903. elem.c('parameter');
  6904. if (kv.indexOf(':') == -1) {
  6905. elem.attrs({ name: kv });
  6906. } else {
  6907. var k = kv.split(':', 2)[0];
  6908. elem.attrs({ name: k });
  6909. var v = kv.split(':', 2)[1];
  6910. v = SDPUtil.filter_special_chars(v);
  6911. elem.attrs({ value: v });
  6912. }
  6913. elem.up();
  6914. });
  6915. }
  6916. else
  6917. {
  6918. elem.up();
  6919. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  6920. elem.c('parameter');
  6921. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  6922. elem.up();
  6923. var msid = null;
  6924. if(mline.media == "audio")
  6925. {
  6926. msid = APP.RTC.localAudio.getId();
  6927. }
  6928. else
  6929. {
  6930. msid = APP.RTC.localVideo.getId();
  6931. }
  6932. if(msid != null)
  6933. {
  6934. msid = SDPUtil.filter_special_chars(msid);
  6935. elem.c('parameter');
  6936. elem.attrs({name: "msid", value:msid});
  6937. elem.up();
  6938. elem.c('parameter');
  6939. elem.attrs({name: "mslabel", value:msid});
  6940. elem.up();
  6941. elem.c('parameter');
  6942. elem.attrs({name: "label", value:msid});
  6943. elem.up();
  6944. }
  6945. }
  6946. elem.up();
  6947. // XEP-0339 handle ssrc-group attributes
  6948. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  6949. ssrc_group_lines.forEach(function(line) {
  6950. idx = line.indexOf(' ');
  6951. var semantics = line.substr(0, idx).substr(13);
  6952. var ssrcs = line.substr(14 + semantics.length).split(' ');
  6953. if (ssrcs.length != 0) {
  6954. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  6955. ssrcs.forEach(function(ssrc) {
  6956. elem.c('source', { ssrc: ssrc })
  6957. .up();
  6958. });
  6959. elem.up();
  6960. }
  6961. });
  6962. }
  6963. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  6964. elem.c('rtcp-mux').up();
  6965. }
  6966. // XEP-0293 -- map a=rtcp-fb:*
  6967. this.RtcpFbToJingle(i, elem, '*');
  6968. // XEP-0294
  6969. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  6970. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  6971. for (j = 0; j < lines.length; j++) {
  6972. tmp = SDPUtil.parse_extmap(lines[j]);
  6973. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  6974. uri: tmp.uri,
  6975. id: tmp.value });
  6976. if (tmp.hasOwnProperty('direction')) {
  6977. switch (tmp.direction) {
  6978. case 'sendonly':
  6979. elem.attrs({senders: 'responder'});
  6980. break;
  6981. case 'recvonly':
  6982. elem.attrs({senders: 'initiator'});
  6983. break;
  6984. case 'sendrecv':
  6985. elem.attrs({senders: 'both'});
  6986. break;
  6987. case 'inactive':
  6988. elem.attrs({senders: 'none'});
  6989. break;
  6990. }
  6991. }
  6992. // TODO: handle params
  6993. elem.up();
  6994. }
  6995. }
  6996. elem.up(); // end of description
  6997. }
  6998. // map ice-ufrag/pwd, dtls fingerprint, candidates
  6999. this.TransportToJingle(i, elem);
  7000. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  7001. elem.attrs({senders: 'both'});
  7002. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  7003. elem.attrs({senders: 'initiator'});
  7004. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  7005. elem.attrs({senders: 'responder'});
  7006. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  7007. elem.attrs({senders: 'none'});
  7008. }
  7009. if (mline.port == '0') {
  7010. // estos hack to reject an m-line
  7011. elem.attrs({senders: 'rejected'});
  7012. }
  7013. elem.up(); // end of content
  7014. }
  7015. elem.up();
  7016. return elem;
  7017. };
  7018. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  7019. var i = mediaindex;
  7020. var tmp;
  7021. var self = this;
  7022. elem.c('transport');
  7023. // XEP-0343 DTLS/SCTP
  7024. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  7025. {
  7026. var sctpmap = SDPUtil.find_line(
  7027. this.media[i], 'a=sctpmap:', self.session);
  7028. if (sctpmap)
  7029. {
  7030. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  7031. elem.c('sctpmap',
  7032. {
  7033. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  7034. number: sctpAttrs[0], /* SCTP port */
  7035. protocol: sctpAttrs[1], /* protocol */
  7036. });
  7037. // Optional stream count attribute
  7038. if (sctpAttrs.length > 2)
  7039. elem.attrs({ streams: sctpAttrs[2]});
  7040. elem.up();
  7041. }
  7042. }
  7043. // XEP-0320
  7044. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  7045. fingerprints.forEach(function(line) {
  7046. tmp = SDPUtil.parse_fingerprint(line);
  7047. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  7048. elem.c('fingerprint').t(tmp.fingerprint);
  7049. delete tmp.fingerprint;
  7050. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  7051. if (line) {
  7052. tmp.setup = line.substr(8);
  7053. }
  7054. elem.attrs(tmp);
  7055. elem.up(); // end of fingerprint
  7056. });
  7057. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  7058. if (tmp) {
  7059. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  7060. elem.attrs(tmp);
  7061. // XEP-0176
  7062. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  7063. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  7064. lines.forEach(function (line) {
  7065. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  7066. });
  7067. }
  7068. }
  7069. elem.up(); // end of transport
  7070. }
  7071. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  7072. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  7073. lines.forEach(function (line) {
  7074. var tmp = SDPUtil.parse_rtcpfb(line);
  7075. if (tmp.type == 'trr-int') {
  7076. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  7077. elem.up();
  7078. } else {
  7079. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  7080. if (tmp.params.length > 0) {
  7081. elem.attrs({'subtype': tmp.params[0]});
  7082. }
  7083. elem.up();
  7084. }
  7085. });
  7086. };
  7087. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  7088. var media = '';
  7089. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  7090. if (tmp.length) {
  7091. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  7092. if (tmp.attr('value')) {
  7093. media += tmp.attr('value');
  7094. } else {
  7095. media += '0';
  7096. }
  7097. media += '\r\n';
  7098. }
  7099. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  7100. tmp.each(function () {
  7101. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  7102. if ($(this).attr('subtype')) {
  7103. media += ' ' + $(this).attr('subtype');
  7104. }
  7105. media += '\r\n';
  7106. });
  7107. return media;
  7108. };
  7109. // construct an SDP from a jingle stanza
  7110. SDP.prototype.fromJingle = function (jingle) {
  7111. var self = this;
  7112. this.raw = 'v=0\r\n' +
  7113. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  7114. 's=-\r\n' +
  7115. 't=0 0\r\n';
  7116. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  7117. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  7118. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  7119. var contents = $(group).find('>content').map(function (idx, content) {
  7120. return content.getAttribute('name');
  7121. }).get();
  7122. if (contents.length > 0) {
  7123. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  7124. }
  7125. });
  7126. }
  7127. this.session = this.raw;
  7128. jingle.find('>content').each(function () {
  7129. var m = self.jingle2media($(this));
  7130. self.media.push(m);
  7131. });
  7132. // reconstruct msid-semantic -- apparently not necessary
  7133. /*
  7134. var msid = SDPUtil.parse_ssrc(this.raw);
  7135. if (msid.hasOwnProperty('mslabel')) {
  7136. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  7137. }
  7138. */
  7139. this.raw = this.session + this.media.join('');
  7140. };
  7141. // translate a jingle content element into an an SDP media part
  7142. SDP.prototype.jingle2media = function (content) {
  7143. var media = '',
  7144. desc = content.find('description'),
  7145. ssrc = desc.attr('ssrc'),
  7146. self = this,
  7147. tmp;
  7148. var sctp = content.find(
  7149. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  7150. tmp = { media: desc.attr('media') };
  7151. tmp.port = '1';
  7152. if (content.attr('senders') == 'rejected') {
  7153. // estos hack to reject an m-line.
  7154. tmp.port = '0';
  7155. }
  7156. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  7157. if (sctp.length)
  7158. tmp.proto = 'DTLS/SCTP';
  7159. else
  7160. tmp.proto = 'RTP/SAVPF';
  7161. } else {
  7162. tmp.proto = 'RTP/AVPF';
  7163. }
  7164. if (!sctp.length)
  7165. {
  7166. tmp.fmt = desc.find('payload-type').map(
  7167. function () { return this.getAttribute('id'); }).get();
  7168. media += SDPUtil.build_mline(tmp) + '\r\n';
  7169. }
  7170. else
  7171. {
  7172. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  7173. media += 'a=sctpmap:' + sctp.attr('number') +
  7174. ' ' + sctp.attr('protocol');
  7175. var streamCount = sctp.attr('streams');
  7176. if (streamCount)
  7177. media += ' ' + streamCount + '\r\n';
  7178. else
  7179. media += '\r\n';
  7180. }
  7181. media += 'c=IN IP4 0.0.0.0\r\n';
  7182. if (!sctp.length)
  7183. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  7184. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  7185. if (tmp.length) {
  7186. if (tmp.attr('ufrag')) {
  7187. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  7188. }
  7189. if (tmp.attr('pwd')) {
  7190. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  7191. }
  7192. tmp.find('>fingerprint').each(function () {
  7193. // FIXME: check namespace at some point
  7194. media += 'a=fingerprint:' + this.getAttribute('hash');
  7195. media += ' ' + $(this).text();
  7196. media += '\r\n';
  7197. if (this.getAttribute('setup')) {
  7198. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  7199. }
  7200. });
  7201. }
  7202. switch (content.attr('senders')) {
  7203. case 'initiator':
  7204. media += 'a=sendonly\r\n';
  7205. break;
  7206. case 'responder':
  7207. media += 'a=recvonly\r\n';
  7208. break;
  7209. case 'none':
  7210. media += 'a=inactive\r\n';
  7211. break;
  7212. case 'both':
  7213. media += 'a=sendrecv\r\n';
  7214. break;
  7215. }
  7216. media += 'a=mid:' + content.attr('name') + '\r\n';
  7217. // <description><rtcp-mux/></description>
  7218. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  7219. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  7220. if (desc.find('rtcp-mux').length) {
  7221. media += 'a=rtcp-mux\r\n';
  7222. }
  7223. if (desc.find('encryption').length) {
  7224. desc.find('encryption>crypto').each(function () {
  7225. media += 'a=crypto:' + this.getAttribute('tag');
  7226. media += ' ' + this.getAttribute('crypto-suite');
  7227. media += ' ' + this.getAttribute('key-params');
  7228. if (this.getAttribute('session-params')) {
  7229. media += ' ' + this.getAttribute('session-params');
  7230. }
  7231. media += '\r\n';
  7232. });
  7233. }
  7234. desc.find('payload-type').each(function () {
  7235. media += SDPUtil.build_rtpmap(this) + '\r\n';
  7236. if ($(this).find('>parameter').length) {
  7237. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  7238. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  7239. media += '\r\n';
  7240. }
  7241. // xep-0293
  7242. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  7243. });
  7244. // xep-0293
  7245. media += self.RtcpFbFromJingle(desc, '*');
  7246. // xep-0294
  7247. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  7248. tmp.each(function () {
  7249. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  7250. });
  7251. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  7252. media += SDPUtil.candidateFromJingle(this);
  7253. });
  7254. // XEP-0339 handle ssrc-group attributes
  7255. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  7256. var semantics = this.getAttribute('semantics');
  7257. var ssrcs = $(this).find('>source').map(function() {
  7258. return this.getAttribute('ssrc');
  7259. }).get();
  7260. if (ssrcs.length != 0) {
  7261. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  7262. }
  7263. });
  7264. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  7265. tmp.each(function () {
  7266. var ssrc = this.getAttribute('ssrc');
  7267. $(this).find('>parameter').each(function () {
  7268. var name = this.getAttribute('name');
  7269. var value = this.getAttribute('value');
  7270. value = SDPUtil.filter_special_chars(value);
  7271. media += 'a=ssrc:' + ssrc + ' ' + name;
  7272. if (value && value.length)
  7273. media += ':' + value;
  7274. media += '\r\n';
  7275. });
  7276. });
  7277. return media;
  7278. };
  7279. module.exports = SDP;
  7280. },{"./SDPUtil":29}],28:[function(require,module,exports){
  7281. var SDPUtil = require("./SDPUtil");
  7282. function SDPDiffer(mySDP, otherSDP) {
  7283. this.mySDP = mySDP;
  7284. this.otherSDP = otherSDP;
  7285. }
  7286. /**
  7287. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  7288. * @param otherSdp the other SDP to check ssrc with.
  7289. */
  7290. SDPDiffer.prototype.getNewMedia = function() {
  7291. // this could be useful in Array.prototype.
  7292. function arrayEquals(array) {
  7293. // if the other array is a falsy value, return
  7294. if (!array)
  7295. return false;
  7296. // compare lengths - can save a lot of time
  7297. if (this.length != array.length)
  7298. return false;
  7299. for (var i = 0, l=this.length; i < l; i++) {
  7300. // Check if we have nested arrays
  7301. if (this[i] instanceof Array && array[i] instanceof Array) {
  7302. // recurse into the nested arrays
  7303. if (!this[i].equals(array[i]))
  7304. return false;
  7305. }
  7306. else if (this[i] != array[i]) {
  7307. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  7308. return false;
  7309. }
  7310. }
  7311. return true;
  7312. }
  7313. var myMedias = this.mySDP.getMediaSsrcMap();
  7314. var othersMedias = this.otherSDP.getMediaSsrcMap();
  7315. var newMedia = {};
  7316. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  7317. var myMedia = myMedias[othersMediaIdx];
  7318. var othersMedia = othersMedias[othersMediaIdx];
  7319. if(!myMedia && othersMedia) {
  7320. // Add whole channel
  7321. newMedia[othersMediaIdx] = othersMedia;
  7322. return;
  7323. }
  7324. // Look for new ssrcs accross the channel
  7325. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  7326. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  7327. // Allocate channel if we've found ssrc that doesn't exist in our channel
  7328. if(!newMedia[othersMediaIdx]){
  7329. newMedia[othersMediaIdx] = {
  7330. mediaindex: othersMedia.mediaindex,
  7331. mid: othersMedia.mid,
  7332. ssrcs: {},
  7333. ssrcGroups: []
  7334. };
  7335. }
  7336. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  7337. }
  7338. });
  7339. // Look for new ssrc groups across the channels
  7340. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  7341. // try to match the other ssrc-group with an ssrc-group of ours
  7342. var matched = false;
  7343. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  7344. var mySsrcGroup = myMedia.ssrcGroups[i];
  7345. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  7346. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  7347. matched = true;
  7348. break;
  7349. }
  7350. }
  7351. if (!matched) {
  7352. // Allocate channel if we've found an ssrc-group that doesn't
  7353. // exist in our channel
  7354. if(!newMedia[othersMediaIdx]){
  7355. newMedia[othersMediaIdx] = {
  7356. mediaindex: othersMedia.mediaindex,
  7357. mid: othersMedia.mid,
  7358. ssrcs: {},
  7359. ssrcGroups: []
  7360. };
  7361. }
  7362. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  7363. }
  7364. });
  7365. });
  7366. return newMedia;
  7367. };
  7368. /**
  7369. * Sends SSRC update IQ.
  7370. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  7371. * @param sid session identifier that will be put into the IQ.
  7372. * @param initiator initiator identifier.
  7373. * @param toJid destination Jid
  7374. * @param isAdd indicates if this is remove or add operation.
  7375. */
  7376. SDPDiffer.prototype.toJingle = function(modify) {
  7377. var sdpMediaSsrcs = this.getNewMedia();
  7378. var self = this;
  7379. // FIXME: only announce video ssrcs since we mix audio and dont need
  7380. // the audio ssrcs therefore
  7381. var modified = false;
  7382. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  7383. modified = true;
  7384. var media = sdpMediaSsrcs[mediaindex];
  7385. modify.c('content', {name: media.mid});
  7386. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  7387. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  7388. // generate sources from lines
  7389. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  7390. var mediaSsrc = media.ssrcs[ssrcNum];
  7391. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7392. modify.attrs({ssrc: mediaSsrc.ssrc});
  7393. // iterate over ssrc lines
  7394. mediaSsrc.lines.forEach(function (line) {
  7395. var idx = line.indexOf(' ');
  7396. var kv = line.substr(idx + 1);
  7397. modify.c('parameter');
  7398. if (kv.indexOf(':') == -1) {
  7399. modify.attrs({ name: kv });
  7400. } else {
  7401. var nv = kv.split(':', 2);
  7402. var name = nv[0];
  7403. var value = SDPUtil.filter_special_chars(nv[1]);
  7404. modify.attrs({ name: name });
  7405. modify.attrs({ value: value });
  7406. }
  7407. modify.up(); // end of parameter
  7408. });
  7409. modify.up(); // end of source
  7410. });
  7411. // generate source groups from lines
  7412. media.ssrcGroups.forEach(function(ssrcGroup) {
  7413. if (ssrcGroup.ssrcs.length != 0) {
  7414. modify.c('ssrc-group', {
  7415. semantics: ssrcGroup.semantics,
  7416. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  7417. });
  7418. ssrcGroup.ssrcs.forEach(function (ssrc) {
  7419. modify.c('source', { ssrc: ssrc })
  7420. .up(); // end of source
  7421. });
  7422. modify.up(); // end of ssrc-group
  7423. }
  7424. });
  7425. modify.up(); // end of description
  7426. modify.up(); // end of content
  7427. });
  7428. return modified;
  7429. };
  7430. module.exports = SDPDiffer;
  7431. },{"./SDPUtil":29}],29:[function(require,module,exports){
  7432. SDPUtil = {
  7433. filter_special_chars: function (text) {
  7434. return text.replace(/[\\\/\{,\}\+]/g, "");
  7435. },
  7436. iceparams: function (mediadesc, sessiondesc) {
  7437. var data = null;
  7438. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  7439. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  7440. data = {
  7441. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  7442. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  7443. };
  7444. }
  7445. return data;
  7446. },
  7447. parse_iceufrag: function (line) {
  7448. return line.substring(12);
  7449. },
  7450. build_iceufrag: function (frag) {
  7451. return 'a=ice-ufrag:' + frag;
  7452. },
  7453. parse_icepwd: function (line) {
  7454. return line.substring(10);
  7455. },
  7456. build_icepwd: function (pwd) {
  7457. return 'a=ice-pwd:' + pwd;
  7458. },
  7459. parse_mid: function (line) {
  7460. return line.substring(6);
  7461. },
  7462. parse_mline: function (line) {
  7463. var parts = line.substring(2).split(' '),
  7464. data = {};
  7465. data.media = parts.shift();
  7466. data.port = parts.shift();
  7467. data.proto = parts.shift();
  7468. if (parts[parts.length - 1] === '') { // trailing whitespace
  7469. parts.pop();
  7470. }
  7471. data.fmt = parts;
  7472. return data;
  7473. },
  7474. build_mline: function (mline) {
  7475. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  7476. },
  7477. parse_rtpmap: function (line) {
  7478. var parts = line.substring(9).split(' '),
  7479. data = {};
  7480. data.id = parts.shift();
  7481. parts = parts[0].split('/');
  7482. data.name = parts.shift();
  7483. data.clockrate = parts.shift();
  7484. data.channels = parts.length ? parts.shift() : '1';
  7485. return data;
  7486. },
  7487. /**
  7488. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  7489. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  7490. * @returns [SCTP port number, protocol, streams]
  7491. */
  7492. parse_sctpmap: function (line)
  7493. {
  7494. var parts = line.substring(10).split(' ');
  7495. var sctpPort = parts[0];
  7496. var protocol = parts[1];
  7497. // Stream count is optional
  7498. var streamCount = parts.length > 2 ? parts[2] : null;
  7499. return [sctpPort, protocol, streamCount];// SCTP port
  7500. },
  7501. build_rtpmap: function (el) {
  7502. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  7503. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  7504. line += '/' + el.getAttribute('channels');
  7505. }
  7506. return line;
  7507. },
  7508. parse_crypto: function (line) {
  7509. var parts = line.substring(9).split(' '),
  7510. data = {};
  7511. data.tag = parts.shift();
  7512. data['crypto-suite'] = parts.shift();
  7513. data['key-params'] = parts.shift();
  7514. if (parts.length) {
  7515. data['session-params'] = parts.join(' ');
  7516. }
  7517. return data;
  7518. },
  7519. parse_fingerprint: function (line) { // RFC 4572
  7520. var parts = line.substring(14).split(' '),
  7521. data = {};
  7522. data.hash = parts.shift();
  7523. data.fingerprint = parts.shift();
  7524. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  7525. return data;
  7526. },
  7527. parse_fmtp: function (line) {
  7528. var parts = line.split(' '),
  7529. i, key, value,
  7530. data = [];
  7531. parts.shift();
  7532. parts = parts.join(' ').split(';');
  7533. for (i = 0; i < parts.length; i++) {
  7534. key = parts[i].split('=')[0];
  7535. while (key.length && key[0] == ' ') {
  7536. key = key.substring(1);
  7537. }
  7538. value = parts[i].split('=')[1];
  7539. if (key && value) {
  7540. data.push({name: key, value: value});
  7541. } else if (key) {
  7542. // rfc 4733 (DTMF) style stuff
  7543. data.push({name: '', value: key});
  7544. }
  7545. }
  7546. return data;
  7547. },
  7548. parse_icecandidate: function (line) {
  7549. var candidate = {},
  7550. elems = line.split(' ');
  7551. candidate.foundation = elems[0].substring(12);
  7552. candidate.component = elems[1];
  7553. candidate.protocol = elems[2].toLowerCase();
  7554. candidate.priority = elems[3];
  7555. candidate.ip = elems[4];
  7556. candidate.port = elems[5];
  7557. // elems[6] => "typ"
  7558. candidate.type = elems[7];
  7559. candidate.generation = 0; // default value, may be overwritten below
  7560. for (var i = 8; i < elems.length; i += 2) {
  7561. switch (elems[i]) {
  7562. case 'raddr':
  7563. candidate['rel-addr'] = elems[i + 1];
  7564. break;
  7565. case 'rport':
  7566. candidate['rel-port'] = elems[i + 1];
  7567. break;
  7568. case 'generation':
  7569. candidate.generation = elems[i + 1];
  7570. break;
  7571. case 'tcptype':
  7572. candidate.tcptype = elems[i + 1];
  7573. break;
  7574. default: // TODO
  7575. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  7576. }
  7577. }
  7578. candidate.network = '1';
  7579. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  7580. return candidate;
  7581. },
  7582. build_icecandidate: function (cand) {
  7583. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  7584. line += ' ';
  7585. switch (cand.type) {
  7586. case 'srflx':
  7587. case 'prflx':
  7588. case 'relay':
  7589. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  7590. line += 'raddr';
  7591. line += ' ';
  7592. line += cand['rel-addr'];
  7593. line += ' ';
  7594. line += 'rport';
  7595. line += ' ';
  7596. line += cand['rel-port'];
  7597. line += ' ';
  7598. }
  7599. break;
  7600. }
  7601. if (cand.hasOwnAttribute('tcptype')) {
  7602. line += 'tcptype';
  7603. line += ' ';
  7604. line += cand.tcptype;
  7605. line += ' ';
  7606. }
  7607. line += 'generation';
  7608. line += ' ';
  7609. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  7610. return line;
  7611. },
  7612. parse_ssrc: function (desc) {
  7613. // proprietary mapping of a=ssrc lines
  7614. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  7615. // and parse according to that
  7616. var lines = desc.split('\r\n'),
  7617. data = {};
  7618. for (var i = 0; i < lines.length; i++) {
  7619. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  7620. var idx = lines[i].indexOf(' ');
  7621. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  7622. }
  7623. }
  7624. return data;
  7625. },
  7626. parse_rtcpfb: function (line) {
  7627. var parts = line.substr(10).split(' ');
  7628. var data = {};
  7629. data.pt = parts.shift();
  7630. data.type = parts.shift();
  7631. data.params = parts;
  7632. return data;
  7633. },
  7634. parse_extmap: function (line) {
  7635. var parts = line.substr(9).split(' ');
  7636. var data = {};
  7637. data.value = parts.shift();
  7638. if (data.value.indexOf('/') != -1) {
  7639. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  7640. data.value = data.value.substr(0, data.value.indexOf('/'));
  7641. } else {
  7642. data.direction = 'both';
  7643. }
  7644. data.uri = parts.shift();
  7645. data.params = parts;
  7646. return data;
  7647. },
  7648. find_line: function (haystack, needle, sessionpart) {
  7649. var lines = haystack.split('\r\n');
  7650. for (var i = 0; i < lines.length; i++) {
  7651. if (lines[i].substring(0, needle.length) == needle) {
  7652. return lines[i];
  7653. }
  7654. }
  7655. if (!sessionpart) {
  7656. return false;
  7657. }
  7658. // search session part
  7659. lines = sessionpart.split('\r\n');
  7660. for (var j = 0; j < lines.length; j++) {
  7661. if (lines[j].substring(0, needle.length) == needle) {
  7662. return lines[j];
  7663. }
  7664. }
  7665. return false;
  7666. },
  7667. find_lines: function (haystack, needle, sessionpart) {
  7668. var lines = haystack.split('\r\n'),
  7669. needles = [];
  7670. for (var i = 0; i < lines.length; i++) {
  7671. if (lines[i].substring(0, needle.length) == needle)
  7672. needles.push(lines[i]);
  7673. }
  7674. if (needles.length || !sessionpart) {
  7675. return needles;
  7676. }
  7677. // search session part
  7678. lines = sessionpart.split('\r\n');
  7679. for (var j = 0; j < lines.length; j++) {
  7680. if (lines[j].substring(0, needle.length) == needle) {
  7681. needles.push(lines[j]);
  7682. }
  7683. }
  7684. return needles;
  7685. },
  7686. candidateToJingle: function (line) {
  7687. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  7688. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  7689. if (line.indexOf('candidate:') === 0) {
  7690. line = 'a=' + line;
  7691. } else if (line.substring(0, 12) != 'a=candidate:') {
  7692. console.log('parseCandidate called with a line that is not a candidate line');
  7693. console.log(line);
  7694. return null;
  7695. }
  7696. if (line.substring(line.length - 2) == '\r\n') // chomp it
  7697. line = line.substring(0, line.length - 2);
  7698. var candidate = {},
  7699. elems = line.split(' '),
  7700. i;
  7701. if (elems[6] != 'typ') {
  7702. console.log('did not find typ in the right place');
  7703. console.log(line);
  7704. return null;
  7705. }
  7706. candidate.foundation = elems[0].substring(12);
  7707. candidate.component = elems[1];
  7708. candidate.protocol = elems[2].toLowerCase();
  7709. candidate.priority = elems[3];
  7710. candidate.ip = elems[4];
  7711. candidate.port = elems[5];
  7712. // elems[6] => "typ"
  7713. candidate.type = elems[7];
  7714. candidate.generation = '0'; // default, may be overwritten below
  7715. for (i = 8; i < elems.length; i += 2) {
  7716. switch (elems[i]) {
  7717. case 'raddr':
  7718. candidate['rel-addr'] = elems[i + 1];
  7719. break;
  7720. case 'rport':
  7721. candidate['rel-port'] = elems[i + 1];
  7722. break;
  7723. case 'generation':
  7724. candidate.generation = elems[i + 1];
  7725. break;
  7726. case 'tcptype':
  7727. candidate.tcptype = elems[i + 1];
  7728. break;
  7729. default: // TODO
  7730. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  7731. }
  7732. }
  7733. candidate.network = '1';
  7734. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  7735. return candidate;
  7736. },
  7737. candidateFromJingle: function (cand) {
  7738. var line = 'a=candidate:';
  7739. line += cand.getAttribute('foundation');
  7740. line += ' ';
  7741. line += cand.getAttribute('component');
  7742. line += ' ';
  7743. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  7744. line += ' ';
  7745. line += cand.getAttribute('priority');
  7746. line += ' ';
  7747. line += cand.getAttribute('ip');
  7748. line += ' ';
  7749. line += cand.getAttribute('port');
  7750. line += ' ';
  7751. line += 'typ';
  7752. line += ' ' + cand.getAttribute('type');
  7753. line += ' ';
  7754. switch (cand.getAttribute('type')) {
  7755. case 'srflx':
  7756. case 'prflx':
  7757. case 'relay':
  7758. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  7759. line += 'raddr';
  7760. line += ' ';
  7761. line += cand.getAttribute('rel-addr');
  7762. line += ' ';
  7763. line += 'rport';
  7764. line += ' ';
  7765. line += cand.getAttribute('rel-port');
  7766. line += ' ';
  7767. }
  7768. break;
  7769. }
  7770. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  7771. line += 'tcptype';
  7772. line += ' ';
  7773. line += cand.getAttribute('tcptype');
  7774. line += ' ';
  7775. }
  7776. line += 'generation';
  7777. line += ' ';
  7778. line += cand.getAttribute('generation') || '0';
  7779. return line + '\r\n';
  7780. }
  7781. };
  7782. module.exports = SDPUtil;
  7783. },{}],30:[function(require,module,exports){
  7784. var RTC = require('../RTC/RTC');
  7785. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  7786. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7787. var SSRCReplacement = require("./LocalSSRCReplacement");
  7788. function TraceablePeerConnection(ice_config, constraints, session) {
  7789. var self = this;
  7790. this.session = session;
  7791. var RTCPeerConnectionType = null;
  7792. if (RTCBrowserType.isFirefox()) {
  7793. RTCPeerConnectionType = mozRTCPeerConnection;
  7794. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  7795. RTCPeerConnectionType = RTCPeerConnection;
  7796. } else {
  7797. RTCPeerConnectionType = webkitRTCPeerConnection;
  7798. }
  7799. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  7800. this.updateLog = [];
  7801. this.stats = {};
  7802. this.statsinterval = null;
  7803. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  7804. var Interop = require('sdp-interop').Interop;
  7805. this.interop = new Interop();
  7806. var Simulcast = require('sdp-simulcast');
  7807. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  7808. // override as desired
  7809. this.trace = function (what, info) {
  7810. /*console.warn('WTRACE', what, info);
  7811. if (info && RTCBrowserType.isIExplorer()) {
  7812. if (info.length > 1024) {
  7813. console.warn('WTRACE', what, info.substr(1024));
  7814. }
  7815. if (info.length > 2048) {
  7816. console.warn('WTRACE', what, info.substr(2048));
  7817. }
  7818. }*/
  7819. self.updateLog.push({
  7820. time: new Date(),
  7821. type: what,
  7822. value: info || ""
  7823. });
  7824. };
  7825. this.onicecandidate = null;
  7826. this.peerconnection.onicecandidate = function (event) {
  7827. // FIXME: this causes stack overflow with Temasys Plugin
  7828. if (!RTCBrowserType.isTemasysPluginUsed())
  7829. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  7830. if (self.onicecandidate !== null) {
  7831. self.onicecandidate(event);
  7832. }
  7833. };
  7834. this.onaddstream = null;
  7835. this.peerconnection.onaddstream = function (event) {
  7836. self.trace('onaddstream', event.stream.id);
  7837. if (self.onaddstream !== null) {
  7838. self.onaddstream(event);
  7839. }
  7840. };
  7841. this.onremovestream = null;
  7842. this.peerconnection.onremovestream = function (event) {
  7843. self.trace('onremovestream', event.stream.id);
  7844. if (self.onremovestream !== null) {
  7845. self.onremovestream(event);
  7846. }
  7847. };
  7848. this.onsignalingstatechange = null;
  7849. this.peerconnection.onsignalingstatechange = function (event) {
  7850. self.trace('onsignalingstatechange', self.signalingState);
  7851. if (self.onsignalingstatechange !== null) {
  7852. self.onsignalingstatechange(event);
  7853. }
  7854. };
  7855. this.oniceconnectionstatechange = null;
  7856. this.peerconnection.oniceconnectionstatechange = function (event) {
  7857. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  7858. if (self.oniceconnectionstatechange !== null) {
  7859. self.oniceconnectionstatechange(event);
  7860. }
  7861. };
  7862. this.onnegotiationneeded = null;
  7863. this.peerconnection.onnegotiationneeded = function (event) {
  7864. self.trace('onnegotiationneeded');
  7865. if (self.onnegotiationneeded !== null) {
  7866. self.onnegotiationneeded(event);
  7867. }
  7868. };
  7869. self.ondatachannel = null;
  7870. this.peerconnection.ondatachannel = function (event) {
  7871. self.trace('ondatachannel', event);
  7872. if (self.ondatachannel !== null) {
  7873. self.ondatachannel(event);
  7874. }
  7875. };
  7876. // XXX: do all non-firefox browsers which we support also support this?
  7877. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  7878. this.statsinterval = window.setInterval(function() {
  7879. self.peerconnection.getStats(function(stats) {
  7880. var results = stats.result();
  7881. var now = new Date();
  7882. for (var i = 0; i < results.length; ++i) {
  7883. results[i].names().forEach(function (name) {
  7884. var id = results[i].id + '-' + name;
  7885. if (!self.stats[id]) {
  7886. self.stats[id] = {
  7887. startTime: now,
  7888. endTime: now,
  7889. values: [],
  7890. times: []
  7891. };
  7892. }
  7893. self.stats[id].values.push(results[i].stat(name));
  7894. self.stats[id].times.push(now.getTime());
  7895. if (self.stats[id].values.length > self.maxstats) {
  7896. self.stats[id].values.shift();
  7897. self.stats[id].times.shift();
  7898. }
  7899. self.stats[id].endTime = now;
  7900. });
  7901. }
  7902. });
  7903. }, 1000);
  7904. }
  7905. }
  7906. /**
  7907. * Returns a string representation of a SessionDescription object.
  7908. */
  7909. var dumpSDP = function(description) {
  7910. if (typeof description === 'undefined' || description == null) {
  7911. return '';
  7912. }
  7913. return 'type: ' + description.type + '\r\n' + description.sdp;
  7914. };
  7915. /**
  7916. * Takes a SessionDescription object and returns a "normalized" version.
  7917. * Currently it only takes care of ordering the a=ssrc lines.
  7918. */
  7919. var normalizePlanB = function(desc) {
  7920. if (typeof desc !== 'object' || desc === null ||
  7921. typeof desc.sdp !== 'string') {
  7922. console.warn('An empty description was passed as an argument.');
  7923. return desc;
  7924. }
  7925. var transform = require('sdp-transform');
  7926. var session = transform.parse(desc.sdp);
  7927. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  7928. Array.isArray(session.media)) {
  7929. session.media.forEach(function (mLine) {
  7930. // Chrome appears to be picky about the order in which a=ssrc lines
  7931. // are listed in an m-line when rtx is enabled (and thus there are
  7932. // a=ssrc-group lines with FID semantics). Specifically if we have
  7933. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  7934. // the "a=ssrc:S1" lines, SRD fails.
  7935. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  7936. // first.
  7937. var firstSsrcs = [];
  7938. var newSsrcLines = [];
  7939. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  7940. mLine.ssrcGroups.forEach(function (group) {
  7941. if (typeof group.semantics !== 'undefined' &&
  7942. group.semantics === 'FID') {
  7943. if (typeof group.ssrcs !== 'undefined') {
  7944. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  7945. }
  7946. }
  7947. });
  7948. }
  7949. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  7950. for (var i = 0; i<mLine.ssrcs.length; i++){
  7951. if (typeof mLine.ssrcs[i] === 'object'
  7952. && typeof mLine.ssrcs[i].id !== 'undefined'
  7953. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  7954. newSsrcLines.push(mLine.ssrcs[i]);
  7955. delete mLine.ssrcs[i];
  7956. }
  7957. }
  7958. for (var i = 0; i<mLine.ssrcs.length; i++){
  7959. if (typeof mLine.ssrcs[i] !== 'undefined') {
  7960. newSsrcLines.push(mLine.ssrcs[i]);
  7961. }
  7962. }
  7963. mLine.ssrcs = newSsrcLines;
  7964. }
  7965. });
  7966. }
  7967. var resStr = transform.write(session);
  7968. return new RTCSessionDescription({
  7969. type: desc.type,
  7970. sdp: resStr
  7971. });
  7972. };
  7973. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  7974. TraceablePeerConnection.prototype.__defineGetter__(
  7975. 'signalingState',
  7976. function() { return this.peerconnection.signalingState; });
  7977. TraceablePeerConnection.prototype.__defineGetter__(
  7978. 'iceConnectionState',
  7979. function() { return this.peerconnection.iceConnectionState; });
  7980. TraceablePeerConnection.prototype.__defineGetter__(
  7981. 'localDescription',
  7982. function() {
  7983. var desc = this.peerconnection.localDescription;
  7984. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  7985. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  7986. // if we're running on FF, transform to Plan B first.
  7987. if (RTCBrowserType.usesUnifiedPlan()) {
  7988. desc = this.interop.toPlanB(desc);
  7989. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  7990. }
  7991. return desc;
  7992. });
  7993. TraceablePeerConnection.prototype.__defineGetter__(
  7994. 'remoteDescription',
  7995. function() {
  7996. var desc = this.peerconnection.remoteDescription;
  7997. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  7998. // if we're running on FF, transform to Plan B first.
  7999. if (RTCBrowserType.usesUnifiedPlan()) {
  8000. desc = this.interop.toPlanB(desc);
  8001. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  8002. }
  8003. return desc;
  8004. });
  8005. }
  8006. TraceablePeerConnection.prototype.addStream = function (stream) {
  8007. this.trace('addStream', stream.id);
  8008. try
  8009. {
  8010. this.peerconnection.addStream(stream);
  8011. }
  8012. catch (e)
  8013. {
  8014. console.error(e);
  8015. }
  8016. };
  8017. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  8018. this.trace('removeStream', stream.id);
  8019. if(stopStreams) {
  8020. stream.getAudioTracks().forEach(function (track) {
  8021. // stop() not supported with IE
  8022. if (track.stop) {
  8023. track.stop();
  8024. }
  8025. });
  8026. stream.getVideoTracks().forEach(function (track) {
  8027. // stop() not supported with IE
  8028. if (track.stop) {
  8029. track.stop();
  8030. }
  8031. });
  8032. if (stream.stop) {
  8033. stream.stop();
  8034. }
  8035. }
  8036. try {
  8037. // FF doesn't support this yet.
  8038. if (this.peerconnection.removeStream)
  8039. this.peerconnection.removeStream(stream);
  8040. } catch (e) {
  8041. console.error(e);
  8042. }
  8043. };
  8044. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  8045. this.trace('createDataChannel', label, opts);
  8046. return this.peerconnection.createDataChannel(label, opts);
  8047. };
  8048. TraceablePeerConnection.prototype.setLocalDescription
  8049. = function (description, successCallback, failureCallback) {
  8050. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  8051. // if we're running on FF, transform to Plan A first.
  8052. if (RTCBrowserType.usesUnifiedPlan()) {
  8053. description = this.interop.toUnifiedPlan(description);
  8054. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  8055. }
  8056. var self = this;
  8057. this.peerconnection.setLocalDescription(description,
  8058. function () {
  8059. self.trace('setLocalDescriptionOnSuccess');
  8060. successCallback();
  8061. },
  8062. function (err) {
  8063. self.trace('setLocalDescriptionOnFailure', err);
  8064. failureCallback(err);
  8065. }
  8066. );
  8067. /*
  8068. if (this.statsinterval === null && this.maxstats > 0) {
  8069. // start gathering stats
  8070. }
  8071. */
  8072. };
  8073. TraceablePeerConnection.prototype.setRemoteDescription
  8074. = function (description, successCallback, failureCallback) {
  8075. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  8076. // TODO the focus should squeze or explode the remote simulcast
  8077. description = this.simulcast.mungeRemoteDescription(description);
  8078. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  8079. // if we're running on FF, transform to Plan A first.
  8080. if (RTCBrowserType.usesUnifiedPlan()) {
  8081. description = this.interop.toUnifiedPlan(description);
  8082. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  8083. }
  8084. if (RTCBrowserType.usesPlanB()) {
  8085. description = normalizePlanB(description);
  8086. }
  8087. var self = this;
  8088. this.peerconnection.setRemoteDescription(description,
  8089. function () {
  8090. self.trace('setRemoteDescriptionOnSuccess');
  8091. successCallback();
  8092. },
  8093. function (err) {
  8094. self.trace('setRemoteDescriptionOnFailure', err);
  8095. failureCallback(err);
  8096. }
  8097. );
  8098. /*
  8099. if (this.statsinterval === null && this.maxstats > 0) {
  8100. // start gathering stats
  8101. }
  8102. */
  8103. };
  8104. TraceablePeerConnection.prototype.close = function () {
  8105. this.trace('stop');
  8106. if (this.statsinterval !== null) {
  8107. window.clearInterval(this.statsinterval);
  8108. this.statsinterval = null;
  8109. }
  8110. this.peerconnection.close();
  8111. };
  8112. TraceablePeerConnection.prototype.createOffer
  8113. = function (successCallback, failureCallback, constraints) {
  8114. var self = this;
  8115. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  8116. this.peerconnection.createOffer(
  8117. function (offer) {
  8118. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  8119. // NOTE this is not tested because in meet the focus generates the
  8120. // offer.
  8121. // if we're running on FF, transform to Plan B first.
  8122. if (RTCBrowserType.usesUnifiedPlan()) {
  8123. offer = self.interop.toPlanB(offer);
  8124. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  8125. }
  8126. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  8127. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  8128. offer = self.simulcast.mungeLocalDescription(offer);
  8129. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  8130. }
  8131. successCallback(offer);
  8132. },
  8133. function(err) {
  8134. self.trace('createOfferOnFailure', err);
  8135. failureCallback(err);
  8136. },
  8137. constraints
  8138. );
  8139. };
  8140. TraceablePeerConnection.prototype.createAnswer
  8141. = function (successCallback, failureCallback, constraints) {
  8142. var self = this;
  8143. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  8144. this.peerconnection.createAnswer(
  8145. function (answer) {
  8146. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  8147. // if we're running on FF, transform to Plan A first.
  8148. if (RTCBrowserType.usesUnifiedPlan()) {
  8149. answer = self.interop.toPlanB(answer);
  8150. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  8151. }
  8152. // munge local video SSRC
  8153. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  8154. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  8155. answer = self.simulcast.mungeLocalDescription(answer);
  8156. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  8157. }
  8158. successCallback(answer);
  8159. },
  8160. function(err) {
  8161. self.trace('createAnswerOnFailure', err);
  8162. failureCallback(err);
  8163. },
  8164. constraints
  8165. );
  8166. };
  8167. TraceablePeerConnection.prototype.addIceCandidate
  8168. = function (candidate, successCallback, failureCallback) {
  8169. //var self = this;
  8170. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  8171. this.peerconnection.addIceCandidate(candidate);
  8172. /* maybe later
  8173. this.peerconnection.addIceCandidate(candidate,
  8174. function () {
  8175. self.trace('addIceCandidateOnSuccess');
  8176. successCallback();
  8177. },
  8178. function (err) {
  8179. self.trace('addIceCandidateOnFailure', err);
  8180. failureCallback(err);
  8181. }
  8182. );
  8183. */
  8184. };
  8185. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  8186. // TODO: Is this the correct way to handle Opera, Temasys?
  8187. if (RTCBrowserType.isFirefox()) {
  8188. // ignore for now...
  8189. if(!errback)
  8190. errback = function () {};
  8191. this.peerconnection.getStats(null, callback, errback);
  8192. } else {
  8193. this.peerconnection.getStats(callback);
  8194. }
  8195. };
  8196. module.exports = TraceablePeerConnection;
  8197. },{"../../service/xmpp/XMPPEvents":83,"../RTC/RTC":13,"../RTC/RTCBrowserType.js":14,"./LocalSSRCReplacement":26,"sdp-interop":59,"sdp-simulcast":66,"sdp-transform":73}],31:[function(require,module,exports){
  8198. /* global $, $iq, APP, config, messageHandler,
  8199. roomName, sessionTerminated, Strophe, Util */
  8200. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8201. var Settings = require("../settings/Settings");
  8202. var AuthenticationEvents
  8203. = require("../../service/authentication/AuthenticationEvents");
  8204. function createExpBackoffTimer(step) {
  8205. var count = 1;
  8206. return function (reset) {
  8207. // Reset call
  8208. if (reset) {
  8209. count = 1;
  8210. return;
  8211. }
  8212. // Calculate next timeout
  8213. var timeout = Math.pow(2, count - 1);
  8214. count += 1;
  8215. return timeout * step;
  8216. };
  8217. }
  8218. function Moderator(roomName, xmpp, emitter) {
  8219. this.roomName = roomName;
  8220. this.xmppService = xmpp;
  8221. this.getNextTimeout = createExpBackoffTimer(1000);
  8222. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  8223. // External authentication stuff
  8224. this.externalAuthEnabled = false;
  8225. this.settings = new Settings(roomName);
  8226. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  8227. // it will be enabled automatically if focus detects the component through
  8228. // service discovery.
  8229. this.sipGatewayEnabled = this.xmppService.options.hosts.call_control !== undefined;
  8230. this.eventEmitter = emitter;
  8231. this.connection = this.xmppService.connection;
  8232. this.focusUserJid;
  8233. //FIXME:
  8234. // Message listener that talks to POPUP window
  8235. function listener(event) {
  8236. if (event.data && event.data.sessionId) {
  8237. if (event.origin !== window.location.origin) {
  8238. console.warn("Ignoring sessionId from different origin: " +
  8239. event.origin);
  8240. return;
  8241. }
  8242. localStorage.setItem('sessionId', event.data.sessionId);
  8243. // After popup is closed we will authenticate
  8244. }
  8245. }
  8246. // Register
  8247. if (window.addEventListener) {
  8248. window.addEventListener("message", listener, false);
  8249. } else {
  8250. window.attachEvent("onmessage", listener);
  8251. }
  8252. }
  8253. Moderator.prototype.isExternalAuthEnabled = function () {
  8254. return this.externalAuthEnabled;
  8255. };
  8256. Moderator.prototype.isSipGatewayEnabled = function () {
  8257. return this.sipGatewayEnabled;
  8258. };
  8259. Moderator.prototype.onMucMemberLeft = function (jid) {
  8260. console.info("Someone left is it focus ? " + jid);
  8261. var resource = Strophe.getResourceFromJid(jid);
  8262. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  8263. console.info(
  8264. "Focus has left the room - leaving conference");
  8265. //hangUp();
  8266. // We'd rather reload to have everything re-initialized
  8267. //FIXME: show some message before reload
  8268. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  8269. }
  8270. };
  8271. Moderator.prototype.setFocusUserJid = function (focusJid) {
  8272. if (!this.focusUserJid) {
  8273. this.focusUserJid = focusJid;
  8274. console.info("Focus jid set to: " + this.focusUserJid);
  8275. }
  8276. };
  8277. Moderator.prototype.getFocusUserJid = function () {
  8278. return this.focusUserJid;
  8279. };
  8280. Moderator.prototype.getFocusComponent = function () {
  8281. // Get focus component address
  8282. var focusComponent = this.xmppService.options.hosts.focus;
  8283. // If not specified use default: 'focus.domain'
  8284. if (!focusComponent) {
  8285. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  8286. }
  8287. return focusComponent;
  8288. };
  8289. Moderator.prototype.createConferenceIq = function () {
  8290. // Generate create conference IQ
  8291. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  8292. // Session Id used for authentication
  8293. var sessionId = localStorage.getItem('sessionId');
  8294. var machineUID = this.settings.getSettings().uid;
  8295. console.info(
  8296. "Session ID: " + sessionId + " machine UID: " + machineUID);
  8297. elem.c('conference', {
  8298. xmlns: 'http://jitsi.org/protocol/focus',
  8299. room: this.roomName,
  8300. 'machine-uid': machineUID
  8301. });
  8302. if (sessionId) {
  8303. elem.attrs({ 'session-id': sessionId});
  8304. }
  8305. if (this.xmppService.options.hosts.bridge !== undefined) {
  8306. elem.c(
  8307. 'property',
  8308. {name: 'bridge',value: this.xmppService.options.hosts.bridge})
  8309. .up();
  8310. }
  8311. // Tell the focus we have Jigasi configured
  8312. if (this.xmppService.options.hosts.call_control !== undefined) {
  8313. elem.c(
  8314. 'property',
  8315. {name: 'call_control',value: this.xmppService.options.hosts.call_control})
  8316. .up();
  8317. }
  8318. if (this.xmppService.options.channelLastN !== undefined) {
  8319. elem.c(
  8320. 'property',
  8321. {name: 'channelLastN',value: this.xmppService.options.channelLastN})
  8322. .up();
  8323. }
  8324. if (this.xmppService.options.adaptiveLastN !== undefined) {
  8325. elem.c(
  8326. 'property',
  8327. {name: 'adaptiveLastN',value: this.xmppService.options.adaptiveLastN})
  8328. .up();
  8329. }
  8330. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  8331. elem.c(
  8332. 'property',
  8333. {name: 'adaptiveSimulcast',value: this.xmppService.options.adaptiveSimulcast})
  8334. .up();
  8335. }
  8336. if (this.xmppService.options.openSctp !== undefined) {
  8337. elem.c(
  8338. 'property',
  8339. {name: 'openSctp',value: this.xmppService.options.openSctp})
  8340. .up();
  8341. }
  8342. if(this.xmppService.options.startAudioMuted !== undefined)
  8343. {
  8344. elem.c(
  8345. 'property',
  8346. {name: 'startAudioMuted',value: this.xmppService.options.startAudioMuted})
  8347. .up();
  8348. }
  8349. if(this.xmppService.options.startVideoMuted !== undefined)
  8350. {
  8351. elem.c(
  8352. 'property',
  8353. {name: 'startVideoMuted',value: this.xmppService.options.startVideoMuted})
  8354. .up();
  8355. }
  8356. elem.c(
  8357. 'property',
  8358. {name: 'simulcastMode',value: 'rewriting'})
  8359. .up();
  8360. elem.up();
  8361. return elem;
  8362. };
  8363. Moderator.prototype.parseSessionId = function (resultIq) {
  8364. var sessionId = $(resultIq).find('conference').attr('session-id');
  8365. if (sessionId) {
  8366. console.info('Received sessionId: ' + sessionId);
  8367. localStorage.setItem('sessionId', sessionId);
  8368. }
  8369. };
  8370. Moderator.prototype.parseConfigOptions = function (resultIq) {
  8371. this.setFocusUserJid(
  8372. $(resultIq).find('conference').attr('focusjid'));
  8373. var authenticationEnabled
  8374. = $(resultIq).find(
  8375. '>conference>property' +
  8376. '[name=\'authentication\'][value=\'true\']').length > 0;
  8377. console.info("Authentication enabled: " + authenticationEnabled);
  8378. this.externalAuthEnabled = $(resultIq).find(
  8379. '>conference>property' +
  8380. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  8381. console.info('External authentication enabled: ' + this.externalAuthEnabled);
  8382. if (!this.externalAuthEnabled) {
  8383. // We expect to receive sessionId in 'internal' authentication mode
  8384. this.parseSessionId(resultIq);
  8385. }
  8386. var authIdentity = $(resultIq).find('>conference').attr('identity');
  8387. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  8388. authenticationEnabled, authIdentity);
  8389. // Check if focus has auto-detected Jigasi component(this will be also
  8390. // included if we have passed our host from the config)
  8391. if ($(resultIq).find(
  8392. '>conference>property' +
  8393. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  8394. this.sipGatewayEnabled = true;
  8395. }
  8396. console.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  8397. };
  8398. // FIXME = we need to show the fact that we're waiting for the focus
  8399. // to the user(or that focus is not available)
  8400. Moderator.prototype.allocateConferenceFocus = function ( callback) {
  8401. // Try to use focus user JID from the config
  8402. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  8403. // Send create conference IQ
  8404. var iq = this.createConferenceIq();
  8405. var self = this;
  8406. this.connection.sendIQ(
  8407. iq,
  8408. function (result) {
  8409. // Setup config options
  8410. self.parseConfigOptions(result);
  8411. if ('true' === $(result).find('conference').attr('ready')) {
  8412. // Reset both timers
  8413. self.getNextTimeout(true);
  8414. self.getNextErrorTimeout(true);
  8415. // Exec callback
  8416. callback();
  8417. } else {
  8418. var waitMs = self.getNextTimeout();
  8419. console.info("Waiting for the focus... " + waitMs);
  8420. // Reset error timeout
  8421. self.getNextErrorTimeout(true);
  8422. window.setTimeout(
  8423. function () {
  8424. self.allocateConferenceFocus(callback);
  8425. }, waitMs);
  8426. }
  8427. },
  8428. function (error) {
  8429. // Invalid session ? remove and try again
  8430. // without session ID to get a new one
  8431. var invalidSession
  8432. = $(error).find('>error>session-invalid').length;
  8433. if (invalidSession) {
  8434. console.info("Session expired! - removing");
  8435. localStorage.removeItem("sessionId");
  8436. }
  8437. if ($(error).find('>error>graceful-shutdown').length) {
  8438. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  8439. return;
  8440. }
  8441. // Check for error returned by the reservation system
  8442. var reservationErr = $(error).find('>error>reservation-error');
  8443. if (reservationErr.length) {
  8444. // Trigger error event
  8445. var errorCode = reservationErr.attr('error-code');
  8446. var errorMsg;
  8447. if ($(error).find('>error>text')) {
  8448. errorMsg = $(error).find('>error>text').text();
  8449. }
  8450. self.eventEmitter.emit(
  8451. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  8452. return;
  8453. }
  8454. // Not authorized to create new room
  8455. if ($(error).find('>error>not-authorized').length) {
  8456. console.warn("Unauthorized to start the conference", error);
  8457. var toDomain
  8458. = Strophe.getDomainFromJid(error.getAttribute('to'));
  8459. if (toDomain !== this.xmppService.options.hosts.anonymousdomain) {
  8460. //FIXME: "is external" should come either from
  8461. // the focus or config.js
  8462. self.externalAuthEnabled = true;
  8463. }
  8464. self.eventEmitter.emit(
  8465. XMPPEvents.AUTHENTICATION_REQUIRED,
  8466. function () {
  8467. self.allocateConferenceFocus(
  8468. callback);
  8469. });
  8470. return;
  8471. }
  8472. var waitMs = self.getNextErrorTimeout();
  8473. console.error("Focus error, retry after " + waitMs, error);
  8474. // Show message
  8475. var focusComponent = self.getFocusComponent();
  8476. var retrySec = waitMs / 1000;
  8477. //FIXME: message is duplicated ?
  8478. // Do not show in case of session invalid
  8479. // which means just a retry
  8480. if (!invalidSession) {
  8481. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  8482. focusComponent, retrySec);
  8483. }
  8484. // Reset response timeout
  8485. self.getNextTimeout(true);
  8486. window.setTimeout(
  8487. function () {
  8488. self.allocateConferenceFocus(callback);
  8489. }, waitMs);
  8490. }
  8491. );
  8492. };
  8493. Moderator.prototype.getLoginUrl = function (urlCallback) {
  8494. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  8495. iq.c('login-url', {
  8496. xmlns: 'http://jitsi.org/protocol/focus',
  8497. room: this.roomName,
  8498. 'machine-uid': this.settings.getSettings().uid
  8499. });
  8500. this.connection.sendIQ(
  8501. iq,
  8502. function (result) {
  8503. var url = $(result).find('login-url').attr('url');
  8504. url = url = decodeURIComponent(url);
  8505. if (url) {
  8506. console.info("Got auth url: " + url);
  8507. urlCallback(url);
  8508. } else {
  8509. console.error(
  8510. "Failed to get auth url from the focus", result);
  8511. }
  8512. },
  8513. function (error) {
  8514. console.error("Get auth url error", error);
  8515. }
  8516. );
  8517. };
  8518. Moderator.prototype.getPopupLoginUrl = function (urlCallback) {
  8519. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  8520. iq.c('login-url', {
  8521. xmlns: 'http://jitsi.org/protocol/focus',
  8522. room: this.roomName,
  8523. 'machine-uid': this.settings.getSettings().uid,
  8524. popup: true
  8525. });
  8526. this.connection.sendIQ(
  8527. iq,
  8528. function (result) {
  8529. var url = $(result).find('login-url').attr('url');
  8530. url = url = decodeURIComponent(url);
  8531. if (url) {
  8532. console.info("Got POPUP auth url: " + url);
  8533. urlCallback(url);
  8534. } else {
  8535. console.error(
  8536. "Failed to get POPUP auth url from the focus", result);
  8537. }
  8538. },
  8539. function (error) {
  8540. console.error('Get POPUP auth url error', error);
  8541. }
  8542. );
  8543. };
  8544. Moderator.prototype.logout = function (callback) {
  8545. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  8546. var sessionId = localStorage.getItem('sessionId');
  8547. if (!sessionId) {
  8548. callback();
  8549. return;
  8550. }
  8551. iq.c('logout', {
  8552. xmlns: 'http://jitsi.org/protocol/focus',
  8553. 'session-id': sessionId
  8554. });
  8555. this.connection.sendIQ(
  8556. iq,
  8557. function (result) {
  8558. var logoutUrl = $(result).find('logout').attr('logout-url');
  8559. if (logoutUrl) {
  8560. logoutUrl = decodeURIComponent(logoutUrl);
  8561. }
  8562. console.info("Log out OK, url: " + logoutUrl, result);
  8563. localStorage.removeItem('sessionId');
  8564. callback(logoutUrl);
  8565. },
  8566. function (error) {
  8567. console.error("Logout error", error);
  8568. }
  8569. );
  8570. };
  8571. module.exports = Moderator;
  8572. },{"../../service/authentication/AuthenticationEvents":80,"../../service/xmpp/XMPPEvents":83,"../settings/Settings":18}],32:[function(require,module,exports){
  8573. /* jshint -W117 */
  8574. /* a simple MUC connection plugin
  8575. * can only handle a single MUC room
  8576. */
  8577. var ChatRoom = require("./ChatRoom");
  8578. module.exports = function(XMPP) {
  8579. Strophe.addConnectionPlugin('emuc', {
  8580. connection: null,
  8581. rooms: {},//map with the rooms
  8582. init: function (conn) {
  8583. this.connection = conn;
  8584. // add handlers (just once)
  8585. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, null, null);
  8586. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null);
  8587. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null);
  8588. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null);
  8589. },
  8590. createRoom: function (jid, password, options) {
  8591. var roomJid = Strophe.getBareJidFromJid(jid);
  8592. if (this.rooms[roomJid]) {
  8593. console.error("You are already in the room!");
  8594. return;
  8595. }
  8596. this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, options);
  8597. return this.rooms[roomJid];
  8598. },
  8599. doLeave: function (jid) {
  8600. this.rooms[jid].doLeave();
  8601. delete this.rooms[jid];
  8602. },
  8603. onPresence: function (pres) {
  8604. var from = pres.getAttribute('from');
  8605. // What is this for? A workaround for something?
  8606. if (pres.getAttribute('type')) {
  8607. return true;
  8608. }
  8609. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  8610. if(!room)
  8611. return;
  8612. // Parse status.
  8613. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  8614. room.createNonAnonymousRoom();
  8615. }
  8616. room.onPresence(pres);
  8617. return true;
  8618. },
  8619. onPresenceUnavailable: function (pres) {
  8620. var from = pres.getAttribute('from');
  8621. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  8622. if(!room)
  8623. return;
  8624. room.onPresenceUnavailable(pres, from);
  8625. return true;
  8626. },
  8627. onPresenceError: function (pres) {
  8628. var from = pres.getAttribute('from');
  8629. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  8630. if(!room)
  8631. return;
  8632. room.onPresenceError(pres, from);
  8633. return true;
  8634. },
  8635. onMessage: function (msg) {
  8636. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  8637. var from = msg.getAttribute('from');
  8638. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  8639. if(!room)
  8640. return;
  8641. room.onMessage(msg, from);
  8642. return true;
  8643. },
  8644. setJingleSession: function (from, session) {
  8645. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  8646. if(!room)
  8647. return;
  8648. room.setJingleSession(session);
  8649. }
  8650. });
  8651. };
  8652. },{"./ChatRoom":23}],33:[function(require,module,exports){
  8653. /* jshint -W117 */
  8654. var JingleSession = require("./JingleSessionPC");
  8655. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8656. var RTCBrowserType = require("../RTC/RTCBrowserType");
  8657. module.exports = function(XMPP, eventEmitter) {
  8658. Strophe.addConnectionPlugin('jingle', {
  8659. connection: null,
  8660. sessions: {},
  8661. jid2session: {},
  8662. ice_config: {iceServers: []},
  8663. media_constraints: {
  8664. mandatory: {
  8665. 'OfferToReceiveAudio': true,
  8666. 'OfferToReceiveVideo': true
  8667. }
  8668. // MozDontOfferDataChannel: true when this is firefox
  8669. },
  8670. init: function (conn) {
  8671. this.connection = conn;
  8672. if (this.connection.disco) {
  8673. // http://xmpp.org/extensions/xep-0167.html#support
  8674. // http://xmpp.org/extensions/xep-0176.html#support
  8675. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  8676. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  8677. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  8678. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  8679. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  8680. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  8681. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  8682. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  8683. || RTCBrowserType.isTemasysPluginUsed()) {
  8684. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  8685. }
  8686. // this is dealt with by SDP O/A so we don't need to announce this
  8687. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  8688. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  8689. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  8690. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  8691. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  8692. }
  8693. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  8694. },
  8695. onJingle: function (iq) {
  8696. var sid = $(iq).find('jingle').attr('sid');
  8697. var action = $(iq).find('jingle').attr('action');
  8698. var fromJid = iq.getAttribute('from');
  8699. // send ack first
  8700. var ack = $iq({type: 'result',
  8701. to: fromJid,
  8702. id: iq.getAttribute('id')
  8703. });
  8704. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  8705. var sess = this.sessions[sid];
  8706. if ('session-initiate' != action) {
  8707. if (sess === null) {
  8708. ack.type = 'error';
  8709. ack.c('error', {type: 'cancel'})
  8710. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  8711. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  8712. this.connection.send(ack);
  8713. return true;
  8714. }
  8715. // local jid is not checked
  8716. if (fromJid != sess.peerjid) {
  8717. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  8718. ack.type = 'error';
  8719. ack.c('error', {type: 'cancel'})
  8720. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  8721. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  8722. this.connection.send(ack);
  8723. return true;
  8724. }
  8725. } else if (sess !== undefined) {
  8726. // existing session with same session id
  8727. // this might be out-of-order if the sess.peerjid is the same as from
  8728. ack.type = 'error';
  8729. ack.c('error', {type: 'cancel'})
  8730. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  8731. console.warn('duplicate session id', sid);
  8732. this.connection.send(ack);
  8733. return true;
  8734. }
  8735. // FIXME: check for a defined action
  8736. this.connection.send(ack);
  8737. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  8738. switch (action) {
  8739. case 'session-initiate':
  8740. var startMuted = $(iq).find('jingle>startmuted');
  8741. if (startMuted && startMuted.length > 0) {
  8742. var audioMuted = startMuted.attr("audio");
  8743. var videoMuted = startMuted.attr("video");
  8744. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  8745. audioMuted === "true", videoMuted === "true");
  8746. }
  8747. sess = new JingleSession(
  8748. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  8749. this.connection, XMPP);
  8750. // configure session
  8751. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  8752. this.connection.emuc.setJingleSession(fromBareJid, sess);
  8753. sess.media_constraints = this.media_constraints;
  8754. sess.ice_config = this.ice_config;
  8755. sess.initialize(fromJid, false);
  8756. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  8757. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  8758. sess.setOffer($(iq).find('>jingle'));
  8759. this.sessions[sess.sid] = sess;
  8760. this.jid2session[sess.peerjid] = sess;
  8761. // the callback should either
  8762. // .sendAnswer and .accept
  8763. // or .sendTerminate -- not necessarily synchronous
  8764. sess.sendAnswer();
  8765. sess.accept();
  8766. break;
  8767. case 'session-accept':
  8768. sess.setAnswer($(iq).find('>jingle'));
  8769. sess.accept();
  8770. break;
  8771. case 'session-terminate':
  8772. // If this is not the focus sending the terminate, we have
  8773. // nothing more to do here.
  8774. if (Object.keys(this.sessions).length < 1
  8775. || !(this.sessions[Object.keys(this.sessions)[0]]
  8776. instanceof JingleSession))
  8777. {
  8778. break;
  8779. }
  8780. console.log('terminating...', sess.sid);
  8781. sess.terminate();
  8782. this.terminate(sess.sid);
  8783. if ($(iq).find('>jingle>reason').length) {
  8784. $(document).trigger('callterminated.jingle', [
  8785. sess.sid,
  8786. sess.peerjid,
  8787. $(iq).find('>jingle>reason>:first')[0].tagName,
  8788. $(iq).find('>jingle>reason>text').text()
  8789. ]);
  8790. } else {
  8791. $(document).trigger('callterminated.jingle',
  8792. [sess.sid, sess.peerjid]);
  8793. }
  8794. break;
  8795. case 'transport-info':
  8796. sess.addIceCandidate($(iq).find('>jingle>content'));
  8797. break;
  8798. case 'session-info':
  8799. var affected;
  8800. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  8801. $(document).trigger('ringing.jingle', [sess.sid]);
  8802. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  8803. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  8804. $(document).trigger('mute.jingle', [sess.sid, affected]);
  8805. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  8806. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  8807. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  8808. }
  8809. break;
  8810. case 'addsource': // FIXME: proprietary, un-jingleish
  8811. case 'source-add': // FIXME: proprietary
  8812. sess.addSource($(iq).find('>jingle>content'), fromJid);
  8813. break;
  8814. case 'removesource': // FIXME: proprietary, un-jingleish
  8815. case 'source-remove': // FIXME: proprietary
  8816. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  8817. break;
  8818. default:
  8819. console.warn('jingle action not implemented', action);
  8820. break;
  8821. }
  8822. return true;
  8823. },
  8824. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  8825. if (sid === null || sid === undefined) {
  8826. for (sid in this.sessions) {
  8827. if (this.sessions[sid].state != 'ended') {
  8828. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  8829. this.sessions[sid].terminate();
  8830. }
  8831. delete this.jid2session[this.sessions[sid].peerjid];
  8832. delete this.sessions[sid];
  8833. }
  8834. } else if (this.sessions.hasOwnProperty(sid)) {
  8835. if (this.sessions[sid].state != 'ended') {
  8836. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  8837. this.sessions[sid].terminate();
  8838. }
  8839. delete this.jid2session[this.sessions[sid].peerjid];
  8840. delete this.sessions[sid];
  8841. }
  8842. },
  8843. getStunAndTurnCredentials: function () {
  8844. // get stun and turn configuration from server via xep-0215
  8845. // uses time-limited credentials as described in
  8846. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  8847. //
  8848. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  8849. // for a prosody module which implements this
  8850. //
  8851. // currently, this doesn't work with updateIce and therefore credentials with a long
  8852. // validity have to be fetched before creating the peerconnection
  8853. // TODO: implement refresh via updateIce as described in
  8854. // https://code.google.com/p/webrtc/issues/detail?id=1650
  8855. var self = this;
  8856. this.connection.sendIQ(
  8857. $iq({type: 'get', to: this.connection.domain})
  8858. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  8859. function (res) {
  8860. var iceservers = [];
  8861. $(res).find('>services>service').each(function (idx, el) {
  8862. el = $(el);
  8863. var dict = {};
  8864. var type = el.attr('type');
  8865. switch (type) {
  8866. case 'stun':
  8867. dict.url = 'stun:' + el.attr('host');
  8868. if (el.attr('port')) {
  8869. dict.url += ':' + el.attr('port');
  8870. }
  8871. iceservers.push(dict);
  8872. break;
  8873. case 'turn':
  8874. case 'turns':
  8875. dict.url = type + ':';
  8876. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  8877. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  8878. dict.url += el.attr('username') + '@';
  8879. } else {
  8880. dict.username = el.attr('username'); // only works in M28
  8881. }
  8882. }
  8883. dict.url += el.attr('host');
  8884. if (el.attr('port') && el.attr('port') != '3478') {
  8885. dict.url += ':' + el.attr('port');
  8886. }
  8887. if (el.attr('transport') && el.attr('transport') != 'udp') {
  8888. dict.url += '?transport=' + el.attr('transport');
  8889. }
  8890. if (el.attr('password')) {
  8891. dict.credential = el.attr('password');
  8892. }
  8893. iceservers.push(dict);
  8894. break;
  8895. }
  8896. });
  8897. self.ice_config.iceServers = iceservers;
  8898. },
  8899. function (err) {
  8900. console.warn('getting turn credentials failed', err);
  8901. console.warn('is mod_turncredentials or similar installed?');
  8902. }
  8903. );
  8904. // implement push?
  8905. },
  8906. /**
  8907. * Returns the data saved in 'updateLog' in a format to be logged.
  8908. */
  8909. getLog: function () {
  8910. var data = {};
  8911. var self = this;
  8912. Object.keys(this.sessions).forEach(function (sid) {
  8913. var session = self.sessions[sid];
  8914. if (session.peerconnection && session.peerconnection.updateLog) {
  8915. // FIXME: should probably be a .dump call
  8916. data["jingle_" + session.sid] = {
  8917. updateLog: session.peerconnection.updateLog,
  8918. stats: session.peerconnection.stats,
  8919. url: window.location.href
  8920. };
  8921. }
  8922. });
  8923. return data;
  8924. }
  8925. });
  8926. };
  8927. },{"../../service/xmpp/XMPPEvents":83,"../RTC/RTCBrowserType":14,"./JingleSessionPC":25}],34:[function(require,module,exports){
  8928. /* global Strophe */
  8929. module.exports = function () {
  8930. Strophe.addConnectionPlugin('logger', {
  8931. // logs raw stanzas and makes them available for download as JSON
  8932. connection: null,
  8933. log: [],
  8934. init: function (conn) {
  8935. this.connection = conn;
  8936. this.connection.rawInput = this.log_incoming.bind(this);
  8937. this.connection.rawOutput = this.log_outgoing.bind(this);
  8938. },
  8939. log_incoming: function (stanza) {
  8940. this.log.push([new Date().getTime(), 'incoming', stanza]);
  8941. },
  8942. log_outgoing: function (stanza) {
  8943. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  8944. }
  8945. });
  8946. };
  8947. },{}],35:[function(require,module,exports){
  8948. /* jshint -W117 */
  8949. module.exports = function() {
  8950. Strophe.addConnectionPlugin('rayo',
  8951. {
  8952. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  8953. connection: null,
  8954. init: function (conn) {
  8955. this.connection = conn;
  8956. if (this.connection.disco) {
  8957. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  8958. }
  8959. this.connection.addHandler(
  8960. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  8961. },
  8962. onRayo: function (iq) {
  8963. console.info("Rayo IQ", iq);
  8964. },
  8965. dial: function (to, from, roomName, roomPass) {
  8966. var self = this;
  8967. var req = $iq(
  8968. {
  8969. type: 'set',
  8970. to: this.connection.emuc.focusMucJid
  8971. }
  8972. );
  8973. req.c('dial',
  8974. {
  8975. xmlns: this.RAYO_XMLNS,
  8976. to: to,
  8977. from: from
  8978. });
  8979. req.c('header',
  8980. {
  8981. name: 'JvbRoomName',
  8982. value: roomName
  8983. }).up();
  8984. if (roomPass !== null && roomPass.length) {
  8985. req.c('header',
  8986. {
  8987. name: 'JvbRoomPassword',
  8988. value: roomPass
  8989. }).up();
  8990. }
  8991. this.connection.sendIQ(
  8992. req,
  8993. function (result) {
  8994. console.info('Dial result ', result);
  8995. var resource = $(result).find('ref').attr('uri');
  8996. this.call_resource = resource.substr('xmpp:'.length);
  8997. console.info(
  8998. "Received call resource: " + this.call_resource);
  8999. },
  9000. function (error) {
  9001. console.info('Dial error ', error);
  9002. }
  9003. );
  9004. },
  9005. hang_up: function () {
  9006. if (!this.call_resource) {
  9007. console.warn("No call in progress");
  9008. return;
  9009. }
  9010. var self = this;
  9011. var req = $iq(
  9012. {
  9013. type: 'set',
  9014. to: this.call_resource
  9015. }
  9016. );
  9017. req.c('hangup',
  9018. {
  9019. xmlns: this.RAYO_XMLNS
  9020. });
  9021. this.connection.sendIQ(
  9022. req,
  9023. function (result) {
  9024. console.info('Hangup result ', result);
  9025. self.call_resource = null;
  9026. },
  9027. function (error) {
  9028. console.info('Hangup error ', error);
  9029. self.call_resource = null;
  9030. }
  9031. );
  9032. }
  9033. }
  9034. );
  9035. };
  9036. },{}],36:[function(require,module,exports){
  9037. /**
  9038. * Strophe logger implementation. Logs from level WARN and above.
  9039. */
  9040. module.exports = function () {
  9041. Strophe.log = function (level, msg) {
  9042. switch (level) {
  9043. case Strophe.LogLevel.WARN:
  9044. console.warn("Strophe: " + msg);
  9045. break;
  9046. case Strophe.LogLevel.ERROR:
  9047. case Strophe.LogLevel.FATAL:
  9048. console.error("Strophe: " + msg);
  9049. break;
  9050. }
  9051. };
  9052. Strophe.getStatusString = function (status) {
  9053. switch (status) {
  9054. case Strophe.Status.ERROR:
  9055. return "ERROR";
  9056. case Strophe.Status.CONNECTING:
  9057. return "CONNECTING";
  9058. case Strophe.Status.CONNFAIL:
  9059. return "CONNFAIL";
  9060. case Strophe.Status.AUTHENTICATING:
  9061. return "AUTHENTICATING";
  9062. case Strophe.Status.AUTHFAIL:
  9063. return "AUTHFAIL";
  9064. case Strophe.Status.CONNECTED:
  9065. return "CONNECTED";
  9066. case Strophe.Status.DISCONNECTED:
  9067. return "DISCONNECTED";
  9068. case Strophe.Status.DISCONNECTING:
  9069. return "DISCONNECTING";
  9070. case Strophe.Status.ATTACHED:
  9071. return "ATTACHED";
  9072. default:
  9073. return "unknown";
  9074. }
  9075. };
  9076. };
  9077. },{}],37:[function(require,module,exports){
  9078. /* global $, APP, config, Strophe*/
  9079. var EventEmitter = require("events");
  9080. var Pako = require("pako");
  9081. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  9082. var RTCEvents = require("../../service/RTC/RTCEvents");
  9083. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9084. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  9085. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  9086. var RTC = require("../RTC/RTC");
  9087. var authenticatedUser = false;
  9088. function createConnection(bosh) {
  9089. bosh = bosh || '/http-bind';
  9090. return new Strophe.Connection(bosh);
  9091. };
  9092. //!!!!!!!!!! FIXME: ...
  9093. function initStrophePlugins(XMPP)
  9094. {
  9095. require("./strophe.emuc")(XMPP);
  9096. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  9097. // require("./strophe.moderate")(XMPP, eventEmitter);
  9098. require("./strophe.util")();
  9099. require("./strophe.rayo")();
  9100. require("./strophe.logger")();
  9101. }
  9102. //!!!!!!!!!! FIXME: ...
  9103. ///**
  9104. // * If given <tt>localStream</tt> is video one this method will advertise it's
  9105. // * video type in MUC presence.
  9106. // * @param localStream new or modified <tt>LocalStream</tt>.
  9107. // */
  9108. //function broadcastLocalVideoType(localStream) {
  9109. // if (localStream.videoType)
  9110. // XMPP.addToPresence('videoType', localStream.videoType);
  9111. //}
  9112. //
  9113. //function registerListeners() {
  9114. // RTC.addStreamListener(
  9115. // broadcastLocalVideoType,
  9116. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  9117. // );
  9118. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  9119. // XMPP.addToPresence("devices", devices);
  9120. // });
  9121. //}
  9122. function XMPP(options) {
  9123. this.eventEmitter = new EventEmitter();
  9124. this.connection = null;
  9125. this.disconnectInProgress = false;
  9126. this.forceMuted = false;
  9127. this.options = options;
  9128. initStrophePlugins(this);
  9129. // registerListeners();
  9130. this.connection = createConnection(options.bosh);
  9131. }
  9132. XMPP.prototype.getConnection = function(){ return connection; };
  9133. XMPP.prototype._connect = function (jid, password) {
  9134. var self = this;
  9135. // connection.connect() starts the connection process.
  9136. //
  9137. // As the connection process proceeds, the user supplied callback will
  9138. // be triggered multiple times with status updates. The callback should
  9139. // take two arguments - the status code and the error condition.
  9140. //
  9141. // The status code will be one of the values in the Strophe.Status
  9142. // constants. The error condition will be one of the conditions defined
  9143. // in RFC 3920 or the condition ‘strophe-parsererror’.
  9144. //
  9145. // The Parameters wait, hold and route are optional and only relevant
  9146. // for BOSH connections. Please see XEP 124 for a more detailed
  9147. // explanation of the optional parameters.
  9148. //
  9149. // Connection status constants for use by the connection handler
  9150. // callback.
  9151. //
  9152. // Status.ERROR - An error has occurred (websockets specific)
  9153. // Status.CONNECTING - The connection is currently being made
  9154. // Status.CONNFAIL - The connection attempt failed
  9155. // Status.AUTHENTICATING - The connection is authenticating
  9156. // Status.AUTHFAIL - The authentication attempt failed
  9157. // Status.CONNECTED - The connection has succeeded
  9158. // Status.DISCONNECTED - The connection has been terminated
  9159. // Status.DISCONNECTING - The connection is currently being terminated
  9160. // Status.ATTACHED - The connection has been attached
  9161. var anonymousConnectionFailed = false;
  9162. var connectionFailed = false;
  9163. var lastErrorMsg;
  9164. this.connection.connect(jid, password, function (status, msg) {
  9165. console.log('Strophe status changed to',
  9166. Strophe.getStatusString(status), msg);
  9167. if (status === Strophe.Status.CONNECTED) {
  9168. if (self.options.useStunTurn) {
  9169. self.connection.jingle.getStunAndTurnCredentials();
  9170. }
  9171. console.info("My Jabber ID: " + self.connection.jid);
  9172. if (password)
  9173. authenticatedUser = true;
  9174. if (self.connection && self.connection.connected &&
  9175. Strophe.getResourceFromJid(self.connection.jid)) {
  9176. // .connected is true while connecting?
  9177. // self.connection.send($pres());
  9178. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  9179. Strophe.getResourceFromJid(self.connection.jid));
  9180. }
  9181. } else if (status === Strophe.Status.CONNFAIL) {
  9182. if (msg === 'x-strophe-bad-non-anon-jid') {
  9183. anonymousConnectionFailed = true;
  9184. }
  9185. else
  9186. {
  9187. connectionFailed = true;
  9188. }
  9189. lastErrorMsg = msg;
  9190. } else if (status === Strophe.Status.DISCONNECTED) {
  9191. self.disconnectInProgress = false;
  9192. if (anonymousConnectionFailed) {
  9193. // prompt user for username and password
  9194. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  9195. JitsiConnectionErrors.PASSWORD_REQUIRED);
  9196. } else if(connectionFailed) {
  9197. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  9198. JitsiConnectionErrors.OTHER_ERROR,
  9199. msg ? msg : lastErrorMsg);
  9200. } else {
  9201. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  9202. msg ? msg : lastErrorMsg);
  9203. }
  9204. } else if (status === Strophe.Status.AUTHFAIL) {
  9205. // wrong password or username, prompt user
  9206. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  9207. JitsiConnectionErrors.PASSWORD_REQUIRED);
  9208. }
  9209. });
  9210. }
  9211. XMPP.prototype.connect = function (jid, password) {
  9212. if(!jid) {
  9213. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  9214. // Force authenticated domain if room is appended with '?login=true'
  9215. if (this.options.hosts.anonymousdomain &&
  9216. window.location.search.indexOf("login=true") !== -1) {
  9217. configDomain = this.options.hosts.domain;
  9218. }
  9219. jid = configDomain || window.location.hostname;
  9220. }
  9221. return this._connect(jid, password);
  9222. };
  9223. XMPP.prototype.createRoom = function (roomName, options, useNicks, nick) {
  9224. var roomjid = roomName + '@' + this.options.hosts.muc;
  9225. if (useNicks) {
  9226. if (nick) {
  9227. roomjid += '/' + nick;
  9228. } else {
  9229. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  9230. }
  9231. } else {
  9232. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  9233. if(!authenticatedUser)
  9234. tmpJid = tmpJid.substr(0, 8);
  9235. roomjid += '/' + tmpJid;
  9236. }
  9237. return this.connection.emuc.createRoom(roomjid, null, options);
  9238. }
  9239. XMPP.prototype.addListener = function(type, listener) {
  9240. this.eventEmitter.on(type, listener);
  9241. };
  9242. XMPP.prototype.removeListener = function (type, listener) {
  9243. this.eventEmitter.removeListener(type, listener);
  9244. };
  9245. //FIXME: this should work with the room
  9246. XMPP.prototype.leaveRoom = function (jid) {
  9247. var handler = this.connection.jingle.jid2session[jid];
  9248. if (handler && handler.peerconnection) {
  9249. // FIXME: probably removing streams is not required and close() should
  9250. // be enough
  9251. if (RTC.localAudio) {
  9252. handler.peerconnection.removeStream(
  9253. RTC.localAudio.getOriginalStream(), true);
  9254. }
  9255. if (RTC.localVideo) {
  9256. handler.peerconnection.removeStream(
  9257. RTC.localVideo.getOriginalStream(), true);
  9258. }
  9259. handler.peerconnection.close();
  9260. }
  9261. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  9262. this.connection.emuc.doLeave(jid);
  9263. };
  9264. /**
  9265. * Sends 'data' as a log message to the focus. Returns true iff a message
  9266. * was sent.
  9267. * @param data
  9268. * @returns {boolean} true iff a message was sent.
  9269. */
  9270. XMPP.prototype.sendLogs = function (data) {
  9271. if(!this.connection.emuc.focusMucJid)
  9272. return false;
  9273. var deflate = true;
  9274. var content = JSON.stringify(data);
  9275. if (deflate) {
  9276. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  9277. }
  9278. content = Base64.encode(content);
  9279. // XEP-0337-ish
  9280. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  9281. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  9282. id: 'PeerConnectionStats'});
  9283. message.c('message').t(content).up();
  9284. if (deflate) {
  9285. message.c('tag', {name: "deflated", value: "true"}).up();
  9286. }
  9287. message.up();
  9288. this.connection.send(message);
  9289. return true;
  9290. };
  9291. // Gets the logs from strophe.jingle.
  9292. XMPP.prototype.getJingleLog = function () {
  9293. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  9294. };
  9295. // Gets the logs from strophe.
  9296. XMPP.prototype.getXmppLog = function () {
  9297. return this.connection.logger ? this.connection.logger.log : null;
  9298. };
  9299. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  9300. this.connection.rayo.dial(to, from, roomName,roomPass);
  9301. };
  9302. XMPP.prototype.setMute = function (jid, mute) {
  9303. this.connection.moderate.setMute(jid, mute);
  9304. };
  9305. XMPP.prototype.eject = function (jid) {
  9306. this.connection.moderate.eject(jid);
  9307. };
  9308. XMPP.prototype.getSessions = function () {
  9309. return this.connection.jingle.sessions;
  9310. };
  9311. XMPP.prototype.disconnect = function () {
  9312. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  9313. {
  9314. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  9315. return;
  9316. }
  9317. this.disconnectInProgress = true;
  9318. this.connection.disconnect();
  9319. };
  9320. module.exports = XMPP;
  9321. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":77,"../../service/RTC/StreamEventTypes":79,"../../service/xmpp/XMPPEvents":83,"../RTC/RTC":13,"./strophe.emuc":32,"./strophe.jingle":33,"./strophe.logger":34,"./strophe.rayo":35,"./strophe.util":36,"events":39,"pako":42}],38:[function(require,module,exports){
  9322. (function (process){
  9323. /*!
  9324. * async
  9325. * https://github.com/caolan/async
  9326. *
  9327. * Copyright 2010-2014 Caolan McMahon
  9328. * Released under the MIT license
  9329. */
  9330. /*jshint onevar: false, indent:4 */
  9331. /*global setImmediate: false, setTimeout: false, console: false */
  9332. (function () {
  9333. var async = {};
  9334. // global on the server, window in the browser
  9335. var root, previous_async;
  9336. root = this;
  9337. if (root != null) {
  9338. previous_async = root.async;
  9339. }
  9340. async.noConflict = function () {
  9341. root.async = previous_async;
  9342. return async;
  9343. };
  9344. function only_once(fn) {
  9345. var called = false;
  9346. return function() {
  9347. if (called) throw new Error("Callback was already called.");
  9348. called = true;
  9349. fn.apply(root, arguments);
  9350. }
  9351. }
  9352. //// cross-browser compatiblity functions ////
  9353. var _toString = Object.prototype.toString;
  9354. var _isArray = Array.isArray || function (obj) {
  9355. return _toString.call(obj) === '[object Array]';
  9356. };
  9357. var _each = function (arr, iterator) {
  9358. if (arr.forEach) {
  9359. return arr.forEach(iterator);
  9360. }
  9361. for (var i = 0; i < arr.length; i += 1) {
  9362. iterator(arr[i], i, arr);
  9363. }
  9364. };
  9365. var _map = function (arr, iterator) {
  9366. if (arr.map) {
  9367. return arr.map(iterator);
  9368. }
  9369. var results = [];
  9370. _each(arr, function (x, i, a) {
  9371. results.push(iterator(x, i, a));
  9372. });
  9373. return results;
  9374. };
  9375. var _reduce = function (arr, iterator, memo) {
  9376. if (arr.reduce) {
  9377. return arr.reduce(iterator, memo);
  9378. }
  9379. _each(arr, function (x, i, a) {
  9380. memo = iterator(memo, x, i, a);
  9381. });
  9382. return memo;
  9383. };
  9384. var _keys = function (obj) {
  9385. if (Object.keys) {
  9386. return Object.keys(obj);
  9387. }
  9388. var keys = [];
  9389. for (var k in obj) {
  9390. if (obj.hasOwnProperty(k)) {
  9391. keys.push(k);
  9392. }
  9393. }
  9394. return keys;
  9395. };
  9396. //// exported async module functions ////
  9397. //// nextTick implementation with browser-compatible fallback ////
  9398. if (typeof process === 'undefined' || !(process.nextTick)) {
  9399. if (typeof setImmediate === 'function') {
  9400. async.nextTick = function (fn) {
  9401. // not a direct alias for IE10 compatibility
  9402. setImmediate(fn);
  9403. };
  9404. async.setImmediate = async.nextTick;
  9405. }
  9406. else {
  9407. async.nextTick = function (fn) {
  9408. setTimeout(fn, 0);
  9409. };
  9410. async.setImmediate = async.nextTick;
  9411. }
  9412. }
  9413. else {
  9414. async.nextTick = process.nextTick;
  9415. if (typeof setImmediate !== 'undefined') {
  9416. async.setImmediate = function (fn) {
  9417. // not a direct alias for IE10 compatibility
  9418. setImmediate(fn);
  9419. };
  9420. }
  9421. else {
  9422. async.setImmediate = async.nextTick;
  9423. }
  9424. }
  9425. async.each = function (arr, iterator, callback) {
  9426. callback = callback || function () {};
  9427. if (!arr.length) {
  9428. return callback();
  9429. }
  9430. var completed = 0;
  9431. _each(arr, function (x) {
  9432. iterator(x, only_once(done) );
  9433. });
  9434. function done(err) {
  9435. if (err) {
  9436. callback(err);
  9437. callback = function () {};
  9438. }
  9439. else {
  9440. completed += 1;
  9441. if (completed >= arr.length) {
  9442. callback();
  9443. }
  9444. }
  9445. }
  9446. };
  9447. async.forEach = async.each;
  9448. async.eachSeries = function (arr, iterator, callback) {
  9449. callback = callback || function () {};
  9450. if (!arr.length) {
  9451. return callback();
  9452. }
  9453. var completed = 0;
  9454. var iterate = function () {
  9455. iterator(arr[completed], function (err) {
  9456. if (err) {
  9457. callback(err);
  9458. callback = function () {};
  9459. }
  9460. else {
  9461. completed += 1;
  9462. if (completed >= arr.length) {
  9463. callback();
  9464. }
  9465. else {
  9466. iterate();
  9467. }
  9468. }
  9469. });
  9470. };
  9471. iterate();
  9472. };
  9473. async.forEachSeries = async.eachSeries;
  9474. async.eachLimit = function (arr, limit, iterator, callback) {
  9475. var fn = _eachLimit(limit);
  9476. fn.apply(null, [arr, iterator, callback]);
  9477. };
  9478. async.forEachLimit = async.eachLimit;
  9479. var _eachLimit = function (limit) {
  9480. return function (arr, iterator, callback) {
  9481. callback = callback || function () {};
  9482. if (!arr.length || limit <= 0) {
  9483. return callback();
  9484. }
  9485. var completed = 0;
  9486. var started = 0;
  9487. var running = 0;
  9488. (function replenish () {
  9489. if (completed >= arr.length) {
  9490. return callback();
  9491. }
  9492. while (running < limit && started < arr.length) {
  9493. started += 1;
  9494. running += 1;
  9495. iterator(arr[started - 1], function (err) {
  9496. if (err) {
  9497. callback(err);
  9498. callback = function () {};
  9499. }
  9500. else {
  9501. completed += 1;
  9502. running -= 1;
  9503. if (completed >= arr.length) {
  9504. callback();
  9505. }
  9506. else {
  9507. replenish();
  9508. }
  9509. }
  9510. });
  9511. }
  9512. })();
  9513. };
  9514. };
  9515. var doParallel = function (fn) {
  9516. return function () {
  9517. var args = Array.prototype.slice.call(arguments);
  9518. return fn.apply(null, [async.each].concat(args));
  9519. };
  9520. };
  9521. var doParallelLimit = function(limit, fn) {
  9522. return function () {
  9523. var args = Array.prototype.slice.call(arguments);
  9524. return fn.apply(null, [_eachLimit(limit)].concat(args));
  9525. };
  9526. };
  9527. var doSeries = function (fn) {
  9528. return function () {
  9529. var args = Array.prototype.slice.call(arguments);
  9530. return fn.apply(null, [async.eachSeries].concat(args));
  9531. };
  9532. };
  9533. var _asyncMap = function (eachfn, arr, iterator, callback) {
  9534. arr = _map(arr, function (x, i) {
  9535. return {index: i, value: x};
  9536. });
  9537. if (!callback) {
  9538. eachfn(arr, function (x, callback) {
  9539. iterator(x.value, function (err) {
  9540. callback(err);
  9541. });
  9542. });
  9543. } else {
  9544. var results = [];
  9545. eachfn(arr, function (x, callback) {
  9546. iterator(x.value, function (err, v) {
  9547. results[x.index] = v;
  9548. callback(err);
  9549. });
  9550. }, function (err) {
  9551. callback(err, results);
  9552. });
  9553. }
  9554. };
  9555. async.map = doParallel(_asyncMap);
  9556. async.mapSeries = doSeries(_asyncMap);
  9557. async.mapLimit = function (arr, limit, iterator, callback) {
  9558. return _mapLimit(limit)(arr, iterator, callback);
  9559. };
  9560. var _mapLimit = function(limit) {
  9561. return doParallelLimit(limit, _asyncMap);
  9562. };
  9563. // reduce only has a series version, as doing reduce in parallel won't
  9564. // work in many situations.
  9565. async.reduce = function (arr, memo, iterator, callback) {
  9566. async.eachSeries(arr, function (x, callback) {
  9567. iterator(memo, x, function (err, v) {
  9568. memo = v;
  9569. callback(err);
  9570. });
  9571. }, function (err) {
  9572. callback(err, memo);
  9573. });
  9574. };
  9575. // inject alias
  9576. async.inject = async.reduce;
  9577. // foldl alias
  9578. async.foldl = async.reduce;
  9579. async.reduceRight = function (arr, memo, iterator, callback) {
  9580. var reversed = _map(arr, function (x) {
  9581. return x;
  9582. }).reverse();
  9583. async.reduce(reversed, memo, iterator, callback);
  9584. };
  9585. // foldr alias
  9586. async.foldr = async.reduceRight;
  9587. var _filter = function (eachfn, arr, iterator, callback) {
  9588. var results = [];
  9589. arr = _map(arr, function (x, i) {
  9590. return {index: i, value: x};
  9591. });
  9592. eachfn(arr, function (x, callback) {
  9593. iterator(x.value, function (v) {
  9594. if (v) {
  9595. results.push(x);
  9596. }
  9597. callback();
  9598. });
  9599. }, function (err) {
  9600. callback(_map(results.sort(function (a, b) {
  9601. return a.index - b.index;
  9602. }), function (x) {
  9603. return x.value;
  9604. }));
  9605. });
  9606. };
  9607. async.filter = doParallel(_filter);
  9608. async.filterSeries = doSeries(_filter);
  9609. // select alias
  9610. async.select = async.filter;
  9611. async.selectSeries = async.filterSeries;
  9612. var _reject = function (eachfn, arr, iterator, callback) {
  9613. var results = [];
  9614. arr = _map(arr, function (x, i) {
  9615. return {index: i, value: x};
  9616. });
  9617. eachfn(arr, function (x, callback) {
  9618. iterator(x.value, function (v) {
  9619. if (!v) {
  9620. results.push(x);
  9621. }
  9622. callback();
  9623. });
  9624. }, function (err) {
  9625. callback(_map(results.sort(function (a, b) {
  9626. return a.index - b.index;
  9627. }), function (x) {
  9628. return x.value;
  9629. }));
  9630. });
  9631. };
  9632. async.reject = doParallel(_reject);
  9633. async.rejectSeries = doSeries(_reject);
  9634. var _detect = function (eachfn, arr, iterator, main_callback) {
  9635. eachfn(arr, function (x, callback) {
  9636. iterator(x, function (result) {
  9637. if (result) {
  9638. main_callback(x);
  9639. main_callback = function () {};
  9640. }
  9641. else {
  9642. callback();
  9643. }
  9644. });
  9645. }, function (err) {
  9646. main_callback();
  9647. });
  9648. };
  9649. async.detect = doParallel(_detect);
  9650. async.detectSeries = doSeries(_detect);
  9651. async.some = function (arr, iterator, main_callback) {
  9652. async.each(arr, function (x, callback) {
  9653. iterator(x, function (v) {
  9654. if (v) {
  9655. main_callback(true);
  9656. main_callback = function () {};
  9657. }
  9658. callback();
  9659. });
  9660. }, function (err) {
  9661. main_callback(false);
  9662. });
  9663. };
  9664. // any alias
  9665. async.any = async.some;
  9666. async.every = function (arr, iterator, main_callback) {
  9667. async.each(arr, function (x, callback) {
  9668. iterator(x, function (v) {
  9669. if (!v) {
  9670. main_callback(false);
  9671. main_callback = function () {};
  9672. }
  9673. callback();
  9674. });
  9675. }, function (err) {
  9676. main_callback(true);
  9677. });
  9678. };
  9679. // all alias
  9680. async.all = async.every;
  9681. async.sortBy = function (arr, iterator, callback) {
  9682. async.map(arr, function (x, callback) {
  9683. iterator(x, function (err, criteria) {
  9684. if (err) {
  9685. callback(err);
  9686. }
  9687. else {
  9688. callback(null, {value: x, criteria: criteria});
  9689. }
  9690. });
  9691. }, function (err, results) {
  9692. if (err) {
  9693. return callback(err);
  9694. }
  9695. else {
  9696. var fn = function (left, right) {
  9697. var a = left.criteria, b = right.criteria;
  9698. return a < b ? -1 : a > b ? 1 : 0;
  9699. };
  9700. callback(null, _map(results.sort(fn), function (x) {
  9701. return x.value;
  9702. }));
  9703. }
  9704. });
  9705. };
  9706. async.auto = function (tasks, callback) {
  9707. callback = callback || function () {};
  9708. var keys = _keys(tasks);
  9709. var remainingTasks = keys.length
  9710. if (!remainingTasks) {
  9711. return callback();
  9712. }
  9713. var results = {};
  9714. var listeners = [];
  9715. var addListener = function (fn) {
  9716. listeners.unshift(fn);
  9717. };
  9718. var removeListener = function (fn) {
  9719. for (var i = 0; i < listeners.length; i += 1) {
  9720. if (listeners[i] === fn) {
  9721. listeners.splice(i, 1);
  9722. return;
  9723. }
  9724. }
  9725. };
  9726. var taskComplete = function () {
  9727. remainingTasks--
  9728. _each(listeners.slice(0), function (fn) {
  9729. fn();
  9730. });
  9731. };
  9732. addListener(function () {
  9733. if (!remainingTasks) {
  9734. var theCallback = callback;
  9735. // prevent final callback from calling itself if it errors
  9736. callback = function () {};
  9737. theCallback(null, results);
  9738. }
  9739. });
  9740. _each(keys, function (k) {
  9741. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  9742. var taskCallback = function (err) {
  9743. var args = Array.prototype.slice.call(arguments, 1);
  9744. if (args.length <= 1) {
  9745. args = args[0];
  9746. }
  9747. if (err) {
  9748. var safeResults = {};
  9749. _each(_keys(results), function(rkey) {
  9750. safeResults[rkey] = results[rkey];
  9751. });
  9752. safeResults[k] = args;
  9753. callback(err, safeResults);
  9754. // stop subsequent errors hitting callback multiple times
  9755. callback = function () {};
  9756. }
  9757. else {
  9758. results[k] = args;
  9759. async.setImmediate(taskComplete);
  9760. }
  9761. };
  9762. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  9763. var ready = function () {
  9764. return _reduce(requires, function (a, x) {
  9765. return (a && results.hasOwnProperty(x));
  9766. }, true) && !results.hasOwnProperty(k);
  9767. };
  9768. if (ready()) {
  9769. task[task.length - 1](taskCallback, results);
  9770. }
  9771. else {
  9772. var listener = function () {
  9773. if (ready()) {
  9774. removeListener(listener);
  9775. task[task.length - 1](taskCallback, results);
  9776. }
  9777. };
  9778. addListener(listener);
  9779. }
  9780. });
  9781. };
  9782. async.retry = function(times, task, callback) {
  9783. var DEFAULT_TIMES = 5;
  9784. var attempts = [];
  9785. // Use defaults if times not passed
  9786. if (typeof times === 'function') {
  9787. callback = task;
  9788. task = times;
  9789. times = DEFAULT_TIMES;
  9790. }
  9791. // Make sure times is a number
  9792. times = parseInt(times, 10) || DEFAULT_TIMES;
  9793. var wrappedTask = function(wrappedCallback, wrappedResults) {
  9794. var retryAttempt = function(task, finalAttempt) {
  9795. return function(seriesCallback) {
  9796. task(function(err, result){
  9797. seriesCallback(!err || finalAttempt, {err: err, result: result});
  9798. }, wrappedResults);
  9799. };
  9800. };
  9801. while (times) {
  9802. attempts.push(retryAttempt(task, !(times-=1)));
  9803. }
  9804. async.series(attempts, function(done, data){
  9805. data = data[data.length - 1];
  9806. (wrappedCallback || callback)(data.err, data.result);
  9807. });
  9808. }
  9809. // If a callback is passed, run this as a controll flow
  9810. return callback ? wrappedTask() : wrappedTask
  9811. };
  9812. async.waterfall = function (tasks, callback) {
  9813. callback = callback || function () {};
  9814. if (!_isArray(tasks)) {
  9815. var err = new Error('First argument to waterfall must be an array of functions');
  9816. return callback(err);
  9817. }
  9818. if (!tasks.length) {
  9819. return callback();
  9820. }
  9821. var wrapIterator = function (iterator) {
  9822. return function (err) {
  9823. if (err) {
  9824. callback.apply(null, arguments);
  9825. callback = function () {};
  9826. }
  9827. else {
  9828. var args = Array.prototype.slice.call(arguments, 1);
  9829. var next = iterator.next();
  9830. if (next) {
  9831. args.push(wrapIterator(next));
  9832. }
  9833. else {
  9834. args.push(callback);
  9835. }
  9836. async.setImmediate(function () {
  9837. iterator.apply(null, args);
  9838. });
  9839. }
  9840. };
  9841. };
  9842. wrapIterator(async.iterator(tasks))();
  9843. };
  9844. var _parallel = function(eachfn, tasks, callback) {
  9845. callback = callback || function () {};
  9846. if (_isArray(tasks)) {
  9847. eachfn.map(tasks, function (fn, callback) {
  9848. if (fn) {
  9849. fn(function (err) {
  9850. var args = Array.prototype.slice.call(arguments, 1);
  9851. if (args.length <= 1) {
  9852. args = args[0];
  9853. }
  9854. callback.call(null, err, args);
  9855. });
  9856. }
  9857. }, callback);
  9858. }
  9859. else {
  9860. var results = {};
  9861. eachfn.each(_keys(tasks), function (k, callback) {
  9862. tasks[k](function (err) {
  9863. var args = Array.prototype.slice.call(arguments, 1);
  9864. if (args.length <= 1) {
  9865. args = args[0];
  9866. }
  9867. results[k] = args;
  9868. callback(err);
  9869. });
  9870. }, function (err) {
  9871. callback(err, results);
  9872. });
  9873. }
  9874. };
  9875. async.parallel = function (tasks, callback) {
  9876. _parallel({ map: async.map, each: async.each }, tasks, callback);
  9877. };
  9878. async.parallelLimit = function(tasks, limit, callback) {
  9879. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  9880. };
  9881. async.series = function (tasks, callback) {
  9882. callback = callback || function () {};
  9883. if (_isArray(tasks)) {
  9884. async.mapSeries(tasks, function (fn, callback) {
  9885. if (fn) {
  9886. fn(function (err) {
  9887. var args = Array.prototype.slice.call(arguments, 1);
  9888. if (args.length <= 1) {
  9889. args = args[0];
  9890. }
  9891. callback.call(null, err, args);
  9892. });
  9893. }
  9894. }, callback);
  9895. }
  9896. else {
  9897. var results = {};
  9898. async.eachSeries(_keys(tasks), function (k, callback) {
  9899. tasks[k](function (err) {
  9900. var args = Array.prototype.slice.call(arguments, 1);
  9901. if (args.length <= 1) {
  9902. args = args[0];
  9903. }
  9904. results[k] = args;
  9905. callback(err);
  9906. });
  9907. }, function (err) {
  9908. callback(err, results);
  9909. });
  9910. }
  9911. };
  9912. async.iterator = function (tasks) {
  9913. var makeCallback = function (index) {
  9914. var fn = function () {
  9915. if (tasks.length) {
  9916. tasks[index].apply(null, arguments);
  9917. }
  9918. return fn.next();
  9919. };
  9920. fn.next = function () {
  9921. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  9922. };
  9923. return fn;
  9924. };
  9925. return makeCallback(0);
  9926. };
  9927. async.apply = function (fn) {
  9928. var args = Array.prototype.slice.call(arguments, 1);
  9929. return function () {
  9930. return fn.apply(
  9931. null, args.concat(Array.prototype.slice.call(arguments))
  9932. );
  9933. };
  9934. };
  9935. var _concat = function (eachfn, arr, fn, callback) {
  9936. var r = [];
  9937. eachfn(arr, function (x, cb) {
  9938. fn(x, function (err, y) {
  9939. r = r.concat(y || []);
  9940. cb(err);
  9941. });
  9942. }, function (err) {
  9943. callback(err, r);
  9944. });
  9945. };
  9946. async.concat = doParallel(_concat);
  9947. async.concatSeries = doSeries(_concat);
  9948. async.whilst = function (test, iterator, callback) {
  9949. if (test()) {
  9950. iterator(function (err) {
  9951. if (err) {
  9952. return callback(err);
  9953. }
  9954. async.whilst(test, iterator, callback);
  9955. });
  9956. }
  9957. else {
  9958. callback();
  9959. }
  9960. };
  9961. async.doWhilst = function (iterator, test, callback) {
  9962. iterator(function (err) {
  9963. if (err) {
  9964. return callback(err);
  9965. }
  9966. var args = Array.prototype.slice.call(arguments, 1);
  9967. if (test.apply(null, args)) {
  9968. async.doWhilst(iterator, test, callback);
  9969. }
  9970. else {
  9971. callback();
  9972. }
  9973. });
  9974. };
  9975. async.until = function (test, iterator, callback) {
  9976. if (!test()) {
  9977. iterator(function (err) {
  9978. if (err) {
  9979. return callback(err);
  9980. }
  9981. async.until(test, iterator, callback);
  9982. });
  9983. }
  9984. else {
  9985. callback();
  9986. }
  9987. };
  9988. async.doUntil = function (iterator, test, callback) {
  9989. iterator(function (err) {
  9990. if (err) {
  9991. return callback(err);
  9992. }
  9993. var args = Array.prototype.slice.call(arguments, 1);
  9994. if (!test.apply(null, args)) {
  9995. async.doUntil(iterator, test, callback);
  9996. }
  9997. else {
  9998. callback();
  9999. }
  10000. });
  10001. };
  10002. async.queue = function (worker, concurrency) {
  10003. if (concurrency === undefined) {
  10004. concurrency = 1;
  10005. }
  10006. function _insert(q, data, pos, callback) {
  10007. if (!q.started){
  10008. q.started = true;
  10009. }
  10010. if (!_isArray(data)) {
  10011. data = [data];
  10012. }
  10013. if(data.length == 0) {
  10014. // call drain immediately if there are no tasks
  10015. return async.setImmediate(function() {
  10016. if (q.drain) {
  10017. q.drain();
  10018. }
  10019. });
  10020. }
  10021. _each(data, function(task) {
  10022. var item = {
  10023. data: task,
  10024. callback: typeof callback === 'function' ? callback : null
  10025. };
  10026. if (pos) {
  10027. q.tasks.unshift(item);
  10028. } else {
  10029. q.tasks.push(item);
  10030. }
  10031. if (q.saturated && q.tasks.length === q.concurrency) {
  10032. q.saturated();
  10033. }
  10034. async.setImmediate(q.process);
  10035. });
  10036. }
  10037. var workers = 0;
  10038. var q = {
  10039. tasks: [],
  10040. concurrency: concurrency,
  10041. saturated: null,
  10042. empty: null,
  10043. drain: null,
  10044. started: false,
  10045. paused: false,
  10046. push: function (data, callback) {
  10047. _insert(q, data, false, callback);
  10048. },
  10049. kill: function () {
  10050. q.drain = null;
  10051. q.tasks = [];
  10052. },
  10053. unshift: function (data, callback) {
  10054. _insert(q, data, true, callback);
  10055. },
  10056. process: function () {
  10057. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  10058. var task = q.tasks.shift();
  10059. if (q.empty && q.tasks.length === 0) {
  10060. q.empty();
  10061. }
  10062. workers += 1;
  10063. var next = function () {
  10064. workers -= 1;
  10065. if (task.callback) {
  10066. task.callback.apply(task, arguments);
  10067. }
  10068. if (q.drain && q.tasks.length + workers === 0) {
  10069. q.drain();
  10070. }
  10071. q.process();
  10072. };
  10073. var cb = only_once(next);
  10074. worker(task.data, cb);
  10075. }
  10076. },
  10077. length: function () {
  10078. return q.tasks.length;
  10079. },
  10080. running: function () {
  10081. return workers;
  10082. },
  10083. idle: function() {
  10084. return q.tasks.length + workers === 0;
  10085. },
  10086. pause: function () {
  10087. if (q.paused === true) { return; }
  10088. q.paused = true;
  10089. q.process();
  10090. },
  10091. resume: function () {
  10092. if (q.paused === false) { return; }
  10093. q.paused = false;
  10094. q.process();
  10095. }
  10096. };
  10097. return q;
  10098. };
  10099. async.priorityQueue = function (worker, concurrency) {
  10100. function _compareTasks(a, b){
  10101. return a.priority - b.priority;
  10102. };
  10103. function _binarySearch(sequence, item, compare) {
  10104. var beg = -1,
  10105. end = sequence.length - 1;
  10106. while (beg < end) {
  10107. var mid = beg + ((end - beg + 1) >>> 1);
  10108. if (compare(item, sequence[mid]) >= 0) {
  10109. beg = mid;
  10110. } else {
  10111. end = mid - 1;
  10112. }
  10113. }
  10114. return beg;
  10115. }
  10116. function _insert(q, data, priority, callback) {
  10117. if (!q.started){
  10118. q.started = true;
  10119. }
  10120. if (!_isArray(data)) {
  10121. data = [data];
  10122. }
  10123. if(data.length == 0) {
  10124. // call drain immediately if there are no tasks
  10125. return async.setImmediate(function() {
  10126. if (q.drain) {
  10127. q.drain();
  10128. }
  10129. });
  10130. }
  10131. _each(data, function(task) {
  10132. var item = {
  10133. data: task,
  10134. priority: priority,
  10135. callback: typeof callback === 'function' ? callback : null
  10136. };
  10137. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  10138. if (q.saturated && q.tasks.length === q.concurrency) {
  10139. q.saturated();
  10140. }
  10141. async.setImmediate(q.process);
  10142. });
  10143. }
  10144. // Start with a normal queue
  10145. var q = async.queue(worker, concurrency);
  10146. // Override push to accept second parameter representing priority
  10147. q.push = function (data, priority, callback) {
  10148. _insert(q, data, priority, callback);
  10149. };
  10150. // Remove unshift function
  10151. delete q.unshift;
  10152. return q;
  10153. };
  10154. async.cargo = function (worker, payload) {
  10155. var working = false,
  10156. tasks = [];
  10157. var cargo = {
  10158. tasks: tasks,
  10159. payload: payload,
  10160. saturated: null,
  10161. empty: null,
  10162. drain: null,
  10163. drained: true,
  10164. push: function (data, callback) {
  10165. if (!_isArray(data)) {
  10166. data = [data];
  10167. }
  10168. _each(data, function(task) {
  10169. tasks.push({
  10170. data: task,
  10171. callback: typeof callback === 'function' ? callback : null
  10172. });
  10173. cargo.drained = false;
  10174. if (cargo.saturated && tasks.length === payload) {
  10175. cargo.saturated();
  10176. }
  10177. });
  10178. async.setImmediate(cargo.process);
  10179. },
  10180. process: function process() {
  10181. if (working) return;
  10182. if (tasks.length === 0) {
  10183. if(cargo.drain && !cargo.drained) cargo.drain();
  10184. cargo.drained = true;
  10185. return;
  10186. }
  10187. var ts = typeof payload === 'number'
  10188. ? tasks.splice(0, payload)
  10189. : tasks.splice(0, tasks.length);
  10190. var ds = _map(ts, function (task) {
  10191. return task.data;
  10192. });
  10193. if(cargo.empty) cargo.empty();
  10194. working = true;
  10195. worker(ds, function () {
  10196. working = false;
  10197. var args = arguments;
  10198. _each(ts, function (data) {
  10199. if (data.callback) {
  10200. data.callback.apply(null, args);
  10201. }
  10202. });
  10203. process();
  10204. });
  10205. },
  10206. length: function () {
  10207. return tasks.length;
  10208. },
  10209. running: function () {
  10210. return working;
  10211. }
  10212. };
  10213. return cargo;
  10214. };
  10215. var _console_fn = function (name) {
  10216. return function (fn) {
  10217. var args = Array.prototype.slice.call(arguments, 1);
  10218. fn.apply(null, args.concat([function (err) {
  10219. var args = Array.prototype.slice.call(arguments, 1);
  10220. if (typeof console !== 'undefined') {
  10221. if (err) {
  10222. if (console.error) {
  10223. console.error(err);
  10224. }
  10225. }
  10226. else if (console[name]) {
  10227. _each(args, function (x) {
  10228. console[name](x);
  10229. });
  10230. }
  10231. }
  10232. }]));
  10233. };
  10234. };
  10235. async.log = _console_fn('log');
  10236. async.dir = _console_fn('dir');
  10237. /*async.info = _console_fn('info');
  10238. async.warn = _console_fn('warn');
  10239. async.error = _console_fn('error');*/
  10240. async.memoize = function (fn, hasher) {
  10241. var memo = {};
  10242. var queues = {};
  10243. hasher = hasher || function (x) {
  10244. return x;
  10245. };
  10246. var memoized = function () {
  10247. var args = Array.prototype.slice.call(arguments);
  10248. var callback = args.pop();
  10249. var key = hasher.apply(null, args);
  10250. if (key in memo) {
  10251. async.nextTick(function () {
  10252. callback.apply(null, memo[key]);
  10253. });
  10254. }
  10255. else if (key in queues) {
  10256. queues[key].push(callback);
  10257. }
  10258. else {
  10259. queues[key] = [callback];
  10260. fn.apply(null, args.concat([function () {
  10261. memo[key] = arguments;
  10262. var q = queues[key];
  10263. delete queues[key];
  10264. for (var i = 0, l = q.length; i < l; i++) {
  10265. q[i].apply(null, arguments);
  10266. }
  10267. }]));
  10268. }
  10269. };
  10270. memoized.memo = memo;
  10271. memoized.unmemoized = fn;
  10272. return memoized;
  10273. };
  10274. async.unmemoize = function (fn) {
  10275. return function () {
  10276. return (fn.unmemoized || fn).apply(null, arguments);
  10277. };
  10278. };
  10279. async.times = function (count, iterator, callback) {
  10280. var counter = [];
  10281. for (var i = 0; i < count; i++) {
  10282. counter.push(i);
  10283. }
  10284. return async.map(counter, iterator, callback);
  10285. };
  10286. async.timesSeries = function (count, iterator, callback) {
  10287. var counter = [];
  10288. for (var i = 0; i < count; i++) {
  10289. counter.push(i);
  10290. }
  10291. return async.mapSeries(counter, iterator, callback);
  10292. };
  10293. async.seq = function (/* functions... */) {
  10294. var fns = arguments;
  10295. return function () {
  10296. var that = this;
  10297. var args = Array.prototype.slice.call(arguments);
  10298. var callback = args.pop();
  10299. async.reduce(fns, args, function (newargs, fn, cb) {
  10300. fn.apply(that, newargs.concat([function () {
  10301. var err = arguments[0];
  10302. var nextargs = Array.prototype.slice.call(arguments, 1);
  10303. cb(err, nextargs);
  10304. }]))
  10305. },
  10306. function (err, results) {
  10307. callback.apply(that, [err].concat(results));
  10308. });
  10309. };
  10310. };
  10311. async.compose = function (/* functions... */) {
  10312. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  10313. };
  10314. var _applyEach = function (eachfn, fns /*args...*/) {
  10315. var go = function () {
  10316. var that = this;
  10317. var args = Array.prototype.slice.call(arguments);
  10318. var callback = args.pop();
  10319. return eachfn(fns, function (fn, cb) {
  10320. fn.apply(that, args.concat([cb]));
  10321. },
  10322. callback);
  10323. };
  10324. if (arguments.length > 2) {
  10325. var args = Array.prototype.slice.call(arguments, 2);
  10326. return go.apply(this, args);
  10327. }
  10328. else {
  10329. return go;
  10330. }
  10331. };
  10332. async.applyEach = doParallel(_applyEach);
  10333. async.applyEachSeries = doSeries(_applyEach);
  10334. async.forever = function (fn, callback) {
  10335. function next(err) {
  10336. if (err) {
  10337. if (callback) {
  10338. return callback(err);
  10339. }
  10340. throw err;
  10341. }
  10342. fn(next);
  10343. }
  10344. next();
  10345. };
  10346. // Node.js
  10347. if (typeof module !== 'undefined' && module.exports) {
  10348. module.exports = async;
  10349. }
  10350. // AMD / RequireJS
  10351. else if (typeof define !== 'undefined' && define.amd) {
  10352. define([], function () {
  10353. return async;
  10354. });
  10355. }
  10356. // included directly via <script> tag
  10357. else {
  10358. root.async = async;
  10359. }
  10360. }());
  10361. }).call(this,require('_process'))
  10362. },{"_process":40}],39:[function(require,module,exports){
  10363. // Copyright Joyent, Inc. and other Node contributors.
  10364. //
  10365. // Permission is hereby granted, free of charge, to any person obtaining a
  10366. // copy of this software and associated documentation files (the
  10367. // "Software"), to deal in the Software without restriction, including
  10368. // without limitation the rights to use, copy, modify, merge, publish,
  10369. // distribute, sublicense, and/or sell copies of the Software, and to permit
  10370. // persons to whom the Software is furnished to do so, subject to the
  10371. // following conditions:
  10372. //
  10373. // The above copyright notice and this permission notice shall be included
  10374. // in all copies or substantial portions of the Software.
  10375. //
  10376. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  10377. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  10378. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  10379. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  10380. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  10381. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  10382. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  10383. function EventEmitter() {
  10384. this._events = this._events || {};
  10385. this._maxListeners = this._maxListeners || undefined;
  10386. }
  10387. module.exports = EventEmitter;
  10388. // Backwards-compat with node 0.10.x
  10389. EventEmitter.EventEmitter = EventEmitter;
  10390. EventEmitter.prototype._events = undefined;
  10391. EventEmitter.prototype._maxListeners = undefined;
  10392. // By default EventEmitters will print a warning if more than 10 listeners are
  10393. // added to it. This is a useful default which helps finding memory leaks.
  10394. EventEmitter.defaultMaxListeners = 10;
  10395. // Obviously not all Emitters should be limited to 10. This function allows
  10396. // that to be increased. Set to zero for unlimited.
  10397. EventEmitter.prototype.setMaxListeners = function(n) {
  10398. if (!isNumber(n) || n < 0 || isNaN(n))
  10399. throw TypeError('n must be a positive number');
  10400. this._maxListeners = n;
  10401. return this;
  10402. };
  10403. EventEmitter.prototype.emit = function(type) {
  10404. var er, handler, len, args, i, listeners;
  10405. if (!this._events)
  10406. this._events = {};
  10407. // If there is no 'error' event listener then throw.
  10408. if (type === 'error') {
  10409. if (!this._events.error ||
  10410. (isObject(this._events.error) && !this._events.error.length)) {
  10411. er = arguments[1];
  10412. if (er instanceof Error) {
  10413. throw er; // Unhandled 'error' event
  10414. }
  10415. throw TypeError('Uncaught, unspecified "error" event.');
  10416. }
  10417. }
  10418. handler = this._events[type];
  10419. if (isUndefined(handler))
  10420. return false;
  10421. if (isFunction(handler)) {
  10422. switch (arguments.length) {
  10423. // fast cases
  10424. case 1:
  10425. handler.call(this);
  10426. break;
  10427. case 2:
  10428. handler.call(this, arguments[1]);
  10429. break;
  10430. case 3:
  10431. handler.call(this, arguments[1], arguments[2]);
  10432. break;
  10433. // slower
  10434. default:
  10435. len = arguments.length;
  10436. args = new Array(len - 1);
  10437. for (i = 1; i < len; i++)
  10438. args[i - 1] = arguments[i];
  10439. handler.apply(this, args);
  10440. }
  10441. } else if (isObject(handler)) {
  10442. len = arguments.length;
  10443. args = new Array(len - 1);
  10444. for (i = 1; i < len; i++)
  10445. args[i - 1] = arguments[i];
  10446. listeners = handler.slice();
  10447. len = listeners.length;
  10448. for (i = 0; i < len; i++)
  10449. listeners[i].apply(this, args);
  10450. }
  10451. return true;
  10452. };
  10453. EventEmitter.prototype.addListener = function(type, listener) {
  10454. var m;
  10455. if (!isFunction(listener))
  10456. throw TypeError('listener must be a function');
  10457. if (!this._events)
  10458. this._events = {};
  10459. // To avoid recursion in the case that type === "newListener"! Before
  10460. // adding it to the listeners, first emit "newListener".
  10461. if (this._events.newListener)
  10462. this.emit('newListener', type,
  10463. isFunction(listener.listener) ?
  10464. listener.listener : listener);
  10465. if (!this._events[type])
  10466. // Optimize the case of one listener. Don't need the extra array object.
  10467. this._events[type] = listener;
  10468. else if (isObject(this._events[type]))
  10469. // If we've already got an array, just append.
  10470. this._events[type].push(listener);
  10471. else
  10472. // Adding the second element, need to change to array.
  10473. this._events[type] = [this._events[type], listener];
  10474. // Check for listener leak
  10475. if (isObject(this._events[type]) && !this._events[type].warned) {
  10476. var m;
  10477. if (!isUndefined(this._maxListeners)) {
  10478. m = this._maxListeners;
  10479. } else {
  10480. m = EventEmitter.defaultMaxListeners;
  10481. }
  10482. if (m && m > 0 && this._events[type].length > m) {
  10483. this._events[type].warned = true;
  10484. console.error('(node) warning: possible EventEmitter memory ' +
  10485. 'leak detected. %d listeners added. ' +
  10486. 'Use emitter.setMaxListeners() to increase limit.',
  10487. this._events[type].length);
  10488. if (typeof console.trace === 'function') {
  10489. // not supported in IE 10
  10490. console.trace();
  10491. }
  10492. }
  10493. }
  10494. return this;
  10495. };
  10496. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  10497. EventEmitter.prototype.once = function(type, listener) {
  10498. if (!isFunction(listener))
  10499. throw TypeError('listener must be a function');
  10500. var fired = false;
  10501. function g() {
  10502. this.removeListener(type, g);
  10503. if (!fired) {
  10504. fired = true;
  10505. listener.apply(this, arguments);
  10506. }
  10507. }
  10508. g.listener = listener;
  10509. this.on(type, g);
  10510. return this;
  10511. };
  10512. // emits a 'removeListener' event iff the listener was removed
  10513. EventEmitter.prototype.removeListener = function(type, listener) {
  10514. var list, position, length, i;
  10515. if (!isFunction(listener))
  10516. throw TypeError('listener must be a function');
  10517. if (!this._events || !this._events[type])
  10518. return this;
  10519. list = this._events[type];
  10520. length = list.length;
  10521. position = -1;
  10522. if (list === listener ||
  10523. (isFunction(list.listener) && list.listener === listener)) {
  10524. delete this._events[type];
  10525. if (this._events.removeListener)
  10526. this.emit('removeListener', type, listener);
  10527. } else if (isObject(list)) {
  10528. for (i = length; i-- > 0;) {
  10529. if (list[i] === listener ||
  10530. (list[i].listener && list[i].listener === listener)) {
  10531. position = i;
  10532. break;
  10533. }
  10534. }
  10535. if (position < 0)
  10536. return this;
  10537. if (list.length === 1) {
  10538. list.length = 0;
  10539. delete this._events[type];
  10540. } else {
  10541. list.splice(position, 1);
  10542. }
  10543. if (this._events.removeListener)
  10544. this.emit('removeListener', type, listener);
  10545. }
  10546. return this;
  10547. };
  10548. EventEmitter.prototype.removeAllListeners = function(type) {
  10549. var key, listeners;
  10550. if (!this._events)
  10551. return this;
  10552. // not listening for removeListener, no need to emit
  10553. if (!this._events.removeListener) {
  10554. if (arguments.length === 0)
  10555. this._events = {};
  10556. else if (this._events[type])
  10557. delete this._events[type];
  10558. return this;
  10559. }
  10560. // emit removeListener for all listeners on all events
  10561. if (arguments.length === 0) {
  10562. for (key in this._events) {
  10563. if (key === 'removeListener') continue;
  10564. this.removeAllListeners(key);
  10565. }
  10566. this.removeAllListeners('removeListener');
  10567. this._events = {};
  10568. return this;
  10569. }
  10570. listeners = this._events[type];
  10571. if (isFunction(listeners)) {
  10572. this.removeListener(type, listeners);
  10573. } else {
  10574. // LIFO order
  10575. while (listeners.length)
  10576. this.removeListener(type, listeners[listeners.length - 1]);
  10577. }
  10578. delete this._events[type];
  10579. return this;
  10580. };
  10581. EventEmitter.prototype.listeners = function(type) {
  10582. var ret;
  10583. if (!this._events || !this._events[type])
  10584. ret = [];
  10585. else if (isFunction(this._events[type]))
  10586. ret = [this._events[type]];
  10587. else
  10588. ret = this._events[type].slice();
  10589. return ret;
  10590. };
  10591. EventEmitter.listenerCount = function(emitter, type) {
  10592. var ret;
  10593. if (!emitter._events || !emitter._events[type])
  10594. ret = 0;
  10595. else if (isFunction(emitter._events[type]))
  10596. ret = 1;
  10597. else
  10598. ret = emitter._events[type].length;
  10599. return ret;
  10600. };
  10601. function isFunction(arg) {
  10602. return typeof arg === 'function';
  10603. }
  10604. function isNumber(arg) {
  10605. return typeof arg === 'number';
  10606. }
  10607. function isObject(arg) {
  10608. return typeof arg === 'object' && arg !== null;
  10609. }
  10610. function isUndefined(arg) {
  10611. return arg === void 0;
  10612. }
  10613. },{}],40:[function(require,module,exports){
  10614. // shim for using process in browser
  10615. var process = module.exports = {};
  10616. var queue = [];
  10617. var draining = false;
  10618. var currentQueue;
  10619. var queueIndex = -1;
  10620. function cleanUpNextTick() {
  10621. draining = false;
  10622. if (currentQueue.length) {
  10623. queue = currentQueue.concat(queue);
  10624. } else {
  10625. queueIndex = -1;
  10626. }
  10627. if (queue.length) {
  10628. drainQueue();
  10629. }
  10630. }
  10631. function drainQueue() {
  10632. if (draining) {
  10633. return;
  10634. }
  10635. var timeout = setTimeout(cleanUpNextTick);
  10636. draining = true;
  10637. var len = queue.length;
  10638. while(len) {
  10639. currentQueue = queue;
  10640. queue = [];
  10641. while (++queueIndex < len) {
  10642. if (currentQueue) {
  10643. currentQueue[queueIndex].run();
  10644. }
  10645. }
  10646. queueIndex = -1;
  10647. len = queue.length;
  10648. }
  10649. currentQueue = null;
  10650. draining = false;
  10651. clearTimeout(timeout);
  10652. }
  10653. process.nextTick = function (fun) {
  10654. var args = new Array(arguments.length - 1);
  10655. if (arguments.length > 1) {
  10656. for (var i = 1; i < arguments.length; i++) {
  10657. args[i - 1] = arguments[i];
  10658. }
  10659. }
  10660. queue.push(new Item(fun, args));
  10661. if (queue.length === 1 && !draining) {
  10662. setTimeout(drainQueue, 0);
  10663. }
  10664. };
  10665. // v8 likes predictible objects
  10666. function Item(fun, array) {
  10667. this.fun = fun;
  10668. this.array = array;
  10669. }
  10670. Item.prototype.run = function () {
  10671. this.fun.apply(null, this.array);
  10672. };
  10673. process.title = 'browser';
  10674. process.browser = true;
  10675. process.env = {};
  10676. process.argv = [];
  10677. process.version = ''; // empty string to avoid regexp issues
  10678. process.versions = {};
  10679. function noop() {}
  10680. process.on = noop;
  10681. process.addListener = noop;
  10682. process.once = noop;
  10683. process.off = noop;
  10684. process.removeListener = noop;
  10685. process.removeAllListeners = noop;
  10686. process.emit = noop;
  10687. process.binding = function (name) {
  10688. throw new Error('process.binding is not supported');
  10689. };
  10690. process.cwd = function () { return '/' };
  10691. process.chdir = function (dir) {
  10692. throw new Error('process.chdir is not supported');
  10693. };
  10694. process.umask = function() { return 0; };
  10695. },{}],41:[function(require,module,exports){
  10696. (function (process,global){
  10697. /*!
  10698. * @overview es6-promise - a tiny implementation of Promises/A+.
  10699. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  10700. * @license Licensed under MIT license
  10701. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  10702. * @version 3.0.2
  10703. */
  10704. (function() {
  10705. "use strict";
  10706. function lib$es6$promise$utils$$objectOrFunction(x) {
  10707. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  10708. }
  10709. function lib$es6$promise$utils$$isFunction(x) {
  10710. return typeof x === 'function';
  10711. }
  10712. function lib$es6$promise$utils$$isMaybeThenable(x) {
  10713. return typeof x === 'object' && x !== null;
  10714. }
  10715. var lib$es6$promise$utils$$_isArray;
  10716. if (!Array.isArray) {
  10717. lib$es6$promise$utils$$_isArray = function (x) {
  10718. return Object.prototype.toString.call(x) === '[object Array]';
  10719. };
  10720. } else {
  10721. lib$es6$promise$utils$$_isArray = Array.isArray;
  10722. }
  10723. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  10724. var lib$es6$promise$asap$$len = 0;
  10725. var lib$es6$promise$asap$$toString = {}.toString;
  10726. var lib$es6$promise$asap$$vertxNext;
  10727. var lib$es6$promise$asap$$customSchedulerFn;
  10728. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  10729. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  10730. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  10731. lib$es6$promise$asap$$len += 2;
  10732. if (lib$es6$promise$asap$$len === 2) {
  10733. // If len is 2, that means that we need to schedule an async flush.
  10734. // If additional callbacks are queued before the queue is flushed, they
  10735. // will be processed by this flush that we are scheduling.
  10736. if (lib$es6$promise$asap$$customSchedulerFn) {
  10737. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  10738. } else {
  10739. lib$es6$promise$asap$$scheduleFlush();
  10740. }
  10741. }
  10742. }
  10743. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  10744. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  10745. }
  10746. function lib$es6$promise$asap$$setAsap(asapFn) {
  10747. lib$es6$promise$asap$$asap = asapFn;
  10748. }
  10749. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  10750. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  10751. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  10752. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  10753. // test for web worker but not in IE10
  10754. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  10755. typeof importScripts !== 'undefined' &&
  10756. typeof MessageChannel !== 'undefined';
  10757. // node
  10758. function lib$es6$promise$asap$$useNextTick() {
  10759. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  10760. // see https://github.com/cujojs/when/issues/410 for details
  10761. return function() {
  10762. process.nextTick(lib$es6$promise$asap$$flush);
  10763. };
  10764. }
  10765. // vertx
  10766. function lib$es6$promise$asap$$useVertxTimer() {
  10767. return function() {
  10768. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  10769. };
  10770. }
  10771. function lib$es6$promise$asap$$useMutationObserver() {
  10772. var iterations = 0;
  10773. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  10774. var node = document.createTextNode('');
  10775. observer.observe(node, { characterData: true });
  10776. return function() {
  10777. node.data = (iterations = ++iterations % 2);
  10778. };
  10779. }
  10780. // web worker
  10781. function lib$es6$promise$asap$$useMessageChannel() {
  10782. var channel = new MessageChannel();
  10783. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  10784. return function () {
  10785. channel.port2.postMessage(0);
  10786. };
  10787. }
  10788. function lib$es6$promise$asap$$useSetTimeout() {
  10789. return function() {
  10790. setTimeout(lib$es6$promise$asap$$flush, 1);
  10791. };
  10792. }
  10793. var lib$es6$promise$asap$$queue = new Array(1000);
  10794. function lib$es6$promise$asap$$flush() {
  10795. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  10796. var callback = lib$es6$promise$asap$$queue[i];
  10797. var arg = lib$es6$promise$asap$$queue[i+1];
  10798. callback(arg);
  10799. lib$es6$promise$asap$$queue[i] = undefined;
  10800. lib$es6$promise$asap$$queue[i+1] = undefined;
  10801. }
  10802. lib$es6$promise$asap$$len = 0;
  10803. }
  10804. function lib$es6$promise$asap$$attemptVertx() {
  10805. try {
  10806. var r = require;
  10807. var vertx = r('vertx');
  10808. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  10809. return lib$es6$promise$asap$$useVertxTimer();
  10810. } catch(e) {
  10811. return lib$es6$promise$asap$$useSetTimeout();
  10812. }
  10813. }
  10814. var lib$es6$promise$asap$$scheduleFlush;
  10815. // Decide what async method to use to triggering processing of queued callbacks:
  10816. if (lib$es6$promise$asap$$isNode) {
  10817. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  10818. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  10819. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  10820. } else if (lib$es6$promise$asap$$isWorker) {
  10821. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  10822. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  10823. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  10824. } else {
  10825. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  10826. }
  10827. function lib$es6$promise$$internal$$noop() {}
  10828. var lib$es6$promise$$internal$$PENDING = void 0;
  10829. var lib$es6$promise$$internal$$FULFILLED = 1;
  10830. var lib$es6$promise$$internal$$REJECTED = 2;
  10831. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  10832. function lib$es6$promise$$internal$$selfFulfillment() {
  10833. return new TypeError("You cannot resolve a promise with itself");
  10834. }
  10835. function lib$es6$promise$$internal$$cannotReturnOwn() {
  10836. return new TypeError('A promises callback cannot return that same promise.');
  10837. }
  10838. function lib$es6$promise$$internal$$getThen(promise) {
  10839. try {
  10840. return promise.then;
  10841. } catch(error) {
  10842. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  10843. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  10844. }
  10845. }
  10846. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  10847. try {
  10848. then.call(value, fulfillmentHandler, rejectionHandler);
  10849. } catch(e) {
  10850. return e;
  10851. }
  10852. }
  10853. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  10854. lib$es6$promise$asap$$asap(function(promise) {
  10855. var sealed = false;
  10856. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  10857. if (sealed) { return; }
  10858. sealed = true;
  10859. if (thenable !== value) {
  10860. lib$es6$promise$$internal$$resolve(promise, value);
  10861. } else {
  10862. lib$es6$promise$$internal$$fulfill(promise, value);
  10863. }
  10864. }, function(reason) {
  10865. if (sealed) { return; }
  10866. sealed = true;
  10867. lib$es6$promise$$internal$$reject(promise, reason);
  10868. }, 'Settle: ' + (promise._label || ' unknown promise'));
  10869. if (!sealed && error) {
  10870. sealed = true;
  10871. lib$es6$promise$$internal$$reject(promise, error);
  10872. }
  10873. }, promise);
  10874. }
  10875. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  10876. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  10877. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  10878. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  10879. lib$es6$promise$$internal$$reject(promise, thenable._result);
  10880. } else {
  10881. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  10882. lib$es6$promise$$internal$$resolve(promise, value);
  10883. }, function(reason) {
  10884. lib$es6$promise$$internal$$reject(promise, reason);
  10885. });
  10886. }
  10887. }
  10888. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  10889. if (maybeThenable.constructor === promise.constructor) {
  10890. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  10891. } else {
  10892. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  10893. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  10894. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  10895. } else if (then === undefined) {
  10896. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  10897. } else if (lib$es6$promise$utils$$isFunction(then)) {
  10898. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  10899. } else {
  10900. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  10901. }
  10902. }
  10903. }
  10904. function lib$es6$promise$$internal$$resolve(promise, value) {
  10905. if (promise === value) {
  10906. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  10907. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  10908. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  10909. } else {
  10910. lib$es6$promise$$internal$$fulfill(promise, value);
  10911. }
  10912. }
  10913. function lib$es6$promise$$internal$$publishRejection(promise) {
  10914. if (promise._onerror) {
  10915. promise._onerror(promise._result);
  10916. }
  10917. lib$es6$promise$$internal$$publish(promise);
  10918. }
  10919. function lib$es6$promise$$internal$$fulfill(promise, value) {
  10920. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  10921. promise._result = value;
  10922. promise._state = lib$es6$promise$$internal$$FULFILLED;
  10923. if (promise._subscribers.length !== 0) {
  10924. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  10925. }
  10926. }
  10927. function lib$es6$promise$$internal$$reject(promise, reason) {
  10928. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  10929. promise._state = lib$es6$promise$$internal$$REJECTED;
  10930. promise._result = reason;
  10931. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  10932. }
  10933. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  10934. var subscribers = parent._subscribers;
  10935. var length = subscribers.length;
  10936. parent._onerror = null;
  10937. subscribers[length] = child;
  10938. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  10939. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  10940. if (length === 0 && parent._state) {
  10941. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  10942. }
  10943. }
  10944. function lib$es6$promise$$internal$$publish(promise) {
  10945. var subscribers = promise._subscribers;
  10946. var settled = promise._state;
  10947. if (subscribers.length === 0) { return; }
  10948. var child, callback, detail = promise._result;
  10949. for (var i = 0; i < subscribers.length; i += 3) {
  10950. child = subscribers[i];
  10951. callback = subscribers[i + settled];
  10952. if (child) {
  10953. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  10954. } else {
  10955. callback(detail);
  10956. }
  10957. }
  10958. promise._subscribers.length = 0;
  10959. }
  10960. function lib$es6$promise$$internal$$ErrorObject() {
  10961. this.error = null;
  10962. }
  10963. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  10964. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  10965. try {
  10966. return callback(detail);
  10967. } catch(e) {
  10968. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  10969. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  10970. }
  10971. }
  10972. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  10973. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  10974. value, error, succeeded, failed;
  10975. if (hasCallback) {
  10976. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  10977. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  10978. failed = true;
  10979. error = value.error;
  10980. value = null;
  10981. } else {
  10982. succeeded = true;
  10983. }
  10984. if (promise === value) {
  10985. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  10986. return;
  10987. }
  10988. } else {
  10989. value = detail;
  10990. succeeded = true;
  10991. }
  10992. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  10993. // noop
  10994. } else if (hasCallback && succeeded) {
  10995. lib$es6$promise$$internal$$resolve(promise, value);
  10996. } else if (failed) {
  10997. lib$es6$promise$$internal$$reject(promise, error);
  10998. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  10999. lib$es6$promise$$internal$$fulfill(promise, value);
  11000. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  11001. lib$es6$promise$$internal$$reject(promise, value);
  11002. }
  11003. }
  11004. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  11005. try {
  11006. resolver(function resolvePromise(value){
  11007. lib$es6$promise$$internal$$resolve(promise, value);
  11008. }, function rejectPromise(reason) {
  11009. lib$es6$promise$$internal$$reject(promise, reason);
  11010. });
  11011. } catch(e) {
  11012. lib$es6$promise$$internal$$reject(promise, e);
  11013. }
  11014. }
  11015. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  11016. var enumerator = this;
  11017. enumerator._instanceConstructor = Constructor;
  11018. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  11019. if (enumerator._validateInput(input)) {
  11020. enumerator._input = input;
  11021. enumerator.length = input.length;
  11022. enumerator._remaining = input.length;
  11023. enumerator._init();
  11024. if (enumerator.length === 0) {
  11025. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  11026. } else {
  11027. enumerator.length = enumerator.length || 0;
  11028. enumerator._enumerate();
  11029. if (enumerator._remaining === 0) {
  11030. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  11031. }
  11032. }
  11033. } else {
  11034. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  11035. }
  11036. }
  11037. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  11038. return lib$es6$promise$utils$$isArray(input);
  11039. };
  11040. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  11041. return new Error('Array Methods must be provided an Array');
  11042. };
  11043. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  11044. this._result = new Array(this.length);
  11045. };
  11046. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  11047. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  11048. var enumerator = this;
  11049. var length = enumerator.length;
  11050. var promise = enumerator.promise;
  11051. var input = enumerator._input;
  11052. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  11053. enumerator._eachEntry(input[i], i);
  11054. }
  11055. };
  11056. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  11057. var enumerator = this;
  11058. var c = enumerator._instanceConstructor;
  11059. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  11060. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  11061. entry._onerror = null;
  11062. enumerator._settledAt(entry._state, i, entry._result);
  11063. } else {
  11064. enumerator._willSettleAt(c.resolve(entry), i);
  11065. }
  11066. } else {
  11067. enumerator._remaining--;
  11068. enumerator._result[i] = entry;
  11069. }
  11070. };
  11071. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  11072. var enumerator = this;
  11073. var promise = enumerator.promise;
  11074. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  11075. enumerator._remaining--;
  11076. if (state === lib$es6$promise$$internal$$REJECTED) {
  11077. lib$es6$promise$$internal$$reject(promise, value);
  11078. } else {
  11079. enumerator._result[i] = value;
  11080. }
  11081. }
  11082. if (enumerator._remaining === 0) {
  11083. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  11084. }
  11085. };
  11086. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  11087. var enumerator = this;
  11088. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  11089. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  11090. }, function(reason) {
  11091. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  11092. });
  11093. };
  11094. function lib$es6$promise$promise$all$$all(entries) {
  11095. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  11096. }
  11097. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  11098. function lib$es6$promise$promise$race$$race(entries) {
  11099. /*jshint validthis:true */
  11100. var Constructor = this;
  11101. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  11102. if (!lib$es6$promise$utils$$isArray(entries)) {
  11103. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  11104. return promise;
  11105. }
  11106. var length = entries.length;
  11107. function onFulfillment(value) {
  11108. lib$es6$promise$$internal$$resolve(promise, value);
  11109. }
  11110. function onRejection(reason) {
  11111. lib$es6$promise$$internal$$reject(promise, reason);
  11112. }
  11113. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  11114. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  11115. }
  11116. return promise;
  11117. }
  11118. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  11119. function lib$es6$promise$promise$resolve$$resolve(object) {
  11120. /*jshint validthis:true */
  11121. var Constructor = this;
  11122. if (object && typeof object === 'object' && object.constructor === Constructor) {
  11123. return object;
  11124. }
  11125. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  11126. lib$es6$promise$$internal$$resolve(promise, object);
  11127. return promise;
  11128. }
  11129. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  11130. function lib$es6$promise$promise$reject$$reject(reason) {
  11131. /*jshint validthis:true */
  11132. var Constructor = this;
  11133. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  11134. lib$es6$promise$$internal$$reject(promise, reason);
  11135. return promise;
  11136. }
  11137. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  11138. var lib$es6$promise$promise$$counter = 0;
  11139. function lib$es6$promise$promise$$needsResolver() {
  11140. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  11141. }
  11142. function lib$es6$promise$promise$$needsNew() {
  11143. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  11144. }
  11145. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  11146. /**
  11147. Promise objects represent the eventual result of an asynchronous operation. The
  11148. primary way of interacting with a promise is through its `then` method, which
  11149. registers callbacks to receive either a promise's eventual value or the reason
  11150. why the promise cannot be fulfilled.
  11151. Terminology
  11152. -----------
  11153. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  11154. - `thenable` is an object or function that defines a `then` method.
  11155. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  11156. - `exception` is a value that is thrown using the throw statement.
  11157. - `reason` is a value that indicates why a promise was rejected.
  11158. - `settled` the final resting state of a promise, fulfilled or rejected.
  11159. A promise can be in one of three states: pending, fulfilled, or rejected.
  11160. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  11161. state. Promises that are rejected have a rejection reason and are in the
  11162. rejected state. A fulfillment value is never a thenable.
  11163. Promises can also be said to *resolve* a value. If this value is also a
  11164. promise, then the original promise's settled state will match the value's
  11165. settled state. So a promise that *resolves* a promise that rejects will
  11166. itself reject, and a promise that *resolves* a promise that fulfills will
  11167. itself fulfill.
  11168. Basic Usage:
  11169. ------------
  11170. ```js
  11171. var promise = new Promise(function(resolve, reject) {
  11172. // on success
  11173. resolve(value);
  11174. // on failure
  11175. reject(reason);
  11176. });
  11177. promise.then(function(value) {
  11178. // on fulfillment
  11179. }, function(reason) {
  11180. // on rejection
  11181. });
  11182. ```
  11183. Advanced Usage:
  11184. ---------------
  11185. Promises shine when abstracting away asynchronous interactions such as
  11186. `XMLHttpRequest`s.
  11187. ```js
  11188. function getJSON(url) {
  11189. return new Promise(function(resolve, reject){
  11190. var xhr = new XMLHttpRequest();
  11191. xhr.open('GET', url);
  11192. xhr.onreadystatechange = handler;
  11193. xhr.responseType = 'json';
  11194. xhr.setRequestHeader('Accept', 'application/json');
  11195. xhr.send();
  11196. function handler() {
  11197. if (this.readyState === this.DONE) {
  11198. if (this.status === 200) {
  11199. resolve(this.response);
  11200. } else {
  11201. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  11202. }
  11203. }
  11204. };
  11205. });
  11206. }
  11207. getJSON('/posts.json').then(function(json) {
  11208. // on fulfillment
  11209. }, function(reason) {
  11210. // on rejection
  11211. });
  11212. ```
  11213. Unlike callbacks, promises are great composable primitives.
  11214. ```js
  11215. Promise.all([
  11216. getJSON('/posts'),
  11217. getJSON('/comments')
  11218. ]).then(function(values){
  11219. values[0] // => postsJSON
  11220. values[1] // => commentsJSON
  11221. return values;
  11222. });
  11223. ```
  11224. @class Promise
  11225. @param {function} resolver
  11226. Useful for tooling.
  11227. @constructor
  11228. */
  11229. function lib$es6$promise$promise$$Promise(resolver) {
  11230. this._id = lib$es6$promise$promise$$counter++;
  11231. this._state = undefined;
  11232. this._result = undefined;
  11233. this._subscribers = [];
  11234. if (lib$es6$promise$$internal$$noop !== resolver) {
  11235. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  11236. lib$es6$promise$promise$$needsResolver();
  11237. }
  11238. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  11239. lib$es6$promise$promise$$needsNew();
  11240. }
  11241. lib$es6$promise$$internal$$initializePromise(this, resolver);
  11242. }
  11243. }
  11244. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  11245. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  11246. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  11247. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  11248. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  11249. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  11250. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  11251. lib$es6$promise$promise$$Promise.prototype = {
  11252. constructor: lib$es6$promise$promise$$Promise,
  11253. /**
  11254. The primary way of interacting with a promise is through its `then` method,
  11255. which registers callbacks to receive either a promise's eventual value or the
  11256. reason why the promise cannot be fulfilled.
  11257. ```js
  11258. findUser().then(function(user){
  11259. // user is available
  11260. }, function(reason){
  11261. // user is unavailable, and you are given the reason why
  11262. });
  11263. ```
  11264. Chaining
  11265. --------
  11266. The return value of `then` is itself a promise. This second, 'downstream'
  11267. promise is resolved with the return value of the first promise's fulfillment
  11268. or rejection handler, or rejected if the handler throws an exception.
  11269. ```js
  11270. findUser().then(function (user) {
  11271. return user.name;
  11272. }, function (reason) {
  11273. return 'default name';
  11274. }).then(function (userName) {
  11275. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  11276. // will be `'default name'`
  11277. });
  11278. findUser().then(function (user) {
  11279. throw new Error('Found user, but still unhappy');
  11280. }, function (reason) {
  11281. throw new Error('`findUser` rejected and we're unhappy');
  11282. }).then(function (value) {
  11283. // never reached
  11284. }, function (reason) {
  11285. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  11286. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  11287. });
  11288. ```
  11289. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  11290. ```js
  11291. findUser().then(function (user) {
  11292. throw new PedagogicalException('Upstream error');
  11293. }).then(function (value) {
  11294. // never reached
  11295. }).then(function (value) {
  11296. // never reached
  11297. }, function (reason) {
  11298. // The `PedgagocialException` is propagated all the way down to here
  11299. });
  11300. ```
  11301. Assimilation
  11302. ------------
  11303. Sometimes the value you want to propagate to a downstream promise can only be
  11304. retrieved asynchronously. This can be achieved by returning a promise in the
  11305. fulfillment or rejection handler. The downstream promise will then be pending
  11306. until the returned promise is settled. This is called *assimilation*.
  11307. ```js
  11308. findUser().then(function (user) {
  11309. return findCommentsByAuthor(user);
  11310. }).then(function (comments) {
  11311. // The user's comments are now available
  11312. });
  11313. ```
  11314. If the assimliated promise rejects, then the downstream promise will also reject.
  11315. ```js
  11316. findUser().then(function (user) {
  11317. return findCommentsByAuthor(user);
  11318. }).then(function (comments) {
  11319. // If `findCommentsByAuthor` fulfills, we'll have the value here
  11320. }, function (reason) {
  11321. // If `findCommentsByAuthor` rejects, we'll have the reason here
  11322. });
  11323. ```
  11324. Simple Example
  11325. --------------
  11326. Synchronous Example
  11327. ```javascript
  11328. var result;
  11329. try {
  11330. result = findResult();
  11331. // success
  11332. } catch(reason) {
  11333. // failure
  11334. }
  11335. ```
  11336. Errback Example
  11337. ```js
  11338. findResult(function(result, err){
  11339. if (err) {
  11340. // failure
  11341. } else {
  11342. // success
  11343. }
  11344. });
  11345. ```
  11346. Promise Example;
  11347. ```javascript
  11348. findResult().then(function(result){
  11349. // success
  11350. }, function(reason){
  11351. // failure
  11352. });
  11353. ```
  11354. Advanced Example
  11355. --------------
  11356. Synchronous Example
  11357. ```javascript
  11358. var author, books;
  11359. try {
  11360. author = findAuthor();
  11361. books = findBooksByAuthor(author);
  11362. // success
  11363. } catch(reason) {
  11364. // failure
  11365. }
  11366. ```
  11367. Errback Example
  11368. ```js
  11369. function foundBooks(books) {
  11370. }
  11371. function failure(reason) {
  11372. }
  11373. findAuthor(function(author, err){
  11374. if (err) {
  11375. failure(err);
  11376. // failure
  11377. } else {
  11378. try {
  11379. findBoooksByAuthor(author, function(books, err) {
  11380. if (err) {
  11381. failure(err);
  11382. } else {
  11383. try {
  11384. foundBooks(books);
  11385. } catch(reason) {
  11386. failure(reason);
  11387. }
  11388. }
  11389. });
  11390. } catch(error) {
  11391. failure(err);
  11392. }
  11393. // success
  11394. }
  11395. });
  11396. ```
  11397. Promise Example;
  11398. ```javascript
  11399. findAuthor().
  11400. then(findBooksByAuthor).
  11401. then(function(books){
  11402. // found books
  11403. }).catch(function(reason){
  11404. // something went wrong
  11405. });
  11406. ```
  11407. @method then
  11408. @param {Function} onFulfilled
  11409. @param {Function} onRejected
  11410. Useful for tooling.
  11411. @return {Promise}
  11412. */
  11413. then: function(onFulfillment, onRejection) {
  11414. var parent = this;
  11415. var state = parent._state;
  11416. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  11417. return this;
  11418. }
  11419. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  11420. var result = parent._result;
  11421. if (state) {
  11422. var callback = arguments[state - 1];
  11423. lib$es6$promise$asap$$asap(function(){
  11424. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  11425. });
  11426. } else {
  11427. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  11428. }
  11429. return child;
  11430. },
  11431. /**
  11432. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  11433. as the catch block of a try/catch statement.
  11434. ```js
  11435. function findAuthor(){
  11436. throw new Error('couldn't find that author');
  11437. }
  11438. // synchronous
  11439. try {
  11440. findAuthor();
  11441. } catch(reason) {
  11442. // something went wrong
  11443. }
  11444. // async with promises
  11445. findAuthor().catch(function(reason){
  11446. // something went wrong
  11447. });
  11448. ```
  11449. @method catch
  11450. @param {Function} onRejection
  11451. Useful for tooling.
  11452. @return {Promise}
  11453. */
  11454. 'catch': function(onRejection) {
  11455. return this.then(null, onRejection);
  11456. }
  11457. };
  11458. function lib$es6$promise$polyfill$$polyfill() {
  11459. var local;
  11460. if (typeof global !== 'undefined') {
  11461. local = global;
  11462. } else if (typeof self !== 'undefined') {
  11463. local = self;
  11464. } else {
  11465. try {
  11466. local = Function('return this')();
  11467. } catch (e) {
  11468. throw new Error('polyfill failed because global object is unavailable in this environment');
  11469. }
  11470. }
  11471. var P = local.Promise;
  11472. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  11473. return;
  11474. }
  11475. local.Promise = lib$es6$promise$promise$$default;
  11476. }
  11477. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  11478. var lib$es6$promise$umd$$ES6Promise = {
  11479. 'Promise': lib$es6$promise$promise$$default,
  11480. 'polyfill': lib$es6$promise$polyfill$$default
  11481. };
  11482. /* global define:true module:true window: true */
  11483. if (typeof define === 'function' && define['amd']) {
  11484. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  11485. } else if (typeof module !== 'undefined' && module['exports']) {
  11486. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  11487. } else if (typeof this !== 'undefined') {
  11488. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  11489. }
  11490. lib$es6$promise$polyfill$$default();
  11491. }).call(this);
  11492. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  11493. },{"_process":40}],42:[function(require,module,exports){
  11494. // Top level file is just a mixin of submodules & constants
  11495. 'use strict';
  11496. var assign = require('./lib/utils/common').assign;
  11497. var deflate = require('./lib/deflate');
  11498. var inflate = require('./lib/inflate');
  11499. var constants = require('./lib/zlib/constants');
  11500. var pako = {};
  11501. assign(pako, deflate, inflate, constants);
  11502. module.exports = pako;
  11503. },{"./lib/deflate":43,"./lib/inflate":44,"./lib/utils/common":45,"./lib/zlib/constants":48}],43:[function(require,module,exports){
  11504. 'use strict';
  11505. var zlib_deflate = require('./zlib/deflate.js');
  11506. var utils = require('./utils/common');
  11507. var strings = require('./utils/strings');
  11508. var msg = require('./zlib/messages');
  11509. var zstream = require('./zlib/zstream');
  11510. var toString = Object.prototype.toString;
  11511. /* Public constants ==========================================================*/
  11512. /* ===========================================================================*/
  11513. var Z_NO_FLUSH = 0;
  11514. var Z_FINISH = 4;
  11515. var Z_OK = 0;
  11516. var Z_STREAM_END = 1;
  11517. var Z_SYNC_FLUSH = 2;
  11518. var Z_DEFAULT_COMPRESSION = -1;
  11519. var Z_DEFAULT_STRATEGY = 0;
  11520. var Z_DEFLATED = 8;
  11521. /* ===========================================================================*/
  11522. /**
  11523. * class Deflate
  11524. *
  11525. * Generic JS-style wrapper for zlib calls. If you don't need
  11526. * streaming behaviour - use more simple functions: [[deflate]],
  11527. * [[deflateRaw]] and [[gzip]].
  11528. **/
  11529. /* internal
  11530. * Deflate.chunks -> Array
  11531. *
  11532. * Chunks of output data, if [[Deflate#onData]] not overriden.
  11533. **/
  11534. /**
  11535. * Deflate.result -> Uint8Array|Array
  11536. *
  11537. * Compressed result, generated by default [[Deflate#onData]]
  11538. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  11539. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  11540. * push a chunk with explicit flush (call [[Deflate#push]] with
  11541. * `Z_SYNC_FLUSH` param).
  11542. **/
  11543. /**
  11544. * Deflate.err -> Number
  11545. *
  11546. * Error code after deflate finished. 0 (Z_OK) on success.
  11547. * You will not need it in real life, because deflate errors
  11548. * are possible only on wrong options or bad `onData` / `onEnd`
  11549. * custom handlers.
  11550. **/
  11551. /**
  11552. * Deflate.msg -> String
  11553. *
  11554. * Error message, if [[Deflate.err]] != 0
  11555. **/
  11556. /**
  11557. * new Deflate(options)
  11558. * - options (Object): zlib deflate options.
  11559. *
  11560. * Creates new deflator instance with specified params. Throws exception
  11561. * on bad params. Supported options:
  11562. *
  11563. * - `level`
  11564. * - `windowBits`
  11565. * - `memLevel`
  11566. * - `strategy`
  11567. *
  11568. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  11569. * for more information on these.
  11570. *
  11571. * Additional options, for internal needs:
  11572. *
  11573. * - `chunkSize` - size of generated data chunks (16K by default)
  11574. * - `raw` (Boolean) - do raw deflate
  11575. * - `gzip` (Boolean) - create gzip wrapper
  11576. * - `to` (String) - if equal to 'string', then result will be "binary string"
  11577. * (each char code [0..255])
  11578. * - `header` (Object) - custom header for gzip
  11579. * - `text` (Boolean) - true if compressed data believed to be text
  11580. * - `time` (Number) - modification time, unix timestamp
  11581. * - `os` (Number) - operation system code
  11582. * - `extra` (Array) - array of bytes with extra data (max 65536)
  11583. * - `name` (String) - file name (binary string)
  11584. * - `comment` (String) - comment (binary string)
  11585. * - `hcrc` (Boolean) - true if header crc should be added
  11586. *
  11587. * ##### Example:
  11588. *
  11589. * ```javascript
  11590. * var pako = require('pako')
  11591. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  11592. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  11593. *
  11594. * var deflate = new pako.Deflate({ level: 3});
  11595. *
  11596. * deflate.push(chunk1, false);
  11597. * deflate.push(chunk2, true); // true -> last chunk
  11598. *
  11599. * if (deflate.err) { throw new Error(deflate.err); }
  11600. *
  11601. * console.log(deflate.result);
  11602. * ```
  11603. **/
  11604. var Deflate = function(options) {
  11605. this.options = utils.assign({
  11606. level: Z_DEFAULT_COMPRESSION,
  11607. method: Z_DEFLATED,
  11608. chunkSize: 16384,
  11609. windowBits: 15,
  11610. memLevel: 8,
  11611. strategy: Z_DEFAULT_STRATEGY,
  11612. to: ''
  11613. }, options || {});
  11614. var opt = this.options;
  11615. if (opt.raw && (opt.windowBits > 0)) {
  11616. opt.windowBits = -opt.windowBits;
  11617. }
  11618. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  11619. opt.windowBits += 16;
  11620. }
  11621. this.err = 0; // error code, if happens (0 = Z_OK)
  11622. this.msg = ''; // error message
  11623. this.ended = false; // used to avoid multiple onEnd() calls
  11624. this.chunks = []; // chunks of compressed data
  11625. this.strm = new zstream();
  11626. this.strm.avail_out = 0;
  11627. var status = zlib_deflate.deflateInit2(
  11628. this.strm,
  11629. opt.level,
  11630. opt.method,
  11631. opt.windowBits,
  11632. opt.memLevel,
  11633. opt.strategy
  11634. );
  11635. if (status !== Z_OK) {
  11636. throw new Error(msg[status]);
  11637. }
  11638. if (opt.header) {
  11639. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  11640. }
  11641. };
  11642. /**
  11643. * Deflate#push(data[, mode]) -> Boolean
  11644. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  11645. * converted to utf8 byte sequence.
  11646. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  11647. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  11648. *
  11649. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  11650. * new compressed chunks. Returns `true` on success. The last data block must have
  11651. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  11652. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  11653. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  11654. *
  11655. * On fail call [[Deflate#onEnd]] with error code and return false.
  11656. *
  11657. * We strongly recommend to use `Uint8Array` on input for best speed (output
  11658. * array format is detected automatically). Also, don't skip last param and always
  11659. * use the same type in your code (boolean or number). That will improve JS speed.
  11660. *
  11661. * For regular `Array`-s make sure all elements are [0..255].
  11662. *
  11663. * ##### Example
  11664. *
  11665. * ```javascript
  11666. * push(chunk, false); // push one of data chunks
  11667. * ...
  11668. * push(chunk, true); // push last chunk
  11669. * ```
  11670. **/
  11671. Deflate.prototype.push = function(data, mode) {
  11672. var strm = this.strm;
  11673. var chunkSize = this.options.chunkSize;
  11674. var status, _mode;
  11675. if (this.ended) { return false; }
  11676. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  11677. // Convert data if needed
  11678. if (typeof data === 'string') {
  11679. // If we need to compress text, change encoding to utf8.
  11680. strm.input = strings.string2buf(data);
  11681. } else if (toString.call(data) === '[object ArrayBuffer]') {
  11682. strm.input = new Uint8Array(data);
  11683. } else {
  11684. strm.input = data;
  11685. }
  11686. strm.next_in = 0;
  11687. strm.avail_in = strm.input.length;
  11688. do {
  11689. if (strm.avail_out === 0) {
  11690. strm.output = new utils.Buf8(chunkSize);
  11691. strm.next_out = 0;
  11692. strm.avail_out = chunkSize;
  11693. }
  11694. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  11695. if (status !== Z_STREAM_END && status !== Z_OK) {
  11696. this.onEnd(status);
  11697. this.ended = true;
  11698. return false;
  11699. }
  11700. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  11701. if (this.options.to === 'string') {
  11702. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  11703. } else {
  11704. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  11705. }
  11706. }
  11707. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  11708. // Finalize on the last chunk.
  11709. if (_mode === Z_FINISH) {
  11710. status = zlib_deflate.deflateEnd(this.strm);
  11711. this.onEnd(status);
  11712. this.ended = true;
  11713. return status === Z_OK;
  11714. }
  11715. // callback interim results if Z_SYNC_FLUSH.
  11716. if (_mode === Z_SYNC_FLUSH) {
  11717. this.onEnd(Z_OK);
  11718. strm.avail_out = 0;
  11719. return true;
  11720. }
  11721. return true;
  11722. };
  11723. /**
  11724. * Deflate#onData(chunk) -> Void
  11725. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  11726. * on js engine support. When string output requested, each chunk
  11727. * will be string.
  11728. *
  11729. * By default, stores data blocks in `chunks[]` property and glue
  11730. * those in `onEnd`. Override this handler, if you need another behaviour.
  11731. **/
  11732. Deflate.prototype.onData = function(chunk) {
  11733. this.chunks.push(chunk);
  11734. };
  11735. /**
  11736. * Deflate#onEnd(status) -> Void
  11737. * - status (Number): deflate status. 0 (Z_OK) on success,
  11738. * other if not.
  11739. *
  11740. * Called once after you tell deflate that the input stream is
  11741. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  11742. * or if an error happened. By default - join collected chunks,
  11743. * free memory and fill `results` / `err` properties.
  11744. **/
  11745. Deflate.prototype.onEnd = function(status) {
  11746. // On success - join
  11747. if (status === Z_OK) {
  11748. if (this.options.to === 'string') {
  11749. this.result = this.chunks.join('');
  11750. } else {
  11751. this.result = utils.flattenChunks(this.chunks);
  11752. }
  11753. }
  11754. this.chunks = [];
  11755. this.err = status;
  11756. this.msg = this.strm.msg;
  11757. };
  11758. /**
  11759. * deflate(data[, options]) -> Uint8Array|Array|String
  11760. * - data (Uint8Array|Array|String): input data to compress.
  11761. * - options (Object): zlib deflate options.
  11762. *
  11763. * Compress `data` with deflate alrorythm and `options`.
  11764. *
  11765. * Supported options are:
  11766. *
  11767. * - level
  11768. * - windowBits
  11769. * - memLevel
  11770. * - strategy
  11771. *
  11772. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  11773. * for more information on these.
  11774. *
  11775. * Sugar (options):
  11776. *
  11777. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  11778. * negative windowBits implicitly.
  11779. * - `to` (String) - if equal to 'string', then result will be "binary string"
  11780. * (each char code [0..255])
  11781. *
  11782. * ##### Example:
  11783. *
  11784. * ```javascript
  11785. * var pako = require('pako')
  11786. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  11787. *
  11788. * console.log(pako.deflate(data));
  11789. * ```
  11790. **/
  11791. function deflate(input, options) {
  11792. var deflator = new Deflate(options);
  11793. deflator.push(input, true);
  11794. // That will never happens, if you don't cheat with options :)
  11795. if (deflator.err) { throw deflator.msg; }
  11796. return deflator.result;
  11797. }
  11798. /**
  11799. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  11800. * - data (Uint8Array|Array|String): input data to compress.
  11801. * - options (Object): zlib deflate options.
  11802. *
  11803. * The same as [[deflate]], but creates raw data, without wrapper
  11804. * (header and adler32 crc).
  11805. **/
  11806. function deflateRaw(input, options) {
  11807. options = options || {};
  11808. options.raw = true;
  11809. return deflate(input, options);
  11810. }
  11811. /**
  11812. * gzip(data[, options]) -> Uint8Array|Array|String
  11813. * - data (Uint8Array|Array|String): input data to compress.
  11814. * - options (Object): zlib deflate options.
  11815. *
  11816. * The same as [[deflate]], but create gzip wrapper instead of
  11817. * deflate one.
  11818. **/
  11819. function gzip(input, options) {
  11820. options = options || {};
  11821. options.gzip = true;
  11822. return deflate(input, options);
  11823. }
  11824. exports.Deflate = Deflate;
  11825. exports.deflate = deflate;
  11826. exports.deflateRaw = deflateRaw;
  11827. exports.gzip = gzip;
  11828. },{"./utils/common":45,"./utils/strings":46,"./zlib/deflate.js":50,"./zlib/messages":55,"./zlib/zstream":57}],44:[function(require,module,exports){
  11829. 'use strict';
  11830. var zlib_inflate = require('./zlib/inflate.js');
  11831. var utils = require('./utils/common');
  11832. var strings = require('./utils/strings');
  11833. var c = require('./zlib/constants');
  11834. var msg = require('./zlib/messages');
  11835. var zstream = require('./zlib/zstream');
  11836. var gzheader = require('./zlib/gzheader');
  11837. var toString = Object.prototype.toString;
  11838. /**
  11839. * class Inflate
  11840. *
  11841. * Generic JS-style wrapper for zlib calls. If you don't need
  11842. * streaming behaviour - use more simple functions: [[inflate]]
  11843. * and [[inflateRaw]].
  11844. **/
  11845. /* internal
  11846. * inflate.chunks -> Array
  11847. *
  11848. * Chunks of output data, if [[Inflate#onData]] not overriden.
  11849. **/
  11850. /**
  11851. * Inflate.result -> Uint8Array|Array|String
  11852. *
  11853. * Uncompressed result, generated by default [[Inflate#onData]]
  11854. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  11855. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  11856. * push a chunk with explicit flush (call [[Inflate#push]] with
  11857. * `Z_SYNC_FLUSH` param).
  11858. **/
  11859. /**
  11860. * Inflate.err -> Number
  11861. *
  11862. * Error code after inflate finished. 0 (Z_OK) on success.
  11863. * Should be checked if broken data possible.
  11864. **/
  11865. /**
  11866. * Inflate.msg -> String
  11867. *
  11868. * Error message, if [[Inflate.err]] != 0
  11869. **/
  11870. /**
  11871. * new Inflate(options)
  11872. * - options (Object): zlib inflate options.
  11873. *
  11874. * Creates new inflator instance with specified params. Throws exception
  11875. * on bad params. Supported options:
  11876. *
  11877. * - `windowBits`
  11878. *
  11879. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  11880. * for more information on these.
  11881. *
  11882. * Additional options, for internal needs:
  11883. *
  11884. * - `chunkSize` - size of generated data chunks (16K by default)
  11885. * - `raw` (Boolean) - do raw inflate
  11886. * - `to` (String) - if equal to 'string', then result will be converted
  11887. * from utf8 to utf16 (javascript) string. When string output requested,
  11888. * chunk length can differ from `chunkSize`, depending on content.
  11889. *
  11890. * By default, when no options set, autodetect deflate/gzip data format via
  11891. * wrapper header.
  11892. *
  11893. * ##### Example:
  11894. *
  11895. * ```javascript
  11896. * var pako = require('pako')
  11897. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  11898. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  11899. *
  11900. * var inflate = new pako.Inflate({ level: 3});
  11901. *
  11902. * inflate.push(chunk1, false);
  11903. * inflate.push(chunk2, true); // true -> last chunk
  11904. *
  11905. * if (inflate.err) { throw new Error(inflate.err); }
  11906. *
  11907. * console.log(inflate.result);
  11908. * ```
  11909. **/
  11910. var Inflate = function(options) {
  11911. this.options = utils.assign({
  11912. chunkSize: 16384,
  11913. windowBits: 0,
  11914. to: ''
  11915. }, options || {});
  11916. var opt = this.options;
  11917. // Force window size for `raw` data, if not set directly,
  11918. // because we have no header for autodetect.
  11919. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  11920. opt.windowBits = -opt.windowBits;
  11921. if (opt.windowBits === 0) { opt.windowBits = -15; }
  11922. }
  11923. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  11924. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  11925. !(options && options.windowBits)) {
  11926. opt.windowBits += 32;
  11927. }
  11928. // Gzip header has no info about windows size, we can do autodetect only
  11929. // for deflate. So, if window size not set, force it to max when gzip possible
  11930. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  11931. // bit 3 (16) -> gzipped data
  11932. // bit 4 (32) -> autodetect gzip/deflate
  11933. if ((opt.windowBits & 15) === 0) {
  11934. opt.windowBits |= 15;
  11935. }
  11936. }
  11937. this.err = 0; // error code, if happens (0 = Z_OK)
  11938. this.msg = ''; // error message
  11939. this.ended = false; // used to avoid multiple onEnd() calls
  11940. this.chunks = []; // chunks of compressed data
  11941. this.strm = new zstream();
  11942. this.strm.avail_out = 0;
  11943. var status = zlib_inflate.inflateInit2(
  11944. this.strm,
  11945. opt.windowBits
  11946. );
  11947. if (status !== c.Z_OK) {
  11948. throw new Error(msg[status]);
  11949. }
  11950. this.header = new gzheader();
  11951. zlib_inflate.inflateGetHeader(this.strm, this.header);
  11952. };
  11953. /**
  11954. * Inflate#push(data[, mode]) -> Boolean
  11955. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  11956. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  11957. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  11958. *
  11959. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  11960. * new output chunks. Returns `true` on success. The last data block must have
  11961. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  11962. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  11963. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  11964. *
  11965. * On fail call [[Inflate#onEnd]] with error code and return false.
  11966. *
  11967. * We strongly recommend to use `Uint8Array` on input for best speed (output
  11968. * format is detected automatically). Also, don't skip last param and always
  11969. * use the same type in your code (boolean or number). That will improve JS speed.
  11970. *
  11971. * For regular `Array`-s make sure all elements are [0..255].
  11972. *
  11973. * ##### Example
  11974. *
  11975. * ```javascript
  11976. * push(chunk, false); // push one of data chunks
  11977. * ...
  11978. * push(chunk, true); // push last chunk
  11979. * ```
  11980. **/
  11981. Inflate.prototype.push = function(data, mode) {
  11982. var strm = this.strm;
  11983. var chunkSize = this.options.chunkSize;
  11984. var status, _mode;
  11985. var next_out_utf8, tail, utf8str;
  11986. // Flag to properly process Z_BUF_ERROR on testing inflate call
  11987. // when we check that all output data was flushed.
  11988. var allowBufError = false;
  11989. if (this.ended) { return false; }
  11990. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  11991. // Convert data if needed
  11992. if (typeof data === 'string') {
  11993. // Only binary strings can be decompressed on practice
  11994. strm.input = strings.binstring2buf(data);
  11995. } else if (toString.call(data) === '[object ArrayBuffer]') {
  11996. strm.input = new Uint8Array(data);
  11997. } else {
  11998. strm.input = data;
  11999. }
  12000. strm.next_in = 0;
  12001. strm.avail_in = strm.input.length;
  12002. do {
  12003. if (strm.avail_out === 0) {
  12004. strm.output = new utils.Buf8(chunkSize);
  12005. strm.next_out = 0;
  12006. strm.avail_out = chunkSize;
  12007. }
  12008. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  12009. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  12010. status = c.Z_OK;
  12011. allowBufError = false;
  12012. }
  12013. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  12014. this.onEnd(status);
  12015. this.ended = true;
  12016. return false;
  12017. }
  12018. if (strm.next_out) {
  12019. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  12020. if (this.options.to === 'string') {
  12021. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  12022. tail = strm.next_out - next_out_utf8;
  12023. utf8str = strings.buf2string(strm.output, next_out_utf8);
  12024. // move tail
  12025. strm.next_out = tail;
  12026. strm.avail_out = chunkSize - tail;
  12027. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  12028. this.onData(utf8str);
  12029. } else {
  12030. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  12031. }
  12032. }
  12033. }
  12034. // When no more input data, we should check that internal inflate buffers
  12035. // are flushed. The only way to do it when avail_out = 0 - run one more
  12036. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  12037. // Here we set flag to process this error properly.
  12038. //
  12039. // NOTE. Deflate does not return error in this case and does not needs such
  12040. // logic.
  12041. if (strm.avail_in === 0 && strm.avail_out === 0) {
  12042. allowBufError = true;
  12043. }
  12044. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  12045. if (status === c.Z_STREAM_END) {
  12046. _mode = c.Z_FINISH;
  12047. }
  12048. // Finalize on the last chunk.
  12049. if (_mode === c.Z_FINISH) {
  12050. status = zlib_inflate.inflateEnd(this.strm);
  12051. this.onEnd(status);
  12052. this.ended = true;
  12053. return status === c.Z_OK;
  12054. }
  12055. // callback interim results if Z_SYNC_FLUSH.
  12056. if (_mode === c.Z_SYNC_FLUSH) {
  12057. this.onEnd(c.Z_OK);
  12058. strm.avail_out = 0;
  12059. return true;
  12060. }
  12061. return true;
  12062. };
  12063. /**
  12064. * Inflate#onData(chunk) -> Void
  12065. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  12066. * on js engine support. When string output requested, each chunk
  12067. * will be string.
  12068. *
  12069. * By default, stores data blocks in `chunks[]` property and glue
  12070. * those in `onEnd`. Override this handler, if you need another behaviour.
  12071. **/
  12072. Inflate.prototype.onData = function(chunk) {
  12073. this.chunks.push(chunk);
  12074. };
  12075. /**
  12076. * Inflate#onEnd(status) -> Void
  12077. * - status (Number): inflate status. 0 (Z_OK) on success,
  12078. * other if not.
  12079. *
  12080. * Called either after you tell inflate that the input stream is
  12081. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  12082. * or if an error happened. By default - join collected chunks,
  12083. * free memory and fill `results` / `err` properties.
  12084. **/
  12085. Inflate.prototype.onEnd = function(status) {
  12086. // On success - join
  12087. if (status === c.Z_OK) {
  12088. if (this.options.to === 'string') {
  12089. // Glue & convert here, until we teach pako to send
  12090. // utf8 alligned strings to onData
  12091. this.result = this.chunks.join('');
  12092. } else {
  12093. this.result = utils.flattenChunks(this.chunks);
  12094. }
  12095. }
  12096. this.chunks = [];
  12097. this.err = status;
  12098. this.msg = this.strm.msg;
  12099. };
  12100. /**
  12101. * inflate(data[, options]) -> Uint8Array|Array|String
  12102. * - data (Uint8Array|Array|String): input data to decompress.
  12103. * - options (Object): zlib inflate options.
  12104. *
  12105. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  12106. * format via wrapper header by default. That's why we don't provide
  12107. * separate `ungzip` method.
  12108. *
  12109. * Supported options are:
  12110. *
  12111. * - windowBits
  12112. *
  12113. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  12114. * for more information.
  12115. *
  12116. * Sugar (options):
  12117. *
  12118. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  12119. * negative windowBits implicitly.
  12120. * - `to` (String) - if equal to 'string', then result will be converted
  12121. * from utf8 to utf16 (javascript) string. When string output requested,
  12122. * chunk length can differ from `chunkSize`, depending on content.
  12123. *
  12124. *
  12125. * ##### Example:
  12126. *
  12127. * ```javascript
  12128. * var pako = require('pako')
  12129. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  12130. * , output;
  12131. *
  12132. * try {
  12133. * output = pako.inflate(input);
  12134. * } catch (err)
  12135. * console.log(err);
  12136. * }
  12137. * ```
  12138. **/
  12139. function inflate(input, options) {
  12140. var inflator = new Inflate(options);
  12141. inflator.push(input, true);
  12142. // That will never happens, if you don't cheat with options :)
  12143. if (inflator.err) { throw inflator.msg; }
  12144. return inflator.result;
  12145. }
  12146. /**
  12147. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  12148. * - data (Uint8Array|Array|String): input data to decompress.
  12149. * - options (Object): zlib inflate options.
  12150. *
  12151. * The same as [[inflate]], but creates raw data, without wrapper
  12152. * (header and adler32 crc).
  12153. **/
  12154. function inflateRaw(input, options) {
  12155. options = options || {};
  12156. options.raw = true;
  12157. return inflate(input, options);
  12158. }
  12159. /**
  12160. * ungzip(data[, options]) -> Uint8Array|Array|String
  12161. * - data (Uint8Array|Array|String): input data to decompress.
  12162. * - options (Object): zlib inflate options.
  12163. *
  12164. * Just shortcut to [[inflate]], because it autodetects format
  12165. * by header.content. Done for convenience.
  12166. **/
  12167. exports.Inflate = Inflate;
  12168. exports.inflate = inflate;
  12169. exports.inflateRaw = inflateRaw;
  12170. exports.ungzip = inflate;
  12171. },{"./utils/common":45,"./utils/strings":46,"./zlib/constants":48,"./zlib/gzheader":51,"./zlib/inflate.js":53,"./zlib/messages":55,"./zlib/zstream":57}],45:[function(require,module,exports){
  12172. 'use strict';
  12173. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  12174. (typeof Uint16Array !== 'undefined') &&
  12175. (typeof Int32Array !== 'undefined');
  12176. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  12177. var sources = Array.prototype.slice.call(arguments, 1);
  12178. while (sources.length) {
  12179. var source = sources.shift();
  12180. if (!source) { continue; }
  12181. if (typeof source !== 'object') {
  12182. throw new TypeError(source + 'must be non-object');
  12183. }
  12184. for (var p in source) {
  12185. if (source.hasOwnProperty(p)) {
  12186. obj[p] = source[p];
  12187. }
  12188. }
  12189. }
  12190. return obj;
  12191. };
  12192. // reduce buffer size, avoiding mem copy
  12193. exports.shrinkBuf = function (buf, size) {
  12194. if (buf.length === size) { return buf; }
  12195. if (buf.subarray) { return buf.subarray(0, size); }
  12196. buf.length = size;
  12197. return buf;
  12198. };
  12199. var fnTyped = {
  12200. arraySet: function (dest, src, src_offs, len, dest_offs) {
  12201. if (src.subarray && dest.subarray) {
  12202. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  12203. return;
  12204. }
  12205. // Fallback to ordinary array
  12206. for (var i=0; i<len; i++) {
  12207. dest[dest_offs + i] = src[src_offs + i];
  12208. }
  12209. },
  12210. // Join array of chunks to single array.
  12211. flattenChunks: function(chunks) {
  12212. var i, l, len, pos, chunk, result;
  12213. // calculate data length
  12214. len = 0;
  12215. for (i=0, l=chunks.length; i<l; i++) {
  12216. len += chunks[i].length;
  12217. }
  12218. // join chunks
  12219. result = new Uint8Array(len);
  12220. pos = 0;
  12221. for (i=0, l=chunks.length; i<l; i++) {
  12222. chunk = chunks[i];
  12223. result.set(chunk, pos);
  12224. pos += chunk.length;
  12225. }
  12226. return result;
  12227. }
  12228. };
  12229. var fnUntyped = {
  12230. arraySet: function (dest, src, src_offs, len, dest_offs) {
  12231. for (var i=0; i<len; i++) {
  12232. dest[dest_offs + i] = src[src_offs + i];
  12233. }
  12234. },
  12235. // Join array of chunks to single array.
  12236. flattenChunks: function(chunks) {
  12237. return [].concat.apply([], chunks);
  12238. }
  12239. };
  12240. // Enable/Disable typed arrays use, for testing
  12241. //
  12242. exports.setTyped = function (on) {
  12243. if (on) {
  12244. exports.Buf8 = Uint8Array;
  12245. exports.Buf16 = Uint16Array;
  12246. exports.Buf32 = Int32Array;
  12247. exports.assign(exports, fnTyped);
  12248. } else {
  12249. exports.Buf8 = Array;
  12250. exports.Buf16 = Array;
  12251. exports.Buf32 = Array;
  12252. exports.assign(exports, fnUntyped);
  12253. }
  12254. };
  12255. exports.setTyped(TYPED_OK);
  12256. },{}],46:[function(require,module,exports){
  12257. // String encode/decode helpers
  12258. 'use strict';
  12259. var utils = require('./common');
  12260. // Quick check if we can use fast array to bin string conversion
  12261. //
  12262. // - apply(Array) can fail on Android 2.2
  12263. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  12264. //
  12265. var STR_APPLY_OK = true;
  12266. var STR_APPLY_UIA_OK = true;
  12267. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  12268. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  12269. // Table with utf8 lengths (calculated by first byte of sequence)
  12270. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  12271. // because max possible codepoint is 0x10ffff
  12272. var _utf8len = new utils.Buf8(256);
  12273. for (var q=0; q<256; q++) {
  12274. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  12275. }
  12276. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  12277. // convert string to array (typed, when possible)
  12278. exports.string2buf = function (str) {
  12279. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  12280. // count binary size
  12281. for (m_pos = 0; m_pos < str_len; m_pos++) {
  12282. c = str.charCodeAt(m_pos);
  12283. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  12284. c2 = str.charCodeAt(m_pos+1);
  12285. if ((c2 & 0xfc00) === 0xdc00) {
  12286. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  12287. m_pos++;
  12288. }
  12289. }
  12290. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  12291. }
  12292. // allocate buffer
  12293. buf = new utils.Buf8(buf_len);
  12294. // convert
  12295. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  12296. c = str.charCodeAt(m_pos);
  12297. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  12298. c2 = str.charCodeAt(m_pos+1);
  12299. if ((c2 & 0xfc00) === 0xdc00) {
  12300. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  12301. m_pos++;
  12302. }
  12303. }
  12304. if (c < 0x80) {
  12305. /* one byte */
  12306. buf[i++] = c;
  12307. } else if (c < 0x800) {
  12308. /* two bytes */
  12309. buf[i++] = 0xC0 | (c >>> 6);
  12310. buf[i++] = 0x80 | (c & 0x3f);
  12311. } else if (c < 0x10000) {
  12312. /* three bytes */
  12313. buf[i++] = 0xE0 | (c >>> 12);
  12314. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  12315. buf[i++] = 0x80 | (c & 0x3f);
  12316. } else {
  12317. /* four bytes */
  12318. buf[i++] = 0xf0 | (c >>> 18);
  12319. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  12320. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  12321. buf[i++] = 0x80 | (c & 0x3f);
  12322. }
  12323. }
  12324. return buf;
  12325. };
  12326. // Helper (used in 2 places)
  12327. function buf2binstring(buf, len) {
  12328. // use fallback for big arrays to avoid stack overflow
  12329. if (len < 65537) {
  12330. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  12331. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  12332. }
  12333. }
  12334. var result = '';
  12335. for (var i=0; i < len; i++) {
  12336. result += String.fromCharCode(buf[i]);
  12337. }
  12338. return result;
  12339. }
  12340. // Convert byte array to binary string
  12341. exports.buf2binstring = function(buf) {
  12342. return buf2binstring(buf, buf.length);
  12343. };
  12344. // Convert binary string (typed, when possible)
  12345. exports.binstring2buf = function(str) {
  12346. var buf = new utils.Buf8(str.length);
  12347. for (var i=0, len=buf.length; i < len; i++) {
  12348. buf[i] = str.charCodeAt(i);
  12349. }
  12350. return buf;
  12351. };
  12352. // convert array to string
  12353. exports.buf2string = function (buf, max) {
  12354. var i, out, c, c_len;
  12355. var len = max || buf.length;
  12356. // Reserve max possible length (2 words per char)
  12357. // NB: by unknown reasons, Array is significantly faster for
  12358. // String.fromCharCode.apply than Uint16Array.
  12359. var utf16buf = new Array(len*2);
  12360. for (out=0, i=0; i<len;) {
  12361. c = buf[i++];
  12362. // quick process ascii
  12363. if (c < 0x80) { utf16buf[out++] = c; continue; }
  12364. c_len = _utf8len[c];
  12365. // skip 5 & 6 byte codes
  12366. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  12367. // apply mask on first byte
  12368. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  12369. // join the rest
  12370. while (c_len > 1 && i < len) {
  12371. c = (c << 6) | (buf[i++] & 0x3f);
  12372. c_len--;
  12373. }
  12374. // terminated by end of string?
  12375. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  12376. if (c < 0x10000) {
  12377. utf16buf[out++] = c;
  12378. } else {
  12379. c -= 0x10000;
  12380. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  12381. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  12382. }
  12383. }
  12384. return buf2binstring(utf16buf, out);
  12385. };
  12386. // Calculate max possible position in utf8 buffer,
  12387. // that will not break sequence. If that's not possible
  12388. // - (very small limits) return max size as is.
  12389. //
  12390. // buf[] - utf8 bytes array
  12391. // max - length limit (mandatory);
  12392. exports.utf8border = function(buf, max) {
  12393. var pos;
  12394. max = max || buf.length;
  12395. if (max > buf.length) { max = buf.length; }
  12396. // go back from last position, until start of sequence found
  12397. pos = max-1;
  12398. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  12399. // Fuckup - very small and broken sequence,
  12400. // return max, because we should return something anyway.
  12401. if (pos < 0) { return max; }
  12402. // If we came to start of buffer - that means vuffer is too small,
  12403. // return max too.
  12404. if (pos === 0) { return max; }
  12405. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  12406. };
  12407. },{"./common":45}],47:[function(require,module,exports){
  12408. 'use strict';
  12409. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  12410. // It doesn't worth to make additional optimizationa as in original.
  12411. // Small size is preferable.
  12412. function adler32(adler, buf, len, pos) {
  12413. var s1 = (adler & 0xffff) |0,
  12414. s2 = ((adler >>> 16) & 0xffff) |0,
  12415. n = 0;
  12416. while (len !== 0) {
  12417. // Set limit ~ twice less than 5552, to keep
  12418. // s2 in 31-bits, because we force signed ints.
  12419. // in other case %= will fail.
  12420. n = len > 2000 ? 2000 : len;
  12421. len -= n;
  12422. do {
  12423. s1 = (s1 + buf[pos++]) |0;
  12424. s2 = (s2 + s1) |0;
  12425. } while (--n);
  12426. s1 %= 65521;
  12427. s2 %= 65521;
  12428. }
  12429. return (s1 | (s2 << 16)) |0;
  12430. }
  12431. module.exports = adler32;
  12432. },{}],48:[function(require,module,exports){
  12433. module.exports = {
  12434. /* Allowed flush values; see deflate() and inflate() below for details */
  12435. Z_NO_FLUSH: 0,
  12436. Z_PARTIAL_FLUSH: 1,
  12437. Z_SYNC_FLUSH: 2,
  12438. Z_FULL_FLUSH: 3,
  12439. Z_FINISH: 4,
  12440. Z_BLOCK: 5,
  12441. Z_TREES: 6,
  12442. /* Return codes for the compression/decompression functions. Negative values
  12443. * are errors, positive values are used for special but normal events.
  12444. */
  12445. Z_OK: 0,
  12446. Z_STREAM_END: 1,
  12447. Z_NEED_DICT: 2,
  12448. Z_ERRNO: -1,
  12449. Z_STREAM_ERROR: -2,
  12450. Z_DATA_ERROR: -3,
  12451. //Z_MEM_ERROR: -4,
  12452. Z_BUF_ERROR: -5,
  12453. //Z_VERSION_ERROR: -6,
  12454. /* compression levels */
  12455. Z_NO_COMPRESSION: 0,
  12456. Z_BEST_SPEED: 1,
  12457. Z_BEST_COMPRESSION: 9,
  12458. Z_DEFAULT_COMPRESSION: -1,
  12459. Z_FILTERED: 1,
  12460. Z_HUFFMAN_ONLY: 2,
  12461. Z_RLE: 3,
  12462. Z_FIXED: 4,
  12463. Z_DEFAULT_STRATEGY: 0,
  12464. /* Possible values of the data_type field (though see inflate()) */
  12465. Z_BINARY: 0,
  12466. Z_TEXT: 1,
  12467. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  12468. Z_UNKNOWN: 2,
  12469. /* The deflate compression method */
  12470. Z_DEFLATED: 8
  12471. //Z_NULL: null // Use -1 or null inline, depending on var type
  12472. };
  12473. },{}],49:[function(require,module,exports){
  12474. 'use strict';
  12475. // Note: we can't get significant speed boost here.
  12476. // So write code to minimize size - no pregenerated tables
  12477. // and array tools dependencies.
  12478. // Use ordinary array, since untyped makes no boost here
  12479. function makeTable() {
  12480. var c, table = [];
  12481. for (var n =0; n < 256; n++) {
  12482. c = n;
  12483. for (var k =0; k < 8; k++) {
  12484. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  12485. }
  12486. table[n] = c;
  12487. }
  12488. return table;
  12489. }
  12490. // Create table on load. Just 255 signed longs. Not a problem.
  12491. var crcTable = makeTable();
  12492. function crc32(crc, buf, len, pos) {
  12493. var t = crcTable,
  12494. end = pos + len;
  12495. crc = crc ^ (-1);
  12496. for (var i = pos; i < end; i++) {
  12497. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  12498. }
  12499. return (crc ^ (-1)); // >>> 0;
  12500. }
  12501. module.exports = crc32;
  12502. },{}],50:[function(require,module,exports){
  12503. 'use strict';
  12504. var utils = require('../utils/common');
  12505. var trees = require('./trees');
  12506. var adler32 = require('./adler32');
  12507. var crc32 = require('./crc32');
  12508. var msg = require('./messages');
  12509. /* Public constants ==========================================================*/
  12510. /* ===========================================================================*/
  12511. /* Allowed flush values; see deflate() and inflate() below for details */
  12512. var Z_NO_FLUSH = 0;
  12513. var Z_PARTIAL_FLUSH = 1;
  12514. //var Z_SYNC_FLUSH = 2;
  12515. var Z_FULL_FLUSH = 3;
  12516. var Z_FINISH = 4;
  12517. var Z_BLOCK = 5;
  12518. //var Z_TREES = 6;
  12519. /* Return codes for the compression/decompression functions. Negative values
  12520. * are errors, positive values are used for special but normal events.
  12521. */
  12522. var Z_OK = 0;
  12523. var Z_STREAM_END = 1;
  12524. //var Z_NEED_DICT = 2;
  12525. //var Z_ERRNO = -1;
  12526. var Z_STREAM_ERROR = -2;
  12527. var Z_DATA_ERROR = -3;
  12528. //var Z_MEM_ERROR = -4;
  12529. var Z_BUF_ERROR = -5;
  12530. //var Z_VERSION_ERROR = -6;
  12531. /* compression levels */
  12532. //var Z_NO_COMPRESSION = 0;
  12533. //var Z_BEST_SPEED = 1;
  12534. //var Z_BEST_COMPRESSION = 9;
  12535. var Z_DEFAULT_COMPRESSION = -1;
  12536. var Z_FILTERED = 1;
  12537. var Z_HUFFMAN_ONLY = 2;
  12538. var Z_RLE = 3;
  12539. var Z_FIXED = 4;
  12540. var Z_DEFAULT_STRATEGY = 0;
  12541. /* Possible values of the data_type field (though see inflate()) */
  12542. //var Z_BINARY = 0;
  12543. //var Z_TEXT = 1;
  12544. //var Z_ASCII = 1; // = Z_TEXT
  12545. var Z_UNKNOWN = 2;
  12546. /* The deflate compression method */
  12547. var Z_DEFLATED = 8;
  12548. /*============================================================================*/
  12549. var MAX_MEM_LEVEL = 9;
  12550. /* Maximum value for memLevel in deflateInit2 */
  12551. var MAX_WBITS = 15;
  12552. /* 32K LZ77 window */
  12553. var DEF_MEM_LEVEL = 8;
  12554. var LENGTH_CODES = 29;
  12555. /* number of length codes, not counting the special END_BLOCK code */
  12556. var LITERALS = 256;
  12557. /* number of literal bytes 0..255 */
  12558. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  12559. /* number of Literal or Length codes, including the END_BLOCK code */
  12560. var D_CODES = 30;
  12561. /* number of distance codes */
  12562. var BL_CODES = 19;
  12563. /* number of codes used to transfer the bit lengths */
  12564. var HEAP_SIZE = 2*L_CODES + 1;
  12565. /* maximum heap size */
  12566. var MAX_BITS = 15;
  12567. /* All codes must not exceed MAX_BITS bits */
  12568. var MIN_MATCH = 3;
  12569. var MAX_MATCH = 258;
  12570. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  12571. var PRESET_DICT = 0x20;
  12572. var INIT_STATE = 42;
  12573. var EXTRA_STATE = 69;
  12574. var NAME_STATE = 73;
  12575. var COMMENT_STATE = 91;
  12576. var HCRC_STATE = 103;
  12577. var BUSY_STATE = 113;
  12578. var FINISH_STATE = 666;
  12579. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  12580. var BS_BLOCK_DONE = 2; /* block flush performed */
  12581. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  12582. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  12583. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  12584. function err(strm, errorCode) {
  12585. strm.msg = msg[errorCode];
  12586. return errorCode;
  12587. }
  12588. function rank(f) {
  12589. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  12590. }
  12591. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  12592. /* =========================================================================
  12593. * Flush as much pending output as possible. All deflate() output goes
  12594. * through this function so some applications may wish to modify it
  12595. * to avoid allocating a large strm->output buffer and copying into it.
  12596. * (See also read_buf()).
  12597. */
  12598. function flush_pending(strm) {
  12599. var s = strm.state;
  12600. //_tr_flush_bits(s);
  12601. var len = s.pending;
  12602. if (len > strm.avail_out) {
  12603. len = strm.avail_out;
  12604. }
  12605. if (len === 0) { return; }
  12606. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  12607. strm.next_out += len;
  12608. s.pending_out += len;
  12609. strm.total_out += len;
  12610. strm.avail_out -= len;
  12611. s.pending -= len;
  12612. if (s.pending === 0) {
  12613. s.pending_out = 0;
  12614. }
  12615. }
  12616. function flush_block_only (s, last) {
  12617. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  12618. s.block_start = s.strstart;
  12619. flush_pending(s.strm);
  12620. }
  12621. function put_byte(s, b) {
  12622. s.pending_buf[s.pending++] = b;
  12623. }
  12624. /* =========================================================================
  12625. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  12626. * IN assertion: the stream state is correct and there is enough room in
  12627. * pending_buf.
  12628. */
  12629. function putShortMSB(s, b) {
  12630. // put_byte(s, (Byte)(b >> 8));
  12631. // put_byte(s, (Byte)(b & 0xff));
  12632. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  12633. s.pending_buf[s.pending++] = b & 0xff;
  12634. }
  12635. /* ===========================================================================
  12636. * Read a new buffer from the current input stream, update the adler32
  12637. * and total number of bytes read. All deflate() input goes through
  12638. * this function so some applications may wish to modify it to avoid
  12639. * allocating a large strm->input buffer and copying from it.
  12640. * (See also flush_pending()).
  12641. */
  12642. function read_buf(strm, buf, start, size) {
  12643. var len = strm.avail_in;
  12644. if (len > size) { len = size; }
  12645. if (len === 0) { return 0; }
  12646. strm.avail_in -= len;
  12647. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  12648. if (strm.state.wrap === 1) {
  12649. strm.adler = adler32(strm.adler, buf, len, start);
  12650. }
  12651. else if (strm.state.wrap === 2) {
  12652. strm.adler = crc32(strm.adler, buf, len, start);
  12653. }
  12654. strm.next_in += len;
  12655. strm.total_in += len;
  12656. return len;
  12657. }
  12658. /* ===========================================================================
  12659. * Set match_start to the longest match starting at the given string and
  12660. * return its length. Matches shorter or equal to prev_length are discarded,
  12661. * in which case the result is equal to prev_length and match_start is
  12662. * garbage.
  12663. * IN assertions: cur_match is the head of the hash chain for the current
  12664. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  12665. * OUT assertion: the match length is not greater than s->lookahead.
  12666. */
  12667. function longest_match(s, cur_match) {
  12668. var chain_length = s.max_chain_length; /* max hash chain length */
  12669. var scan = s.strstart; /* current string */
  12670. var match; /* matched string */
  12671. var len; /* length of current match */
  12672. var best_len = s.prev_length; /* best match length so far */
  12673. var nice_match = s.nice_match; /* stop if match long enough */
  12674. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  12675. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  12676. var _win = s.window; // shortcut
  12677. var wmask = s.w_mask;
  12678. var prev = s.prev;
  12679. /* Stop when cur_match becomes <= limit. To simplify the code,
  12680. * we prevent matches with the string of window index 0.
  12681. */
  12682. var strend = s.strstart + MAX_MATCH;
  12683. var scan_end1 = _win[scan + best_len - 1];
  12684. var scan_end = _win[scan + best_len];
  12685. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  12686. * It is easy to get rid of this optimization if necessary.
  12687. */
  12688. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  12689. /* Do not waste too much time if we already have a good match: */
  12690. if (s.prev_length >= s.good_match) {
  12691. chain_length >>= 2;
  12692. }
  12693. /* Do not look for matches beyond the end of the input. This is necessary
  12694. * to make deflate deterministic.
  12695. */
  12696. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  12697. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  12698. do {
  12699. // Assert(cur_match < s->strstart, "no future");
  12700. match = cur_match;
  12701. /* Skip to next match if the match length cannot increase
  12702. * or if the match length is less than 2. Note that the checks below
  12703. * for insufficient lookahead only occur occasionally for performance
  12704. * reasons. Therefore uninitialized memory will be accessed, and
  12705. * conditional jumps will be made that depend on those values.
  12706. * However the length of the match is limited to the lookahead, so
  12707. * the output of deflate is not affected by the uninitialized values.
  12708. */
  12709. if (_win[match + best_len] !== scan_end ||
  12710. _win[match + best_len - 1] !== scan_end1 ||
  12711. _win[match] !== _win[scan] ||
  12712. _win[++match] !== _win[scan + 1]) {
  12713. continue;
  12714. }
  12715. /* The check at best_len-1 can be removed because it will be made
  12716. * again later. (This heuristic is not always a win.)
  12717. * It is not necessary to compare scan[2] and match[2] since they
  12718. * are always equal when the other bytes match, given that
  12719. * the hash keys are equal and that HASH_BITS >= 8.
  12720. */
  12721. scan += 2;
  12722. match++;
  12723. // Assert(*scan == *match, "match[2]?");
  12724. /* We check for insufficient lookahead only every 8th comparison;
  12725. * the 256th check will be made at strstart+258.
  12726. */
  12727. do {
  12728. /*jshint noempty:false*/
  12729. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  12730. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  12731. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  12732. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  12733. scan < strend);
  12734. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  12735. len = MAX_MATCH - (strend - scan);
  12736. scan = strend - MAX_MATCH;
  12737. if (len > best_len) {
  12738. s.match_start = cur_match;
  12739. best_len = len;
  12740. if (len >= nice_match) {
  12741. break;
  12742. }
  12743. scan_end1 = _win[scan + best_len - 1];
  12744. scan_end = _win[scan + best_len];
  12745. }
  12746. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  12747. if (best_len <= s.lookahead) {
  12748. return best_len;
  12749. }
  12750. return s.lookahead;
  12751. }
  12752. /* ===========================================================================
  12753. * Fill the window when the lookahead becomes insufficient.
  12754. * Updates strstart and lookahead.
  12755. *
  12756. * IN assertion: lookahead < MIN_LOOKAHEAD
  12757. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  12758. * At least one byte has been read, or avail_in == 0; reads are
  12759. * performed for at least two bytes (required for the zip translate_eol
  12760. * option -- not supported here).
  12761. */
  12762. function fill_window(s) {
  12763. var _w_size = s.w_size;
  12764. var p, n, m, more, str;
  12765. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  12766. do {
  12767. more = s.window_size - s.lookahead - s.strstart;
  12768. // JS ints have 32 bit, block below not needed
  12769. /* Deal with !@#$% 64K limit: */
  12770. //if (sizeof(int) <= 2) {
  12771. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  12772. // more = wsize;
  12773. //
  12774. // } else if (more == (unsigned)(-1)) {
  12775. // /* Very unlikely, but possible on 16 bit machine if
  12776. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  12777. // */
  12778. // more--;
  12779. // }
  12780. //}
  12781. /* If the window is almost full and there is insufficient lookahead,
  12782. * move the upper half to the lower one to make room in the upper half.
  12783. */
  12784. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  12785. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  12786. s.match_start -= _w_size;
  12787. s.strstart -= _w_size;
  12788. /* we now have strstart >= MAX_DIST */
  12789. s.block_start -= _w_size;
  12790. /* Slide the hash table (could be avoided with 32 bit values
  12791. at the expense of memory usage). We slide even when level == 0
  12792. to keep the hash table consistent if we switch back to level > 0
  12793. later. (Using level 0 permanently is not an optimal usage of
  12794. zlib, so we don't care about this pathological case.)
  12795. */
  12796. n = s.hash_size;
  12797. p = n;
  12798. do {
  12799. m = s.head[--p];
  12800. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  12801. } while (--n);
  12802. n = _w_size;
  12803. p = n;
  12804. do {
  12805. m = s.prev[--p];
  12806. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  12807. /* If n is not on any hash chain, prev[n] is garbage but
  12808. * its value will never be used.
  12809. */
  12810. } while (--n);
  12811. more += _w_size;
  12812. }
  12813. if (s.strm.avail_in === 0) {
  12814. break;
  12815. }
  12816. /* If there was no sliding:
  12817. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  12818. * more == window_size - lookahead - strstart
  12819. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  12820. * => more >= window_size - 2*WSIZE + 2
  12821. * In the BIG_MEM or MMAP case (not yet supported),
  12822. * window_size == input_size + MIN_LOOKAHEAD &&
  12823. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  12824. * Otherwise, window_size == 2*WSIZE so more >= 2.
  12825. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  12826. */
  12827. //Assert(more >= 2, "more < 2");
  12828. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  12829. s.lookahead += n;
  12830. /* Initialize the hash value now that we have some input: */
  12831. if (s.lookahead + s.insert >= MIN_MATCH) {
  12832. str = s.strstart - s.insert;
  12833. s.ins_h = s.window[str];
  12834. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  12835. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  12836. //#if MIN_MATCH != 3
  12837. // Call update_hash() MIN_MATCH-3 more times
  12838. //#endif
  12839. while (s.insert) {
  12840. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  12841. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  12842. s.prev[str & s.w_mask] = s.head[s.ins_h];
  12843. s.head[s.ins_h] = str;
  12844. str++;
  12845. s.insert--;
  12846. if (s.lookahead + s.insert < MIN_MATCH) {
  12847. break;
  12848. }
  12849. }
  12850. }
  12851. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  12852. * but this is not important since only literal bytes will be emitted.
  12853. */
  12854. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  12855. /* If the WIN_INIT bytes after the end of the current data have never been
  12856. * written, then zero those bytes in order to avoid memory check reports of
  12857. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  12858. * the longest match routines. Update the high water mark for the next
  12859. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  12860. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  12861. */
  12862. // if (s.high_water < s.window_size) {
  12863. // var curr = s.strstart + s.lookahead;
  12864. // var init = 0;
  12865. //
  12866. // if (s.high_water < curr) {
  12867. // /* Previous high water mark below current data -- zero WIN_INIT
  12868. // * bytes or up to end of window, whichever is less.
  12869. // */
  12870. // init = s.window_size - curr;
  12871. // if (init > WIN_INIT)
  12872. // init = WIN_INIT;
  12873. // zmemzero(s->window + curr, (unsigned)init);
  12874. // s->high_water = curr + init;
  12875. // }
  12876. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  12877. // /* High water mark at or above current data, but below current data
  12878. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  12879. // * to end of window, whichever is less.
  12880. // */
  12881. // init = (ulg)curr + WIN_INIT - s->high_water;
  12882. // if (init > s->window_size - s->high_water)
  12883. // init = s->window_size - s->high_water;
  12884. // zmemzero(s->window + s->high_water, (unsigned)init);
  12885. // s->high_water += init;
  12886. // }
  12887. // }
  12888. //
  12889. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  12890. // "not enough room for search");
  12891. }
  12892. /* ===========================================================================
  12893. * Copy without compression as much as possible from the input stream, return
  12894. * the current block state.
  12895. * This function does not insert new strings in the dictionary since
  12896. * uncompressible data is probably not useful. This function is used
  12897. * only for the level=0 compression option.
  12898. * NOTE: this function should be optimized to avoid extra copying from
  12899. * window to pending_buf.
  12900. */
  12901. function deflate_stored(s, flush) {
  12902. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  12903. * to pending_buf_size, and each stored block has a 5 byte header:
  12904. */
  12905. var max_block_size = 0xffff;
  12906. if (max_block_size > s.pending_buf_size - 5) {
  12907. max_block_size = s.pending_buf_size - 5;
  12908. }
  12909. /* Copy as much as possible from input to output: */
  12910. for (;;) {
  12911. /* Fill the window as much as possible: */
  12912. if (s.lookahead <= 1) {
  12913. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  12914. // s->block_start >= (long)s->w_size, "slide too late");
  12915. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  12916. // s.block_start >= s.w_size)) {
  12917. // throw new Error("slide too late");
  12918. // }
  12919. fill_window(s);
  12920. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  12921. return BS_NEED_MORE;
  12922. }
  12923. if (s.lookahead === 0) {
  12924. break;
  12925. }
  12926. /* flush the current block */
  12927. }
  12928. //Assert(s->block_start >= 0L, "block gone");
  12929. // if (s.block_start < 0) throw new Error("block gone");
  12930. s.strstart += s.lookahead;
  12931. s.lookahead = 0;
  12932. /* Emit a stored block if pending_buf will be full: */
  12933. var max_start = s.block_start + max_block_size;
  12934. if (s.strstart === 0 || s.strstart >= max_start) {
  12935. /* strstart == 0 is possible when wraparound on 16-bit machine */
  12936. s.lookahead = s.strstart - max_start;
  12937. s.strstart = max_start;
  12938. /*** FLUSH_BLOCK(s, 0); ***/
  12939. flush_block_only(s, false);
  12940. if (s.strm.avail_out === 0) {
  12941. return BS_NEED_MORE;
  12942. }
  12943. /***/
  12944. }
  12945. /* Flush if we may have to slide, otherwise block_start may become
  12946. * negative and the data will be gone:
  12947. */
  12948. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  12949. /*** FLUSH_BLOCK(s, 0); ***/
  12950. flush_block_only(s, false);
  12951. if (s.strm.avail_out === 0) {
  12952. return BS_NEED_MORE;
  12953. }
  12954. /***/
  12955. }
  12956. }
  12957. s.insert = 0;
  12958. if (flush === Z_FINISH) {
  12959. /*** FLUSH_BLOCK(s, 1); ***/
  12960. flush_block_only(s, true);
  12961. if (s.strm.avail_out === 0) {
  12962. return BS_FINISH_STARTED;
  12963. }
  12964. /***/
  12965. return BS_FINISH_DONE;
  12966. }
  12967. if (s.strstart > s.block_start) {
  12968. /*** FLUSH_BLOCK(s, 0); ***/
  12969. flush_block_only(s, false);
  12970. if (s.strm.avail_out === 0) {
  12971. return BS_NEED_MORE;
  12972. }
  12973. /***/
  12974. }
  12975. return BS_NEED_MORE;
  12976. }
  12977. /* ===========================================================================
  12978. * Compress as much as possible from the input stream, return the current
  12979. * block state.
  12980. * This function does not perform lazy evaluation of matches and inserts
  12981. * new strings in the dictionary only for unmatched strings or for short
  12982. * matches. It is used only for the fast compression options.
  12983. */
  12984. function deflate_fast(s, flush) {
  12985. var hash_head; /* head of the hash chain */
  12986. var bflush; /* set if current block must be flushed */
  12987. for (;;) {
  12988. /* Make sure that we always have enough lookahead, except
  12989. * at the end of the input file. We need MAX_MATCH bytes
  12990. * for the next match, plus MIN_MATCH bytes to insert the
  12991. * string following the next match.
  12992. */
  12993. if (s.lookahead < MIN_LOOKAHEAD) {
  12994. fill_window(s);
  12995. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  12996. return BS_NEED_MORE;
  12997. }
  12998. if (s.lookahead === 0) {
  12999. break; /* flush the current block */
  13000. }
  13001. }
  13002. /* Insert the string window[strstart .. strstart+2] in the
  13003. * dictionary, and set hash_head to the head of the hash chain:
  13004. */
  13005. hash_head = 0/*NIL*/;
  13006. if (s.lookahead >= MIN_MATCH) {
  13007. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  13008. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  13009. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  13010. s.head[s.ins_h] = s.strstart;
  13011. /***/
  13012. }
  13013. /* Find the longest match, discarding those <= prev_length.
  13014. * At this point we have always match_length < MIN_MATCH
  13015. */
  13016. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  13017. /* To simplify the code, we prevent matches with the string
  13018. * of window index 0 (in particular we have to avoid a match
  13019. * of the string with itself at the start of the input file).
  13020. */
  13021. s.match_length = longest_match(s, hash_head);
  13022. /* longest_match() sets match_start */
  13023. }
  13024. if (s.match_length >= MIN_MATCH) {
  13025. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  13026. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  13027. s.match_length - MIN_MATCH, bflush); ***/
  13028. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  13029. s.lookahead -= s.match_length;
  13030. /* Insert new strings in the hash table only if the match length
  13031. * is not too large. This saves time but degrades compression.
  13032. */
  13033. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  13034. s.match_length--; /* string at strstart already in table */
  13035. do {
  13036. s.strstart++;
  13037. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  13038. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  13039. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  13040. s.head[s.ins_h] = s.strstart;
  13041. /***/
  13042. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  13043. * always MIN_MATCH bytes ahead.
  13044. */
  13045. } while (--s.match_length !== 0);
  13046. s.strstart++;
  13047. } else
  13048. {
  13049. s.strstart += s.match_length;
  13050. s.match_length = 0;
  13051. s.ins_h = s.window[s.strstart];
  13052. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  13053. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  13054. //#if MIN_MATCH != 3
  13055. // Call UPDATE_HASH() MIN_MATCH-3 more times
  13056. //#endif
  13057. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  13058. * matter since it will be recomputed at next deflate call.
  13059. */
  13060. }
  13061. } else {
  13062. /* No match, output a literal byte */
  13063. //Tracevv((stderr,"%c", s.window[s.strstart]));
  13064. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  13065. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  13066. s.lookahead--;
  13067. s.strstart++;
  13068. }
  13069. if (bflush) {
  13070. /*** FLUSH_BLOCK(s, 0); ***/
  13071. flush_block_only(s, false);
  13072. if (s.strm.avail_out === 0) {
  13073. return BS_NEED_MORE;
  13074. }
  13075. /***/
  13076. }
  13077. }
  13078. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  13079. if (flush === Z_FINISH) {
  13080. /*** FLUSH_BLOCK(s, 1); ***/
  13081. flush_block_only(s, true);
  13082. if (s.strm.avail_out === 0) {
  13083. return BS_FINISH_STARTED;
  13084. }
  13085. /***/
  13086. return BS_FINISH_DONE;
  13087. }
  13088. if (s.last_lit) {
  13089. /*** FLUSH_BLOCK(s, 0); ***/
  13090. flush_block_only(s, false);
  13091. if (s.strm.avail_out === 0) {
  13092. return BS_NEED_MORE;
  13093. }
  13094. /***/
  13095. }
  13096. return BS_BLOCK_DONE;
  13097. }
  13098. /* ===========================================================================
  13099. * Same as above, but achieves better compression. We use a lazy
  13100. * evaluation for matches: a match is finally adopted only if there is
  13101. * no better match at the next window position.
  13102. */
  13103. function deflate_slow(s, flush) {
  13104. var hash_head; /* head of hash chain */
  13105. var bflush; /* set if current block must be flushed */
  13106. var max_insert;
  13107. /* Process the input block. */
  13108. for (;;) {
  13109. /* Make sure that we always have enough lookahead, except
  13110. * at the end of the input file. We need MAX_MATCH bytes
  13111. * for the next match, plus MIN_MATCH bytes to insert the
  13112. * string following the next match.
  13113. */
  13114. if (s.lookahead < MIN_LOOKAHEAD) {
  13115. fill_window(s);
  13116. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  13117. return BS_NEED_MORE;
  13118. }
  13119. if (s.lookahead === 0) { break; } /* flush the current block */
  13120. }
  13121. /* Insert the string window[strstart .. strstart+2] in the
  13122. * dictionary, and set hash_head to the head of the hash chain:
  13123. */
  13124. hash_head = 0/*NIL*/;
  13125. if (s.lookahead >= MIN_MATCH) {
  13126. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  13127. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  13128. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  13129. s.head[s.ins_h] = s.strstart;
  13130. /***/
  13131. }
  13132. /* Find the longest match, discarding those <= prev_length.
  13133. */
  13134. s.prev_length = s.match_length;
  13135. s.prev_match = s.match_start;
  13136. s.match_length = MIN_MATCH-1;
  13137. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  13138. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  13139. /* To simplify the code, we prevent matches with the string
  13140. * of window index 0 (in particular we have to avoid a match
  13141. * of the string with itself at the start of the input file).
  13142. */
  13143. s.match_length = longest_match(s, hash_head);
  13144. /* longest_match() sets match_start */
  13145. if (s.match_length <= 5 &&
  13146. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  13147. /* If prev_match is also MIN_MATCH, match_start is garbage
  13148. * but we will ignore the current match anyway.
  13149. */
  13150. s.match_length = MIN_MATCH-1;
  13151. }
  13152. }
  13153. /* If there was a match at the previous step and the current
  13154. * match is not better, output the previous match:
  13155. */
  13156. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  13157. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  13158. /* Do not insert strings in hash table beyond this. */
  13159. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  13160. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  13161. s.prev_length - MIN_MATCH, bflush);***/
  13162. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  13163. /* Insert in hash table all strings up to the end of the match.
  13164. * strstart-1 and strstart are already inserted. If there is not
  13165. * enough lookahead, the last two strings are not inserted in
  13166. * the hash table.
  13167. */
  13168. s.lookahead -= s.prev_length-1;
  13169. s.prev_length -= 2;
  13170. do {
  13171. if (++s.strstart <= max_insert) {
  13172. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  13173. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  13174. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  13175. s.head[s.ins_h] = s.strstart;
  13176. /***/
  13177. }
  13178. } while (--s.prev_length !== 0);
  13179. s.match_available = 0;
  13180. s.match_length = MIN_MATCH-1;
  13181. s.strstart++;
  13182. if (bflush) {
  13183. /*** FLUSH_BLOCK(s, 0); ***/
  13184. flush_block_only(s, false);
  13185. if (s.strm.avail_out === 0) {
  13186. return BS_NEED_MORE;
  13187. }
  13188. /***/
  13189. }
  13190. } else if (s.match_available) {
  13191. /* If there was no match at the previous position, output a
  13192. * single literal. If there was a match but the current match
  13193. * is longer, truncate the previous match to a single literal.
  13194. */
  13195. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  13196. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  13197. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  13198. if (bflush) {
  13199. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  13200. flush_block_only(s, false);
  13201. /***/
  13202. }
  13203. s.strstart++;
  13204. s.lookahead--;
  13205. if (s.strm.avail_out === 0) {
  13206. return BS_NEED_MORE;
  13207. }
  13208. } else {
  13209. /* There is no previous match to compare with, wait for
  13210. * the next step to decide.
  13211. */
  13212. s.match_available = 1;
  13213. s.strstart++;
  13214. s.lookahead--;
  13215. }
  13216. }
  13217. //Assert (flush != Z_NO_FLUSH, "no flush?");
  13218. if (s.match_available) {
  13219. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  13220. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  13221. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  13222. s.match_available = 0;
  13223. }
  13224. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  13225. if (flush === Z_FINISH) {
  13226. /*** FLUSH_BLOCK(s, 1); ***/
  13227. flush_block_only(s, true);
  13228. if (s.strm.avail_out === 0) {
  13229. return BS_FINISH_STARTED;
  13230. }
  13231. /***/
  13232. return BS_FINISH_DONE;
  13233. }
  13234. if (s.last_lit) {
  13235. /*** FLUSH_BLOCK(s, 0); ***/
  13236. flush_block_only(s, false);
  13237. if (s.strm.avail_out === 0) {
  13238. return BS_NEED_MORE;
  13239. }
  13240. /***/
  13241. }
  13242. return BS_BLOCK_DONE;
  13243. }
  13244. /* ===========================================================================
  13245. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  13246. * one. Do not maintain a hash table. (It will be regenerated if this run of
  13247. * deflate switches away from Z_RLE.)
  13248. */
  13249. function deflate_rle(s, flush) {
  13250. var bflush; /* set if current block must be flushed */
  13251. var prev; /* byte at distance one to match */
  13252. var scan, strend; /* scan goes up to strend for length of run */
  13253. var _win = s.window;
  13254. for (;;) {
  13255. /* Make sure that we always have enough lookahead, except
  13256. * at the end of the input file. We need MAX_MATCH bytes
  13257. * for the longest run, plus one for the unrolled loop.
  13258. */
  13259. if (s.lookahead <= MAX_MATCH) {
  13260. fill_window(s);
  13261. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  13262. return BS_NEED_MORE;
  13263. }
  13264. if (s.lookahead === 0) { break; } /* flush the current block */
  13265. }
  13266. /* See how many times the previous byte repeats */
  13267. s.match_length = 0;
  13268. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  13269. scan = s.strstart - 1;
  13270. prev = _win[scan];
  13271. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  13272. strend = s.strstart + MAX_MATCH;
  13273. do {
  13274. /*jshint noempty:false*/
  13275. } while (prev === _win[++scan] && prev === _win[++scan] &&
  13276. prev === _win[++scan] && prev === _win[++scan] &&
  13277. prev === _win[++scan] && prev === _win[++scan] &&
  13278. prev === _win[++scan] && prev === _win[++scan] &&
  13279. scan < strend);
  13280. s.match_length = MAX_MATCH - (strend - scan);
  13281. if (s.match_length > s.lookahead) {
  13282. s.match_length = s.lookahead;
  13283. }
  13284. }
  13285. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  13286. }
  13287. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  13288. if (s.match_length >= MIN_MATCH) {
  13289. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  13290. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  13291. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  13292. s.lookahead -= s.match_length;
  13293. s.strstart += s.match_length;
  13294. s.match_length = 0;
  13295. } else {
  13296. /* No match, output a literal byte */
  13297. //Tracevv((stderr,"%c", s->window[s->strstart]));
  13298. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  13299. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  13300. s.lookahead--;
  13301. s.strstart++;
  13302. }
  13303. if (bflush) {
  13304. /*** FLUSH_BLOCK(s, 0); ***/
  13305. flush_block_only(s, false);
  13306. if (s.strm.avail_out === 0) {
  13307. return BS_NEED_MORE;
  13308. }
  13309. /***/
  13310. }
  13311. }
  13312. s.insert = 0;
  13313. if (flush === Z_FINISH) {
  13314. /*** FLUSH_BLOCK(s, 1); ***/
  13315. flush_block_only(s, true);
  13316. if (s.strm.avail_out === 0) {
  13317. return BS_FINISH_STARTED;
  13318. }
  13319. /***/
  13320. return BS_FINISH_DONE;
  13321. }
  13322. if (s.last_lit) {
  13323. /*** FLUSH_BLOCK(s, 0); ***/
  13324. flush_block_only(s, false);
  13325. if (s.strm.avail_out === 0) {
  13326. return BS_NEED_MORE;
  13327. }
  13328. /***/
  13329. }
  13330. return BS_BLOCK_DONE;
  13331. }
  13332. /* ===========================================================================
  13333. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  13334. * (It will be regenerated if this run of deflate switches away from Huffman.)
  13335. */
  13336. function deflate_huff(s, flush) {
  13337. var bflush; /* set if current block must be flushed */
  13338. for (;;) {
  13339. /* Make sure that we have a literal to write. */
  13340. if (s.lookahead === 0) {
  13341. fill_window(s);
  13342. if (s.lookahead === 0) {
  13343. if (flush === Z_NO_FLUSH) {
  13344. return BS_NEED_MORE;
  13345. }
  13346. break; /* flush the current block */
  13347. }
  13348. }
  13349. /* Output a literal byte */
  13350. s.match_length = 0;
  13351. //Tracevv((stderr,"%c", s->window[s->strstart]));
  13352. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  13353. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  13354. s.lookahead--;
  13355. s.strstart++;
  13356. if (bflush) {
  13357. /*** FLUSH_BLOCK(s, 0); ***/
  13358. flush_block_only(s, false);
  13359. if (s.strm.avail_out === 0) {
  13360. return BS_NEED_MORE;
  13361. }
  13362. /***/
  13363. }
  13364. }
  13365. s.insert = 0;
  13366. if (flush === Z_FINISH) {
  13367. /*** FLUSH_BLOCK(s, 1); ***/
  13368. flush_block_only(s, true);
  13369. if (s.strm.avail_out === 0) {
  13370. return BS_FINISH_STARTED;
  13371. }
  13372. /***/
  13373. return BS_FINISH_DONE;
  13374. }
  13375. if (s.last_lit) {
  13376. /*** FLUSH_BLOCK(s, 0); ***/
  13377. flush_block_only(s, false);
  13378. if (s.strm.avail_out === 0) {
  13379. return BS_NEED_MORE;
  13380. }
  13381. /***/
  13382. }
  13383. return BS_BLOCK_DONE;
  13384. }
  13385. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  13386. * the desired pack level (0..9). The values given below have been tuned to
  13387. * exclude worst case performance for pathological files. Better values may be
  13388. * found for specific files.
  13389. */
  13390. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  13391. this.good_length = good_length;
  13392. this.max_lazy = max_lazy;
  13393. this.nice_length = nice_length;
  13394. this.max_chain = max_chain;
  13395. this.func = func;
  13396. };
  13397. var configuration_table;
  13398. configuration_table = [
  13399. /* good lazy nice chain */
  13400. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  13401. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  13402. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  13403. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  13404. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  13405. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  13406. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  13407. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  13408. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  13409. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  13410. ];
  13411. /* ===========================================================================
  13412. * Initialize the "longest match" routines for a new zlib stream
  13413. */
  13414. function lm_init(s) {
  13415. s.window_size = 2 * s.w_size;
  13416. /*** CLEAR_HASH(s); ***/
  13417. zero(s.head); // Fill with NIL (= 0);
  13418. /* Set the default configuration parameters:
  13419. */
  13420. s.max_lazy_match = configuration_table[s.level].max_lazy;
  13421. s.good_match = configuration_table[s.level].good_length;
  13422. s.nice_match = configuration_table[s.level].nice_length;
  13423. s.max_chain_length = configuration_table[s.level].max_chain;
  13424. s.strstart = 0;
  13425. s.block_start = 0;
  13426. s.lookahead = 0;
  13427. s.insert = 0;
  13428. s.match_length = s.prev_length = MIN_MATCH - 1;
  13429. s.match_available = 0;
  13430. s.ins_h = 0;
  13431. }
  13432. function DeflateState() {
  13433. this.strm = null; /* pointer back to this zlib stream */
  13434. this.status = 0; /* as the name implies */
  13435. this.pending_buf = null; /* output still pending */
  13436. this.pending_buf_size = 0; /* size of pending_buf */
  13437. this.pending_out = 0; /* next pending byte to output to the stream */
  13438. this.pending = 0; /* nb of bytes in the pending buffer */
  13439. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  13440. this.gzhead = null; /* gzip header information to write */
  13441. this.gzindex = 0; /* where in extra, name, or comment */
  13442. this.method = Z_DEFLATED; /* can only be DEFLATED */
  13443. this.last_flush = -1; /* value of flush param for previous deflate call */
  13444. this.w_size = 0; /* LZ77 window size (32K by default) */
  13445. this.w_bits = 0; /* log2(w_size) (8..16) */
  13446. this.w_mask = 0; /* w_size - 1 */
  13447. this.window = null;
  13448. /* Sliding window. Input bytes are read into the second half of the window,
  13449. * and move to the first half later to keep a dictionary of at least wSize
  13450. * bytes. With this organization, matches are limited to a distance of
  13451. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  13452. * performed with a length multiple of the block size.
  13453. */
  13454. this.window_size = 0;
  13455. /* Actual size of window: 2*wSize, except when the user input buffer
  13456. * is directly used as sliding window.
  13457. */
  13458. this.prev = null;
  13459. /* Link to older string with same hash index. To limit the size of this
  13460. * array to 64K, this link is maintained only for the last 32K strings.
  13461. * An index in this array is thus a window index modulo 32K.
  13462. */
  13463. this.head = null; /* Heads of the hash chains or NIL. */
  13464. this.ins_h = 0; /* hash index of string to be inserted */
  13465. this.hash_size = 0; /* number of elements in hash table */
  13466. this.hash_bits = 0; /* log2(hash_size) */
  13467. this.hash_mask = 0; /* hash_size-1 */
  13468. this.hash_shift = 0;
  13469. /* Number of bits by which ins_h must be shifted at each input
  13470. * step. It must be such that after MIN_MATCH steps, the oldest
  13471. * byte no longer takes part in the hash key, that is:
  13472. * hash_shift * MIN_MATCH >= hash_bits
  13473. */
  13474. this.block_start = 0;
  13475. /* Window position at the beginning of the current output block. Gets
  13476. * negative when the window is moved backwards.
  13477. */
  13478. this.match_length = 0; /* length of best match */
  13479. this.prev_match = 0; /* previous match */
  13480. this.match_available = 0; /* set if previous match exists */
  13481. this.strstart = 0; /* start of string to insert */
  13482. this.match_start = 0; /* start of matching string */
  13483. this.lookahead = 0; /* number of valid bytes ahead in window */
  13484. this.prev_length = 0;
  13485. /* Length of the best match at previous step. Matches not greater than this
  13486. * are discarded. This is used in the lazy match evaluation.
  13487. */
  13488. this.max_chain_length = 0;
  13489. /* To speed up deflation, hash chains are never searched beyond this
  13490. * length. A higher limit improves compression ratio but degrades the
  13491. * speed.
  13492. */
  13493. this.max_lazy_match = 0;
  13494. /* Attempt to find a better match only when the current match is strictly
  13495. * smaller than this value. This mechanism is used only for compression
  13496. * levels >= 4.
  13497. */
  13498. // That's alias to max_lazy_match, don't use directly
  13499. //this.max_insert_length = 0;
  13500. /* Insert new strings in the hash table only if the match length is not
  13501. * greater than this length. This saves time but degrades compression.
  13502. * max_insert_length is used only for compression levels <= 3.
  13503. */
  13504. this.level = 0; /* compression level (1..9) */
  13505. this.strategy = 0; /* favor or force Huffman coding*/
  13506. this.good_match = 0;
  13507. /* Use a faster search when the previous match is longer than this */
  13508. this.nice_match = 0; /* Stop searching when current match exceeds this */
  13509. /* used by trees.c: */
  13510. /* Didn't use ct_data typedef below to suppress compiler warning */
  13511. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  13512. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  13513. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  13514. // Use flat array of DOUBLE size, with interleaved fata,
  13515. // because JS does not support effective
  13516. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  13517. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  13518. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  13519. zero(this.dyn_ltree);
  13520. zero(this.dyn_dtree);
  13521. zero(this.bl_tree);
  13522. this.l_desc = null; /* desc. for literal tree */
  13523. this.d_desc = null; /* desc. for distance tree */
  13524. this.bl_desc = null; /* desc. for bit length tree */
  13525. //ush bl_count[MAX_BITS+1];
  13526. this.bl_count = new utils.Buf16(MAX_BITS+1);
  13527. /* number of codes at each bit length for an optimal tree */
  13528. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  13529. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  13530. zero(this.heap);
  13531. this.heap_len = 0; /* number of elements in the heap */
  13532. this.heap_max = 0; /* element of largest frequency */
  13533. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  13534. * The same heap array is used to build all trees.
  13535. */
  13536. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  13537. zero(this.depth);
  13538. /* Depth of each subtree used as tie breaker for trees of equal frequency
  13539. */
  13540. this.l_buf = 0; /* buffer index for literals or lengths */
  13541. this.lit_bufsize = 0;
  13542. /* Size of match buffer for literals/lengths. There are 4 reasons for
  13543. * limiting lit_bufsize to 64K:
  13544. * - frequencies can be kept in 16 bit counters
  13545. * - if compression is not successful for the first block, all input
  13546. * data is still in the window so we can still emit a stored block even
  13547. * when input comes from standard input. (This can also be done for
  13548. * all blocks if lit_bufsize is not greater than 32K.)
  13549. * - if compression is not successful for a file smaller than 64K, we can
  13550. * even emit a stored file instead of a stored block (saving 5 bytes).
  13551. * This is applicable only for zip (not gzip or zlib).
  13552. * - creating new Huffman trees less frequently may not provide fast
  13553. * adaptation to changes in the input data statistics. (Take for
  13554. * example a binary file with poorly compressible code followed by
  13555. * a highly compressible string table.) Smaller buffer sizes give
  13556. * fast adaptation but have of course the overhead of transmitting
  13557. * trees more frequently.
  13558. * - I can't count above 4
  13559. */
  13560. this.last_lit = 0; /* running index in l_buf */
  13561. this.d_buf = 0;
  13562. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  13563. * the same number of elements. To use different lengths, an extra flag
  13564. * array would be necessary.
  13565. */
  13566. this.opt_len = 0; /* bit length of current block with optimal trees */
  13567. this.static_len = 0; /* bit length of current block with static trees */
  13568. this.matches = 0; /* number of string matches in current block */
  13569. this.insert = 0; /* bytes at end of window left to insert */
  13570. this.bi_buf = 0;
  13571. /* Output buffer. bits are inserted starting at the bottom (least
  13572. * significant bits).
  13573. */
  13574. this.bi_valid = 0;
  13575. /* Number of valid bits in bi_buf. All bits above the last valid bit
  13576. * are always zero.
  13577. */
  13578. // Used for window memory init. We safely ignore it for JS. That makes
  13579. // sense only for pointers and memory check tools.
  13580. //this.high_water = 0;
  13581. /* High water mark offset in window for initialized bytes -- bytes above
  13582. * this are set to zero in order to avoid memory check warnings when
  13583. * longest match routines access bytes past the input. This is then
  13584. * updated to the new high water mark.
  13585. */
  13586. }
  13587. function deflateResetKeep(strm) {
  13588. var s;
  13589. if (!strm || !strm.state) {
  13590. return err(strm, Z_STREAM_ERROR);
  13591. }
  13592. strm.total_in = strm.total_out = 0;
  13593. strm.data_type = Z_UNKNOWN;
  13594. s = strm.state;
  13595. s.pending = 0;
  13596. s.pending_out = 0;
  13597. if (s.wrap < 0) {
  13598. s.wrap = -s.wrap;
  13599. /* was made negative by deflate(..., Z_FINISH); */
  13600. }
  13601. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  13602. strm.adler = (s.wrap === 2) ?
  13603. 0 // crc32(0, Z_NULL, 0)
  13604. :
  13605. 1; // adler32(0, Z_NULL, 0)
  13606. s.last_flush = Z_NO_FLUSH;
  13607. trees._tr_init(s);
  13608. return Z_OK;
  13609. }
  13610. function deflateReset(strm) {
  13611. var ret = deflateResetKeep(strm);
  13612. if (ret === Z_OK) {
  13613. lm_init(strm.state);
  13614. }
  13615. return ret;
  13616. }
  13617. function deflateSetHeader(strm, head) {
  13618. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  13619. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  13620. strm.state.gzhead = head;
  13621. return Z_OK;
  13622. }
  13623. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  13624. if (!strm) { // === Z_NULL
  13625. return Z_STREAM_ERROR;
  13626. }
  13627. var wrap = 1;
  13628. if (level === Z_DEFAULT_COMPRESSION) {
  13629. level = 6;
  13630. }
  13631. if (windowBits < 0) { /* suppress zlib wrapper */
  13632. wrap = 0;
  13633. windowBits = -windowBits;
  13634. }
  13635. else if (windowBits > 15) {
  13636. wrap = 2; /* write gzip wrapper instead */
  13637. windowBits -= 16;
  13638. }
  13639. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  13640. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  13641. strategy < 0 || strategy > Z_FIXED) {
  13642. return err(strm, Z_STREAM_ERROR);
  13643. }
  13644. if (windowBits === 8) {
  13645. windowBits = 9;
  13646. }
  13647. /* until 256-byte window bug fixed */
  13648. var s = new DeflateState();
  13649. strm.state = s;
  13650. s.strm = strm;
  13651. s.wrap = wrap;
  13652. s.gzhead = null;
  13653. s.w_bits = windowBits;
  13654. s.w_size = 1 << s.w_bits;
  13655. s.w_mask = s.w_size - 1;
  13656. s.hash_bits = memLevel + 7;
  13657. s.hash_size = 1 << s.hash_bits;
  13658. s.hash_mask = s.hash_size - 1;
  13659. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  13660. s.window = new utils.Buf8(s.w_size * 2);
  13661. s.head = new utils.Buf16(s.hash_size);
  13662. s.prev = new utils.Buf16(s.w_size);
  13663. // Don't need mem init magic for JS.
  13664. //s.high_water = 0; /* nothing written to s->window yet */
  13665. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  13666. s.pending_buf_size = s.lit_bufsize * 4;
  13667. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  13668. s.d_buf = s.lit_bufsize >> 1;
  13669. s.l_buf = (1 + 2) * s.lit_bufsize;
  13670. s.level = level;
  13671. s.strategy = strategy;
  13672. s.method = method;
  13673. return deflateReset(strm);
  13674. }
  13675. function deflateInit(strm, level) {
  13676. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  13677. }
  13678. function deflate(strm, flush) {
  13679. var old_flush, s;
  13680. var beg, val; // for gzip header write only
  13681. if (!strm || !strm.state ||
  13682. flush > Z_BLOCK || flush < 0) {
  13683. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  13684. }
  13685. s = strm.state;
  13686. if (!strm.output ||
  13687. (!strm.input && strm.avail_in !== 0) ||
  13688. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  13689. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  13690. }
  13691. s.strm = strm; /* just in case */
  13692. old_flush = s.last_flush;
  13693. s.last_flush = flush;
  13694. /* Write the header */
  13695. if (s.status === INIT_STATE) {
  13696. if (s.wrap === 2) { // GZIP header
  13697. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  13698. put_byte(s, 31);
  13699. put_byte(s, 139);
  13700. put_byte(s, 8);
  13701. if (!s.gzhead) { // s->gzhead == Z_NULL
  13702. put_byte(s, 0);
  13703. put_byte(s, 0);
  13704. put_byte(s, 0);
  13705. put_byte(s, 0);
  13706. put_byte(s, 0);
  13707. put_byte(s, s.level === 9 ? 2 :
  13708. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  13709. 4 : 0));
  13710. put_byte(s, OS_CODE);
  13711. s.status = BUSY_STATE;
  13712. }
  13713. else {
  13714. put_byte(s, (s.gzhead.text ? 1 : 0) +
  13715. (s.gzhead.hcrc ? 2 : 0) +
  13716. (!s.gzhead.extra ? 0 : 4) +
  13717. (!s.gzhead.name ? 0 : 8) +
  13718. (!s.gzhead.comment ? 0 : 16)
  13719. );
  13720. put_byte(s, s.gzhead.time & 0xff);
  13721. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  13722. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  13723. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  13724. put_byte(s, s.level === 9 ? 2 :
  13725. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  13726. 4 : 0));
  13727. put_byte(s, s.gzhead.os & 0xff);
  13728. if (s.gzhead.extra && s.gzhead.extra.length) {
  13729. put_byte(s, s.gzhead.extra.length & 0xff);
  13730. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  13731. }
  13732. if (s.gzhead.hcrc) {
  13733. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  13734. }
  13735. s.gzindex = 0;
  13736. s.status = EXTRA_STATE;
  13737. }
  13738. }
  13739. else // DEFLATE header
  13740. {
  13741. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  13742. var level_flags = -1;
  13743. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  13744. level_flags = 0;
  13745. } else if (s.level < 6) {
  13746. level_flags = 1;
  13747. } else if (s.level === 6) {
  13748. level_flags = 2;
  13749. } else {
  13750. level_flags = 3;
  13751. }
  13752. header |= (level_flags << 6);
  13753. if (s.strstart !== 0) { header |= PRESET_DICT; }
  13754. header += 31 - (header % 31);
  13755. s.status = BUSY_STATE;
  13756. putShortMSB(s, header);
  13757. /* Save the adler32 of the preset dictionary: */
  13758. if (s.strstart !== 0) {
  13759. putShortMSB(s, strm.adler >>> 16);
  13760. putShortMSB(s, strm.adler & 0xffff);
  13761. }
  13762. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  13763. }
  13764. }
  13765. //#ifdef GZIP
  13766. if (s.status === EXTRA_STATE) {
  13767. if (s.gzhead.extra/* != Z_NULL*/) {
  13768. beg = s.pending; /* start of bytes to update crc */
  13769. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  13770. if (s.pending === s.pending_buf_size) {
  13771. if (s.gzhead.hcrc && s.pending > beg) {
  13772. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  13773. }
  13774. flush_pending(strm);
  13775. beg = s.pending;
  13776. if (s.pending === s.pending_buf_size) {
  13777. break;
  13778. }
  13779. }
  13780. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  13781. s.gzindex++;
  13782. }
  13783. if (s.gzhead.hcrc && s.pending > beg) {
  13784. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  13785. }
  13786. if (s.gzindex === s.gzhead.extra.length) {
  13787. s.gzindex = 0;
  13788. s.status = NAME_STATE;
  13789. }
  13790. }
  13791. else {
  13792. s.status = NAME_STATE;
  13793. }
  13794. }
  13795. if (s.status === NAME_STATE) {
  13796. if (s.gzhead.name/* != Z_NULL*/) {
  13797. beg = s.pending; /* start of bytes to update crc */
  13798. //int val;
  13799. do {
  13800. if (s.pending === s.pending_buf_size) {
  13801. if (s.gzhead.hcrc && s.pending > beg) {
  13802. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  13803. }
  13804. flush_pending(strm);
  13805. beg = s.pending;
  13806. if (s.pending === s.pending_buf_size) {
  13807. val = 1;
  13808. break;
  13809. }
  13810. }
  13811. // JS specific: little magic to add zero terminator to end of string
  13812. if (s.gzindex < s.gzhead.name.length) {
  13813. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  13814. } else {
  13815. val = 0;
  13816. }
  13817. put_byte(s, val);
  13818. } while (val !== 0);
  13819. if (s.gzhead.hcrc && s.pending > beg) {
  13820. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  13821. }
  13822. if (val === 0) {
  13823. s.gzindex = 0;
  13824. s.status = COMMENT_STATE;
  13825. }
  13826. }
  13827. else {
  13828. s.status = COMMENT_STATE;
  13829. }
  13830. }
  13831. if (s.status === COMMENT_STATE) {
  13832. if (s.gzhead.comment/* != Z_NULL*/) {
  13833. beg = s.pending; /* start of bytes to update crc */
  13834. //int val;
  13835. do {
  13836. if (s.pending === s.pending_buf_size) {
  13837. if (s.gzhead.hcrc && s.pending > beg) {
  13838. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  13839. }
  13840. flush_pending(strm);
  13841. beg = s.pending;
  13842. if (s.pending === s.pending_buf_size) {
  13843. val = 1;
  13844. break;
  13845. }
  13846. }
  13847. // JS specific: little magic to add zero terminator to end of string
  13848. if (s.gzindex < s.gzhead.comment.length) {
  13849. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  13850. } else {
  13851. val = 0;
  13852. }
  13853. put_byte(s, val);
  13854. } while (val !== 0);
  13855. if (s.gzhead.hcrc && s.pending > beg) {
  13856. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  13857. }
  13858. if (val === 0) {
  13859. s.status = HCRC_STATE;
  13860. }
  13861. }
  13862. else {
  13863. s.status = HCRC_STATE;
  13864. }
  13865. }
  13866. if (s.status === HCRC_STATE) {
  13867. if (s.gzhead.hcrc) {
  13868. if (s.pending + 2 > s.pending_buf_size) {
  13869. flush_pending(strm);
  13870. }
  13871. if (s.pending + 2 <= s.pending_buf_size) {
  13872. put_byte(s, strm.adler & 0xff);
  13873. put_byte(s, (strm.adler >> 8) & 0xff);
  13874. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  13875. s.status = BUSY_STATE;
  13876. }
  13877. }
  13878. else {
  13879. s.status = BUSY_STATE;
  13880. }
  13881. }
  13882. //#endif
  13883. /* Flush as much pending output as possible */
  13884. if (s.pending !== 0) {
  13885. flush_pending(strm);
  13886. if (strm.avail_out === 0) {
  13887. /* Since avail_out is 0, deflate will be called again with
  13888. * more output space, but possibly with both pending and
  13889. * avail_in equal to zero. There won't be anything to do,
  13890. * but this is not an error situation so make sure we
  13891. * return OK instead of BUF_ERROR at next call of deflate:
  13892. */
  13893. s.last_flush = -1;
  13894. return Z_OK;
  13895. }
  13896. /* Make sure there is something to do and avoid duplicate consecutive
  13897. * flushes. For repeated and useless calls with Z_FINISH, we keep
  13898. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  13899. */
  13900. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  13901. flush !== Z_FINISH) {
  13902. return err(strm, Z_BUF_ERROR);
  13903. }
  13904. /* User must not provide more input after the first FINISH: */
  13905. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  13906. return err(strm, Z_BUF_ERROR);
  13907. }
  13908. /* Start a new block or continue the current one.
  13909. */
  13910. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  13911. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  13912. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  13913. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  13914. configuration_table[s.level].func(s, flush));
  13915. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  13916. s.status = FINISH_STATE;
  13917. }
  13918. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  13919. if (strm.avail_out === 0) {
  13920. s.last_flush = -1;
  13921. /* avoid BUF_ERROR next call, see above */
  13922. }
  13923. return Z_OK;
  13924. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  13925. * of deflate should use the same flush parameter to make sure
  13926. * that the flush is complete. So we don't have to output an
  13927. * empty block here, this will be done at next call. This also
  13928. * ensures that for a very small output buffer, we emit at most
  13929. * one empty block.
  13930. */
  13931. }
  13932. if (bstate === BS_BLOCK_DONE) {
  13933. if (flush === Z_PARTIAL_FLUSH) {
  13934. trees._tr_align(s);
  13935. }
  13936. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  13937. trees._tr_stored_block(s, 0, 0, false);
  13938. /* For a full flush, this empty block will be recognized
  13939. * as a special marker by inflate_sync().
  13940. */
  13941. if (flush === Z_FULL_FLUSH) {
  13942. /*** CLEAR_HASH(s); ***/ /* forget history */
  13943. zero(s.head); // Fill with NIL (= 0);
  13944. if (s.lookahead === 0) {
  13945. s.strstart = 0;
  13946. s.block_start = 0;
  13947. s.insert = 0;
  13948. }
  13949. }
  13950. }
  13951. flush_pending(strm);
  13952. if (strm.avail_out === 0) {
  13953. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  13954. return Z_OK;
  13955. }
  13956. }
  13957. }
  13958. //Assert(strm->avail_out > 0, "bug2");
  13959. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  13960. if (flush !== Z_FINISH) { return Z_OK; }
  13961. if (s.wrap <= 0) { return Z_STREAM_END; }
  13962. /* Write the trailer */
  13963. if (s.wrap === 2) {
  13964. put_byte(s, strm.adler & 0xff);
  13965. put_byte(s, (strm.adler >> 8) & 0xff);
  13966. put_byte(s, (strm.adler >> 16) & 0xff);
  13967. put_byte(s, (strm.adler >> 24) & 0xff);
  13968. put_byte(s, strm.total_in & 0xff);
  13969. put_byte(s, (strm.total_in >> 8) & 0xff);
  13970. put_byte(s, (strm.total_in >> 16) & 0xff);
  13971. put_byte(s, (strm.total_in >> 24) & 0xff);
  13972. }
  13973. else
  13974. {
  13975. putShortMSB(s, strm.adler >>> 16);
  13976. putShortMSB(s, strm.adler & 0xffff);
  13977. }
  13978. flush_pending(strm);
  13979. /* If avail_out is zero, the application will call deflate again
  13980. * to flush the rest.
  13981. */
  13982. if (s.wrap > 0) { s.wrap = -s.wrap; }
  13983. /* write the trailer only once! */
  13984. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  13985. }
  13986. function deflateEnd(strm) {
  13987. var status;
  13988. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  13989. return Z_STREAM_ERROR;
  13990. }
  13991. status = strm.state.status;
  13992. if (status !== INIT_STATE &&
  13993. status !== EXTRA_STATE &&
  13994. status !== NAME_STATE &&
  13995. status !== COMMENT_STATE &&
  13996. status !== HCRC_STATE &&
  13997. status !== BUSY_STATE &&
  13998. status !== FINISH_STATE
  13999. ) {
  14000. return err(strm, Z_STREAM_ERROR);
  14001. }
  14002. strm.state = null;
  14003. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  14004. }
  14005. /* =========================================================================
  14006. * Copy the source state to the destination state
  14007. */
  14008. //function deflateCopy(dest, source) {
  14009. //
  14010. //}
  14011. exports.deflateInit = deflateInit;
  14012. exports.deflateInit2 = deflateInit2;
  14013. exports.deflateReset = deflateReset;
  14014. exports.deflateResetKeep = deflateResetKeep;
  14015. exports.deflateSetHeader = deflateSetHeader;
  14016. exports.deflate = deflate;
  14017. exports.deflateEnd = deflateEnd;
  14018. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  14019. /* Not implemented
  14020. exports.deflateBound = deflateBound;
  14021. exports.deflateCopy = deflateCopy;
  14022. exports.deflateSetDictionary = deflateSetDictionary;
  14023. exports.deflateParams = deflateParams;
  14024. exports.deflatePending = deflatePending;
  14025. exports.deflatePrime = deflatePrime;
  14026. exports.deflateTune = deflateTune;
  14027. */
  14028. },{"../utils/common":45,"./adler32":47,"./crc32":49,"./messages":55,"./trees":56}],51:[function(require,module,exports){
  14029. 'use strict';
  14030. function GZheader() {
  14031. /* true if compressed data believed to be text */
  14032. this.text = 0;
  14033. /* modification time */
  14034. this.time = 0;
  14035. /* extra flags (not used when writing a gzip file) */
  14036. this.xflags = 0;
  14037. /* operating system */
  14038. this.os = 0;
  14039. /* pointer to extra field or Z_NULL if none */
  14040. this.extra = null;
  14041. /* extra field length (valid if extra != Z_NULL) */
  14042. this.extra_len = 0; // Actually, we don't need it in JS,
  14043. // but leave for few code modifications
  14044. //
  14045. // Setup limits is not necessary because in js we should not preallocate memory
  14046. // for inflate use constant limit in 65536 bytes
  14047. //
  14048. /* space at extra (only when reading header) */
  14049. // this.extra_max = 0;
  14050. /* pointer to zero-terminated file name or Z_NULL */
  14051. this.name = '';
  14052. /* space at name (only when reading header) */
  14053. // this.name_max = 0;
  14054. /* pointer to zero-terminated comment or Z_NULL */
  14055. this.comment = '';
  14056. /* space at comment (only when reading header) */
  14057. // this.comm_max = 0;
  14058. /* true if there was or will be a header crc */
  14059. this.hcrc = 0;
  14060. /* true when done reading gzip header (not used when writing a gzip file) */
  14061. this.done = false;
  14062. }
  14063. module.exports = GZheader;
  14064. },{}],52:[function(require,module,exports){
  14065. 'use strict';
  14066. // See state defs from inflate.js
  14067. var BAD = 30; /* got a data error -- remain here until reset */
  14068. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  14069. /*
  14070. Decode literal, length, and distance codes and write out the resulting
  14071. literal and match bytes until either not enough input or output is
  14072. available, an end-of-block is encountered, or a data error is encountered.
  14073. When large enough input and output buffers are supplied to inflate(), for
  14074. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  14075. inflate execution time is spent in this routine.
  14076. Entry assumptions:
  14077. state.mode === LEN
  14078. strm.avail_in >= 6
  14079. strm.avail_out >= 258
  14080. start >= strm.avail_out
  14081. state.bits < 8
  14082. On return, state.mode is one of:
  14083. LEN -- ran out of enough output space or enough available input
  14084. TYPE -- reached end of block code, inflate() to interpret next block
  14085. BAD -- error in block data
  14086. Notes:
  14087. - The maximum input bits used by a length/distance pair is 15 bits for the
  14088. length code, 5 bits for the length extra, 15 bits for the distance code,
  14089. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  14090. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  14091. checking for available input while decoding.
  14092. - The maximum bytes that a single length/distance pair can output is 258
  14093. bytes, which is the maximum length that can be coded. inflate_fast()
  14094. requires strm.avail_out >= 258 for each loop to avoid checking for
  14095. output space.
  14096. */
  14097. module.exports = function inflate_fast(strm, start) {
  14098. var state;
  14099. var _in; /* local strm.input */
  14100. var last; /* have enough input while in < last */
  14101. var _out; /* local strm.output */
  14102. var beg; /* inflate()'s initial strm.output */
  14103. var end; /* while out < end, enough space available */
  14104. //#ifdef INFLATE_STRICT
  14105. var dmax; /* maximum distance from zlib header */
  14106. //#endif
  14107. var wsize; /* window size or zero if not using window */
  14108. var whave; /* valid bytes in the window */
  14109. var wnext; /* window write index */
  14110. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  14111. var s_window; /* allocated sliding window, if wsize != 0 */
  14112. var hold; /* local strm.hold */
  14113. var bits; /* local strm.bits */
  14114. var lcode; /* local strm.lencode */
  14115. var dcode; /* local strm.distcode */
  14116. var lmask; /* mask for first level of length codes */
  14117. var dmask; /* mask for first level of distance codes */
  14118. var here; /* retrieved table entry */
  14119. var op; /* code bits, operation, extra bits, or */
  14120. /* window position, window bytes to copy */
  14121. var len; /* match length, unused bytes */
  14122. var dist; /* match distance */
  14123. var from; /* where to copy match from */
  14124. var from_source;
  14125. var input, output; // JS specific, because we have no pointers
  14126. /* copy state to local variables */
  14127. state = strm.state;
  14128. //here = state.here;
  14129. _in = strm.next_in;
  14130. input = strm.input;
  14131. last = _in + (strm.avail_in - 5);
  14132. _out = strm.next_out;
  14133. output = strm.output;
  14134. beg = _out - (start - strm.avail_out);
  14135. end = _out + (strm.avail_out - 257);
  14136. //#ifdef INFLATE_STRICT
  14137. dmax = state.dmax;
  14138. //#endif
  14139. wsize = state.wsize;
  14140. whave = state.whave;
  14141. wnext = state.wnext;
  14142. s_window = state.window;
  14143. hold = state.hold;
  14144. bits = state.bits;
  14145. lcode = state.lencode;
  14146. dcode = state.distcode;
  14147. lmask = (1 << state.lenbits) - 1;
  14148. dmask = (1 << state.distbits) - 1;
  14149. /* decode literals and length/distances until end-of-block or not enough
  14150. input data or output space */
  14151. top:
  14152. do {
  14153. if (bits < 15) {
  14154. hold += input[_in++] << bits;
  14155. bits += 8;
  14156. hold += input[_in++] << bits;
  14157. bits += 8;
  14158. }
  14159. here = lcode[hold & lmask];
  14160. dolen:
  14161. for (;;) { // Goto emulation
  14162. op = here >>> 24/*here.bits*/;
  14163. hold >>>= op;
  14164. bits -= op;
  14165. op = (here >>> 16) & 0xff/*here.op*/;
  14166. if (op === 0) { /* literal */
  14167. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  14168. // "inflate: literal '%c'\n" :
  14169. // "inflate: literal 0x%02x\n", here.val));
  14170. output[_out++] = here & 0xffff/*here.val*/;
  14171. }
  14172. else if (op & 16) { /* length base */
  14173. len = here & 0xffff/*here.val*/;
  14174. op &= 15; /* number of extra bits */
  14175. if (op) {
  14176. if (bits < op) {
  14177. hold += input[_in++] << bits;
  14178. bits += 8;
  14179. }
  14180. len += hold & ((1 << op) - 1);
  14181. hold >>>= op;
  14182. bits -= op;
  14183. }
  14184. //Tracevv((stderr, "inflate: length %u\n", len));
  14185. if (bits < 15) {
  14186. hold += input[_in++] << bits;
  14187. bits += 8;
  14188. hold += input[_in++] << bits;
  14189. bits += 8;
  14190. }
  14191. here = dcode[hold & dmask];
  14192. dodist:
  14193. for (;;) { // goto emulation
  14194. op = here >>> 24/*here.bits*/;
  14195. hold >>>= op;
  14196. bits -= op;
  14197. op = (here >>> 16) & 0xff/*here.op*/;
  14198. if (op & 16) { /* distance base */
  14199. dist = here & 0xffff/*here.val*/;
  14200. op &= 15; /* number of extra bits */
  14201. if (bits < op) {
  14202. hold += input[_in++] << bits;
  14203. bits += 8;
  14204. if (bits < op) {
  14205. hold += input[_in++] << bits;
  14206. bits += 8;
  14207. }
  14208. }
  14209. dist += hold & ((1 << op) - 1);
  14210. //#ifdef INFLATE_STRICT
  14211. if (dist > dmax) {
  14212. strm.msg = 'invalid distance too far back';
  14213. state.mode = BAD;
  14214. break top;
  14215. }
  14216. //#endif
  14217. hold >>>= op;
  14218. bits -= op;
  14219. //Tracevv((stderr, "inflate: distance %u\n", dist));
  14220. op = _out - beg; /* max distance in output */
  14221. if (dist > op) { /* see if copy from window */
  14222. op = dist - op; /* distance back in window */
  14223. if (op > whave) {
  14224. if (state.sane) {
  14225. strm.msg = 'invalid distance too far back';
  14226. state.mode = BAD;
  14227. break top;
  14228. }
  14229. // (!) This block is disabled in zlib defailts,
  14230. // don't enable it for binary compatibility
  14231. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  14232. // if (len <= op - whave) {
  14233. // do {
  14234. // output[_out++] = 0;
  14235. // } while (--len);
  14236. // continue top;
  14237. // }
  14238. // len -= op - whave;
  14239. // do {
  14240. // output[_out++] = 0;
  14241. // } while (--op > whave);
  14242. // if (op === 0) {
  14243. // from = _out - dist;
  14244. // do {
  14245. // output[_out++] = output[from++];
  14246. // } while (--len);
  14247. // continue top;
  14248. // }
  14249. //#endif
  14250. }
  14251. from = 0; // window index
  14252. from_source = s_window;
  14253. if (wnext === 0) { /* very common case */
  14254. from += wsize - op;
  14255. if (op < len) { /* some from window */
  14256. len -= op;
  14257. do {
  14258. output[_out++] = s_window[from++];
  14259. } while (--op);
  14260. from = _out - dist; /* rest from output */
  14261. from_source = output;
  14262. }
  14263. }
  14264. else if (wnext < op) { /* wrap around window */
  14265. from += wsize + wnext - op;
  14266. op -= wnext;
  14267. if (op < len) { /* some from end of window */
  14268. len -= op;
  14269. do {
  14270. output[_out++] = s_window[from++];
  14271. } while (--op);
  14272. from = 0;
  14273. if (wnext < len) { /* some from start of window */
  14274. op = wnext;
  14275. len -= op;
  14276. do {
  14277. output[_out++] = s_window[from++];
  14278. } while (--op);
  14279. from = _out - dist; /* rest from output */
  14280. from_source = output;
  14281. }
  14282. }
  14283. }
  14284. else { /* contiguous in window */
  14285. from += wnext - op;
  14286. if (op < len) { /* some from window */
  14287. len -= op;
  14288. do {
  14289. output[_out++] = s_window[from++];
  14290. } while (--op);
  14291. from = _out - dist; /* rest from output */
  14292. from_source = output;
  14293. }
  14294. }
  14295. while (len > 2) {
  14296. output[_out++] = from_source[from++];
  14297. output[_out++] = from_source[from++];
  14298. output[_out++] = from_source[from++];
  14299. len -= 3;
  14300. }
  14301. if (len) {
  14302. output[_out++] = from_source[from++];
  14303. if (len > 1) {
  14304. output[_out++] = from_source[from++];
  14305. }
  14306. }
  14307. }
  14308. else {
  14309. from = _out - dist; /* copy direct from output */
  14310. do { /* minimum length is three */
  14311. output[_out++] = output[from++];
  14312. output[_out++] = output[from++];
  14313. output[_out++] = output[from++];
  14314. len -= 3;
  14315. } while (len > 2);
  14316. if (len) {
  14317. output[_out++] = output[from++];
  14318. if (len > 1) {
  14319. output[_out++] = output[from++];
  14320. }
  14321. }
  14322. }
  14323. }
  14324. else if ((op & 64) === 0) { /* 2nd level distance code */
  14325. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  14326. continue dodist;
  14327. }
  14328. else {
  14329. strm.msg = 'invalid distance code';
  14330. state.mode = BAD;
  14331. break top;
  14332. }
  14333. break; // need to emulate goto via "continue"
  14334. }
  14335. }
  14336. else if ((op & 64) === 0) { /* 2nd level length code */
  14337. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  14338. continue dolen;
  14339. }
  14340. else if (op & 32) { /* end-of-block */
  14341. //Tracevv((stderr, "inflate: end of block\n"));
  14342. state.mode = TYPE;
  14343. break top;
  14344. }
  14345. else {
  14346. strm.msg = 'invalid literal/length code';
  14347. state.mode = BAD;
  14348. break top;
  14349. }
  14350. break; // need to emulate goto via "continue"
  14351. }
  14352. } while (_in < last && _out < end);
  14353. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  14354. len = bits >> 3;
  14355. _in -= len;
  14356. bits -= len << 3;
  14357. hold &= (1 << bits) - 1;
  14358. /* update state and return */
  14359. strm.next_in = _in;
  14360. strm.next_out = _out;
  14361. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  14362. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  14363. state.hold = hold;
  14364. state.bits = bits;
  14365. return;
  14366. };
  14367. },{}],53:[function(require,module,exports){
  14368. 'use strict';
  14369. var utils = require('../utils/common');
  14370. var adler32 = require('./adler32');
  14371. var crc32 = require('./crc32');
  14372. var inflate_fast = require('./inffast');
  14373. var inflate_table = require('./inftrees');
  14374. var CODES = 0;
  14375. var LENS = 1;
  14376. var DISTS = 2;
  14377. /* Public constants ==========================================================*/
  14378. /* ===========================================================================*/
  14379. /* Allowed flush values; see deflate() and inflate() below for details */
  14380. //var Z_NO_FLUSH = 0;
  14381. //var Z_PARTIAL_FLUSH = 1;
  14382. //var Z_SYNC_FLUSH = 2;
  14383. //var Z_FULL_FLUSH = 3;
  14384. var Z_FINISH = 4;
  14385. var Z_BLOCK = 5;
  14386. var Z_TREES = 6;
  14387. /* Return codes for the compression/decompression functions. Negative values
  14388. * are errors, positive values are used for special but normal events.
  14389. */
  14390. var Z_OK = 0;
  14391. var Z_STREAM_END = 1;
  14392. var Z_NEED_DICT = 2;
  14393. //var Z_ERRNO = -1;
  14394. var Z_STREAM_ERROR = -2;
  14395. var Z_DATA_ERROR = -3;
  14396. var Z_MEM_ERROR = -4;
  14397. var Z_BUF_ERROR = -5;
  14398. //var Z_VERSION_ERROR = -6;
  14399. /* The deflate compression method */
  14400. var Z_DEFLATED = 8;
  14401. /* STATES ====================================================================*/
  14402. /* ===========================================================================*/
  14403. var HEAD = 1; /* i: waiting for magic header */
  14404. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  14405. var TIME = 3; /* i: waiting for modification time (gzip) */
  14406. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  14407. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  14408. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  14409. var NAME = 7; /* i: waiting for end of file name (gzip) */
  14410. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  14411. var HCRC = 9; /* i: waiting for header crc (gzip) */
  14412. var DICTID = 10; /* i: waiting for dictionary check value */
  14413. var DICT = 11; /* waiting for inflateSetDictionary() call */
  14414. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  14415. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  14416. var STORED = 14; /* i: waiting for stored size (length and complement) */
  14417. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  14418. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  14419. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  14420. var LENLENS = 18; /* i: waiting for code length code lengths */
  14421. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  14422. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  14423. var LEN = 21; /* i: waiting for length/lit/eob code */
  14424. var LENEXT = 22; /* i: waiting for length extra bits */
  14425. var DIST = 23; /* i: waiting for distance code */
  14426. var DISTEXT = 24; /* i: waiting for distance extra bits */
  14427. var MATCH = 25; /* o: waiting for output space to copy string */
  14428. var LIT = 26; /* o: waiting for output space to write literal */
  14429. var CHECK = 27; /* i: waiting for 32-bit check value */
  14430. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  14431. var DONE = 29; /* finished check, done -- remain here until reset */
  14432. var BAD = 30; /* got a data error -- remain here until reset */
  14433. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  14434. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  14435. /* ===========================================================================*/
  14436. var ENOUGH_LENS = 852;
  14437. var ENOUGH_DISTS = 592;
  14438. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  14439. var MAX_WBITS = 15;
  14440. /* 32K LZ77 window */
  14441. var DEF_WBITS = MAX_WBITS;
  14442. function ZSWAP32(q) {
  14443. return (((q >>> 24) & 0xff) +
  14444. ((q >>> 8) & 0xff00) +
  14445. ((q & 0xff00) << 8) +
  14446. ((q & 0xff) << 24));
  14447. }
  14448. function InflateState() {
  14449. this.mode = 0; /* current inflate mode */
  14450. this.last = false; /* true if processing last block */
  14451. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  14452. this.havedict = false; /* true if dictionary provided */
  14453. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  14454. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  14455. this.check = 0; /* protected copy of check value */
  14456. this.total = 0; /* protected copy of output count */
  14457. // TODO: may be {}
  14458. this.head = null; /* where to save gzip header information */
  14459. /* sliding window */
  14460. this.wbits = 0; /* log base 2 of requested window size */
  14461. this.wsize = 0; /* window size or zero if not using window */
  14462. this.whave = 0; /* valid bytes in the window */
  14463. this.wnext = 0; /* window write index */
  14464. this.window = null; /* allocated sliding window, if needed */
  14465. /* bit accumulator */
  14466. this.hold = 0; /* input bit accumulator */
  14467. this.bits = 0; /* number of bits in "in" */
  14468. /* for string and stored block copying */
  14469. this.length = 0; /* literal or length of data to copy */
  14470. this.offset = 0; /* distance back to copy string from */
  14471. /* for table and code decoding */
  14472. this.extra = 0; /* extra bits needed */
  14473. /* fixed and dynamic code tables */
  14474. this.lencode = null; /* starting table for length/literal codes */
  14475. this.distcode = null; /* starting table for distance codes */
  14476. this.lenbits = 0; /* index bits for lencode */
  14477. this.distbits = 0; /* index bits for distcode */
  14478. /* dynamic table building */
  14479. this.ncode = 0; /* number of code length code lengths */
  14480. this.nlen = 0; /* number of length code lengths */
  14481. this.ndist = 0; /* number of distance code lengths */
  14482. this.have = 0; /* number of code lengths in lens[] */
  14483. this.next = null; /* next available space in codes[] */
  14484. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  14485. this.work = new utils.Buf16(288); /* work area for code table building */
  14486. /*
  14487. because we don't have pointers in js, we use lencode and distcode directly
  14488. as buffers so we don't need codes
  14489. */
  14490. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  14491. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  14492. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  14493. this.sane = 0; /* if false, allow invalid distance too far */
  14494. this.back = 0; /* bits back of last unprocessed length/lit */
  14495. this.was = 0; /* initial length of match */
  14496. }
  14497. function inflateResetKeep(strm) {
  14498. var state;
  14499. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  14500. state = strm.state;
  14501. strm.total_in = strm.total_out = state.total = 0;
  14502. strm.msg = ''; /*Z_NULL*/
  14503. if (state.wrap) { /* to support ill-conceived Java test suite */
  14504. strm.adler = state.wrap & 1;
  14505. }
  14506. state.mode = HEAD;
  14507. state.last = 0;
  14508. state.havedict = 0;
  14509. state.dmax = 32768;
  14510. state.head = null/*Z_NULL*/;
  14511. state.hold = 0;
  14512. state.bits = 0;
  14513. //state.lencode = state.distcode = state.next = state.codes;
  14514. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  14515. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  14516. state.sane = 1;
  14517. state.back = -1;
  14518. //Tracev((stderr, "inflate: reset\n"));
  14519. return Z_OK;
  14520. }
  14521. function inflateReset(strm) {
  14522. var state;
  14523. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  14524. state = strm.state;
  14525. state.wsize = 0;
  14526. state.whave = 0;
  14527. state.wnext = 0;
  14528. return inflateResetKeep(strm);
  14529. }
  14530. function inflateReset2(strm, windowBits) {
  14531. var wrap;
  14532. var state;
  14533. /* get the state */
  14534. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  14535. state = strm.state;
  14536. /* extract wrap request from windowBits parameter */
  14537. if (windowBits < 0) {
  14538. wrap = 0;
  14539. windowBits = -windowBits;
  14540. }
  14541. else {
  14542. wrap = (windowBits >> 4) + 1;
  14543. if (windowBits < 48) {
  14544. windowBits &= 15;
  14545. }
  14546. }
  14547. /* set number of window bits, free window if different */
  14548. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  14549. return Z_STREAM_ERROR;
  14550. }
  14551. if (state.window !== null && state.wbits !== windowBits) {
  14552. state.window = null;
  14553. }
  14554. /* update state and reset the rest of it */
  14555. state.wrap = wrap;
  14556. state.wbits = windowBits;
  14557. return inflateReset(strm);
  14558. }
  14559. function inflateInit2(strm, windowBits) {
  14560. var ret;
  14561. var state;
  14562. if (!strm) { return Z_STREAM_ERROR; }
  14563. //strm.msg = Z_NULL; /* in case we return an error */
  14564. state = new InflateState();
  14565. //if (state === Z_NULL) return Z_MEM_ERROR;
  14566. //Tracev((stderr, "inflate: allocated\n"));
  14567. strm.state = state;
  14568. state.window = null/*Z_NULL*/;
  14569. ret = inflateReset2(strm, windowBits);
  14570. if (ret !== Z_OK) {
  14571. strm.state = null/*Z_NULL*/;
  14572. }
  14573. return ret;
  14574. }
  14575. function inflateInit(strm) {
  14576. return inflateInit2(strm, DEF_WBITS);
  14577. }
  14578. /*
  14579. Return state with length and distance decoding tables and index sizes set to
  14580. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  14581. If BUILDFIXED is defined, then instead this routine builds the tables the
  14582. first time it's called, and returns those tables the first time and
  14583. thereafter. This reduces the size of the code by about 2K bytes, in
  14584. exchange for a little execution time. However, BUILDFIXED should not be
  14585. used for threaded applications, since the rewriting of the tables and virgin
  14586. may not be thread-safe.
  14587. */
  14588. var virgin = true;
  14589. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  14590. function fixedtables(state) {
  14591. /* build fixed huffman tables if first call (may not be thread safe) */
  14592. if (virgin) {
  14593. var sym;
  14594. lenfix = new utils.Buf32(512);
  14595. distfix = new utils.Buf32(32);
  14596. /* literal/length table */
  14597. sym = 0;
  14598. while (sym < 144) { state.lens[sym++] = 8; }
  14599. while (sym < 256) { state.lens[sym++] = 9; }
  14600. while (sym < 280) { state.lens[sym++] = 7; }
  14601. while (sym < 288) { state.lens[sym++] = 8; }
  14602. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  14603. /* distance table */
  14604. sym = 0;
  14605. while (sym < 32) { state.lens[sym++] = 5; }
  14606. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  14607. /* do this just once */
  14608. virgin = false;
  14609. }
  14610. state.lencode = lenfix;
  14611. state.lenbits = 9;
  14612. state.distcode = distfix;
  14613. state.distbits = 5;
  14614. }
  14615. /*
  14616. Update the window with the last wsize (normally 32K) bytes written before
  14617. returning. If window does not exist yet, create it. This is only called
  14618. when a window is already in use, or when output has been written during this
  14619. inflate call, but the end of the deflate stream has not been reached yet.
  14620. It is also called to create a window for dictionary data when a dictionary
  14621. is loaded.
  14622. Providing output buffers larger than 32K to inflate() should provide a speed
  14623. advantage, since only the last 32K of output is copied to the sliding window
  14624. upon return from inflate(), and since all distances after the first 32K of
  14625. output will fall in the output data, making match copies simpler and faster.
  14626. The advantage may be dependent on the size of the processor's data caches.
  14627. */
  14628. function updatewindow(strm, src, end, copy) {
  14629. var dist;
  14630. var state = strm.state;
  14631. /* if it hasn't been done already, allocate space for the window */
  14632. if (state.window === null) {
  14633. state.wsize = 1 << state.wbits;
  14634. state.wnext = 0;
  14635. state.whave = 0;
  14636. state.window = new utils.Buf8(state.wsize);
  14637. }
  14638. /* copy state->wsize or less output bytes into the circular window */
  14639. if (copy >= state.wsize) {
  14640. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  14641. state.wnext = 0;
  14642. state.whave = state.wsize;
  14643. }
  14644. else {
  14645. dist = state.wsize - state.wnext;
  14646. if (dist > copy) {
  14647. dist = copy;
  14648. }
  14649. //zmemcpy(state->window + state->wnext, end - copy, dist);
  14650. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  14651. copy -= dist;
  14652. if (copy) {
  14653. //zmemcpy(state->window, end - copy, copy);
  14654. utils.arraySet(state.window,src, end - copy, copy, 0);
  14655. state.wnext = copy;
  14656. state.whave = state.wsize;
  14657. }
  14658. else {
  14659. state.wnext += dist;
  14660. if (state.wnext === state.wsize) { state.wnext = 0; }
  14661. if (state.whave < state.wsize) { state.whave += dist; }
  14662. }
  14663. }
  14664. return 0;
  14665. }
  14666. function inflate(strm, flush) {
  14667. var state;
  14668. var input, output; // input/output buffers
  14669. var next; /* next input INDEX */
  14670. var put; /* next output INDEX */
  14671. var have, left; /* available input and output */
  14672. var hold; /* bit buffer */
  14673. var bits; /* bits in bit buffer */
  14674. var _in, _out; /* save starting available input and output */
  14675. var copy; /* number of stored or match bytes to copy */
  14676. var from; /* where to copy match bytes from */
  14677. var from_source;
  14678. var here = 0; /* current decoding table entry */
  14679. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  14680. //var last; /* parent table entry */
  14681. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  14682. var len; /* length to copy for repeats, bits to drop */
  14683. var ret; /* return code */
  14684. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  14685. var opts;
  14686. var n; // temporary var for NEED_BITS
  14687. var order = /* permutation of code lengths */
  14688. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  14689. if (!strm || !strm.state || !strm.output ||
  14690. (!strm.input && strm.avail_in !== 0)) {
  14691. return Z_STREAM_ERROR;
  14692. }
  14693. state = strm.state;
  14694. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  14695. //--- LOAD() ---
  14696. put = strm.next_out;
  14697. output = strm.output;
  14698. left = strm.avail_out;
  14699. next = strm.next_in;
  14700. input = strm.input;
  14701. have = strm.avail_in;
  14702. hold = state.hold;
  14703. bits = state.bits;
  14704. //---
  14705. _in = have;
  14706. _out = left;
  14707. ret = Z_OK;
  14708. inf_leave: // goto emulation
  14709. for (;;) {
  14710. switch (state.mode) {
  14711. case HEAD:
  14712. if (state.wrap === 0) {
  14713. state.mode = TYPEDO;
  14714. break;
  14715. }
  14716. //=== NEEDBITS(16);
  14717. while (bits < 16) {
  14718. if (have === 0) { break inf_leave; }
  14719. have--;
  14720. hold += input[next++] << bits;
  14721. bits += 8;
  14722. }
  14723. //===//
  14724. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  14725. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  14726. //=== CRC2(state.check, hold);
  14727. hbuf[0] = hold & 0xff;
  14728. hbuf[1] = (hold >>> 8) & 0xff;
  14729. state.check = crc32(state.check, hbuf, 2, 0);
  14730. //===//
  14731. //=== INITBITS();
  14732. hold = 0;
  14733. bits = 0;
  14734. //===//
  14735. state.mode = FLAGS;
  14736. break;
  14737. }
  14738. state.flags = 0; /* expect zlib header */
  14739. if (state.head) {
  14740. state.head.done = false;
  14741. }
  14742. if (!(state.wrap & 1) || /* check if zlib header allowed */
  14743. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  14744. strm.msg = 'incorrect header check';
  14745. state.mode = BAD;
  14746. break;
  14747. }
  14748. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  14749. strm.msg = 'unknown compression method';
  14750. state.mode = BAD;
  14751. break;
  14752. }
  14753. //--- DROPBITS(4) ---//
  14754. hold >>>= 4;
  14755. bits -= 4;
  14756. //---//
  14757. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  14758. if (state.wbits === 0) {
  14759. state.wbits = len;
  14760. }
  14761. else if (len > state.wbits) {
  14762. strm.msg = 'invalid window size';
  14763. state.mode = BAD;
  14764. break;
  14765. }
  14766. state.dmax = 1 << len;
  14767. //Tracev((stderr, "inflate: zlib header ok\n"));
  14768. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  14769. state.mode = hold & 0x200 ? DICTID : TYPE;
  14770. //=== INITBITS();
  14771. hold = 0;
  14772. bits = 0;
  14773. //===//
  14774. break;
  14775. case FLAGS:
  14776. //=== NEEDBITS(16); */
  14777. while (bits < 16) {
  14778. if (have === 0) { break inf_leave; }
  14779. have--;
  14780. hold += input[next++] << bits;
  14781. bits += 8;
  14782. }
  14783. //===//
  14784. state.flags = hold;
  14785. if ((state.flags & 0xff) !== Z_DEFLATED) {
  14786. strm.msg = 'unknown compression method';
  14787. state.mode = BAD;
  14788. break;
  14789. }
  14790. if (state.flags & 0xe000) {
  14791. strm.msg = 'unknown header flags set';
  14792. state.mode = BAD;
  14793. break;
  14794. }
  14795. if (state.head) {
  14796. state.head.text = ((hold >> 8) & 1);
  14797. }
  14798. if (state.flags & 0x0200) {
  14799. //=== CRC2(state.check, hold);
  14800. hbuf[0] = hold & 0xff;
  14801. hbuf[1] = (hold >>> 8) & 0xff;
  14802. state.check = crc32(state.check, hbuf, 2, 0);
  14803. //===//
  14804. }
  14805. //=== INITBITS();
  14806. hold = 0;
  14807. bits = 0;
  14808. //===//
  14809. state.mode = TIME;
  14810. /* falls through */
  14811. case TIME:
  14812. //=== NEEDBITS(32); */
  14813. while (bits < 32) {
  14814. if (have === 0) { break inf_leave; }
  14815. have--;
  14816. hold += input[next++] << bits;
  14817. bits += 8;
  14818. }
  14819. //===//
  14820. if (state.head) {
  14821. state.head.time = hold;
  14822. }
  14823. if (state.flags & 0x0200) {
  14824. //=== CRC4(state.check, hold)
  14825. hbuf[0] = hold & 0xff;
  14826. hbuf[1] = (hold >>> 8) & 0xff;
  14827. hbuf[2] = (hold >>> 16) & 0xff;
  14828. hbuf[3] = (hold >>> 24) & 0xff;
  14829. state.check = crc32(state.check, hbuf, 4, 0);
  14830. //===
  14831. }
  14832. //=== INITBITS();
  14833. hold = 0;
  14834. bits = 0;
  14835. //===//
  14836. state.mode = OS;
  14837. /* falls through */
  14838. case OS:
  14839. //=== NEEDBITS(16); */
  14840. while (bits < 16) {
  14841. if (have === 0) { break inf_leave; }
  14842. have--;
  14843. hold += input[next++] << bits;
  14844. bits += 8;
  14845. }
  14846. //===//
  14847. if (state.head) {
  14848. state.head.xflags = (hold & 0xff);
  14849. state.head.os = (hold >> 8);
  14850. }
  14851. if (state.flags & 0x0200) {
  14852. //=== CRC2(state.check, hold);
  14853. hbuf[0] = hold & 0xff;
  14854. hbuf[1] = (hold >>> 8) & 0xff;
  14855. state.check = crc32(state.check, hbuf, 2, 0);
  14856. //===//
  14857. }
  14858. //=== INITBITS();
  14859. hold = 0;
  14860. bits = 0;
  14861. //===//
  14862. state.mode = EXLEN;
  14863. /* falls through */
  14864. case EXLEN:
  14865. if (state.flags & 0x0400) {
  14866. //=== NEEDBITS(16); */
  14867. while (bits < 16) {
  14868. if (have === 0) { break inf_leave; }
  14869. have--;
  14870. hold += input[next++] << bits;
  14871. bits += 8;
  14872. }
  14873. //===//
  14874. state.length = hold;
  14875. if (state.head) {
  14876. state.head.extra_len = hold;
  14877. }
  14878. if (state.flags & 0x0200) {
  14879. //=== CRC2(state.check, hold);
  14880. hbuf[0] = hold & 0xff;
  14881. hbuf[1] = (hold >>> 8) & 0xff;
  14882. state.check = crc32(state.check, hbuf, 2, 0);
  14883. //===//
  14884. }
  14885. //=== INITBITS();
  14886. hold = 0;
  14887. bits = 0;
  14888. //===//
  14889. }
  14890. else if (state.head) {
  14891. state.head.extra = null/*Z_NULL*/;
  14892. }
  14893. state.mode = EXTRA;
  14894. /* falls through */
  14895. case EXTRA:
  14896. if (state.flags & 0x0400) {
  14897. copy = state.length;
  14898. if (copy > have) { copy = have; }
  14899. if (copy) {
  14900. if (state.head) {
  14901. len = state.head.extra_len - state.length;
  14902. if (!state.head.extra) {
  14903. // Use untyped array for more conveniend processing later
  14904. state.head.extra = new Array(state.head.extra_len);
  14905. }
  14906. utils.arraySet(
  14907. state.head.extra,
  14908. input,
  14909. next,
  14910. // extra field is limited to 65536 bytes
  14911. // - no need for additional size check
  14912. copy,
  14913. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  14914. len
  14915. );
  14916. //zmemcpy(state.head.extra + len, next,
  14917. // len + copy > state.head.extra_max ?
  14918. // state.head.extra_max - len : copy);
  14919. }
  14920. if (state.flags & 0x0200) {
  14921. state.check = crc32(state.check, input, copy, next);
  14922. }
  14923. have -= copy;
  14924. next += copy;
  14925. state.length -= copy;
  14926. }
  14927. if (state.length) { break inf_leave; }
  14928. }
  14929. state.length = 0;
  14930. state.mode = NAME;
  14931. /* falls through */
  14932. case NAME:
  14933. if (state.flags & 0x0800) {
  14934. if (have === 0) { break inf_leave; }
  14935. copy = 0;
  14936. do {
  14937. // TODO: 2 or 1 bytes?
  14938. len = input[next + copy++];
  14939. /* use constant limit because in js we should not preallocate memory */
  14940. if (state.head && len &&
  14941. (state.length < 65536 /*state.head.name_max*/)) {
  14942. state.head.name += String.fromCharCode(len);
  14943. }
  14944. } while (len && copy < have);
  14945. if (state.flags & 0x0200) {
  14946. state.check = crc32(state.check, input, copy, next);
  14947. }
  14948. have -= copy;
  14949. next += copy;
  14950. if (len) { break inf_leave; }
  14951. }
  14952. else if (state.head) {
  14953. state.head.name = null;
  14954. }
  14955. state.length = 0;
  14956. state.mode = COMMENT;
  14957. /* falls through */
  14958. case COMMENT:
  14959. if (state.flags & 0x1000) {
  14960. if (have === 0) { break inf_leave; }
  14961. copy = 0;
  14962. do {
  14963. len = input[next + copy++];
  14964. /* use constant limit because in js we should not preallocate memory */
  14965. if (state.head && len &&
  14966. (state.length < 65536 /*state.head.comm_max*/)) {
  14967. state.head.comment += String.fromCharCode(len);
  14968. }
  14969. } while (len && copy < have);
  14970. if (state.flags & 0x0200) {
  14971. state.check = crc32(state.check, input, copy, next);
  14972. }
  14973. have -= copy;
  14974. next += copy;
  14975. if (len) { break inf_leave; }
  14976. }
  14977. else if (state.head) {
  14978. state.head.comment = null;
  14979. }
  14980. state.mode = HCRC;
  14981. /* falls through */
  14982. case HCRC:
  14983. if (state.flags & 0x0200) {
  14984. //=== NEEDBITS(16); */
  14985. while (bits < 16) {
  14986. if (have === 0) { break inf_leave; }
  14987. have--;
  14988. hold += input[next++] << bits;
  14989. bits += 8;
  14990. }
  14991. //===//
  14992. if (hold !== (state.check & 0xffff)) {
  14993. strm.msg = 'header crc mismatch';
  14994. state.mode = BAD;
  14995. break;
  14996. }
  14997. //=== INITBITS();
  14998. hold = 0;
  14999. bits = 0;
  15000. //===//
  15001. }
  15002. if (state.head) {
  15003. state.head.hcrc = ((state.flags >> 9) & 1);
  15004. state.head.done = true;
  15005. }
  15006. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  15007. state.mode = TYPE;
  15008. break;
  15009. case DICTID:
  15010. //=== NEEDBITS(32); */
  15011. while (bits < 32) {
  15012. if (have === 0) { break inf_leave; }
  15013. have--;
  15014. hold += input[next++] << bits;
  15015. bits += 8;
  15016. }
  15017. //===//
  15018. strm.adler = state.check = ZSWAP32(hold);
  15019. //=== INITBITS();
  15020. hold = 0;
  15021. bits = 0;
  15022. //===//
  15023. state.mode = DICT;
  15024. /* falls through */
  15025. case DICT:
  15026. if (state.havedict === 0) {
  15027. //--- RESTORE() ---
  15028. strm.next_out = put;
  15029. strm.avail_out = left;
  15030. strm.next_in = next;
  15031. strm.avail_in = have;
  15032. state.hold = hold;
  15033. state.bits = bits;
  15034. //---
  15035. return Z_NEED_DICT;
  15036. }
  15037. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  15038. state.mode = TYPE;
  15039. /* falls through */
  15040. case TYPE:
  15041. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  15042. /* falls through */
  15043. case TYPEDO:
  15044. if (state.last) {
  15045. //--- BYTEBITS() ---//
  15046. hold >>>= bits & 7;
  15047. bits -= bits & 7;
  15048. //---//
  15049. state.mode = CHECK;
  15050. break;
  15051. }
  15052. //=== NEEDBITS(3); */
  15053. while (bits < 3) {
  15054. if (have === 0) { break inf_leave; }
  15055. have--;
  15056. hold += input[next++] << bits;
  15057. bits += 8;
  15058. }
  15059. //===//
  15060. state.last = (hold & 0x01)/*BITS(1)*/;
  15061. //--- DROPBITS(1) ---//
  15062. hold >>>= 1;
  15063. bits -= 1;
  15064. //---//
  15065. switch ((hold & 0x03)/*BITS(2)*/) {
  15066. case 0: /* stored block */
  15067. //Tracev((stderr, "inflate: stored block%s\n",
  15068. // state.last ? " (last)" : ""));
  15069. state.mode = STORED;
  15070. break;
  15071. case 1: /* fixed block */
  15072. fixedtables(state);
  15073. //Tracev((stderr, "inflate: fixed codes block%s\n",
  15074. // state.last ? " (last)" : ""));
  15075. state.mode = LEN_; /* decode codes */
  15076. if (flush === Z_TREES) {
  15077. //--- DROPBITS(2) ---//
  15078. hold >>>= 2;
  15079. bits -= 2;
  15080. //---//
  15081. break inf_leave;
  15082. }
  15083. break;
  15084. case 2: /* dynamic block */
  15085. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  15086. // state.last ? " (last)" : ""));
  15087. state.mode = TABLE;
  15088. break;
  15089. case 3:
  15090. strm.msg = 'invalid block type';
  15091. state.mode = BAD;
  15092. }
  15093. //--- DROPBITS(2) ---//
  15094. hold >>>= 2;
  15095. bits -= 2;
  15096. //---//
  15097. break;
  15098. case STORED:
  15099. //--- BYTEBITS() ---// /* go to byte boundary */
  15100. hold >>>= bits & 7;
  15101. bits -= bits & 7;
  15102. //---//
  15103. //=== NEEDBITS(32); */
  15104. while (bits < 32) {
  15105. if (have === 0) { break inf_leave; }
  15106. have--;
  15107. hold += input[next++] << bits;
  15108. bits += 8;
  15109. }
  15110. //===//
  15111. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  15112. strm.msg = 'invalid stored block lengths';
  15113. state.mode = BAD;
  15114. break;
  15115. }
  15116. state.length = hold & 0xffff;
  15117. //Tracev((stderr, "inflate: stored length %u\n",
  15118. // state.length));
  15119. //=== INITBITS();
  15120. hold = 0;
  15121. bits = 0;
  15122. //===//
  15123. state.mode = COPY_;
  15124. if (flush === Z_TREES) { break inf_leave; }
  15125. /* falls through */
  15126. case COPY_:
  15127. state.mode = COPY;
  15128. /* falls through */
  15129. case COPY:
  15130. copy = state.length;
  15131. if (copy) {
  15132. if (copy > have) { copy = have; }
  15133. if (copy > left) { copy = left; }
  15134. if (copy === 0) { break inf_leave; }
  15135. //--- zmemcpy(put, next, copy); ---
  15136. utils.arraySet(output, input, next, copy, put);
  15137. //---//
  15138. have -= copy;
  15139. next += copy;
  15140. left -= copy;
  15141. put += copy;
  15142. state.length -= copy;
  15143. break;
  15144. }
  15145. //Tracev((stderr, "inflate: stored end\n"));
  15146. state.mode = TYPE;
  15147. break;
  15148. case TABLE:
  15149. //=== NEEDBITS(14); */
  15150. while (bits < 14) {
  15151. if (have === 0) { break inf_leave; }
  15152. have--;
  15153. hold += input[next++] << bits;
  15154. bits += 8;
  15155. }
  15156. //===//
  15157. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  15158. //--- DROPBITS(5) ---//
  15159. hold >>>= 5;
  15160. bits -= 5;
  15161. //---//
  15162. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  15163. //--- DROPBITS(5) ---//
  15164. hold >>>= 5;
  15165. bits -= 5;
  15166. //---//
  15167. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  15168. //--- DROPBITS(4) ---//
  15169. hold >>>= 4;
  15170. bits -= 4;
  15171. //---//
  15172. //#ifndef PKZIP_BUG_WORKAROUND
  15173. if (state.nlen > 286 || state.ndist > 30) {
  15174. strm.msg = 'too many length or distance symbols';
  15175. state.mode = BAD;
  15176. break;
  15177. }
  15178. //#endif
  15179. //Tracev((stderr, "inflate: table sizes ok\n"));
  15180. state.have = 0;
  15181. state.mode = LENLENS;
  15182. /* falls through */
  15183. case LENLENS:
  15184. while (state.have < state.ncode) {
  15185. //=== NEEDBITS(3);
  15186. while (bits < 3) {
  15187. if (have === 0) { break inf_leave; }
  15188. have--;
  15189. hold += input[next++] << bits;
  15190. bits += 8;
  15191. }
  15192. //===//
  15193. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  15194. //--- DROPBITS(3) ---//
  15195. hold >>>= 3;
  15196. bits -= 3;
  15197. //---//
  15198. }
  15199. while (state.have < 19) {
  15200. state.lens[order[state.have++]] = 0;
  15201. }
  15202. // We have separate tables & no pointers. 2 commented lines below not needed.
  15203. //state.next = state.codes;
  15204. //state.lencode = state.next;
  15205. // Switch to use dynamic table
  15206. state.lencode = state.lendyn;
  15207. state.lenbits = 7;
  15208. opts = {bits: state.lenbits};
  15209. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  15210. state.lenbits = opts.bits;
  15211. if (ret) {
  15212. strm.msg = 'invalid code lengths set';
  15213. state.mode = BAD;
  15214. break;
  15215. }
  15216. //Tracev((stderr, "inflate: code lengths ok\n"));
  15217. state.have = 0;
  15218. state.mode = CODELENS;
  15219. /* falls through */
  15220. case CODELENS:
  15221. while (state.have < state.nlen + state.ndist) {
  15222. for (;;) {
  15223. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  15224. here_bits = here >>> 24;
  15225. here_op = (here >>> 16) & 0xff;
  15226. here_val = here & 0xffff;
  15227. if ((here_bits) <= bits) { break; }
  15228. //--- PULLBYTE() ---//
  15229. if (have === 0) { break inf_leave; }
  15230. have--;
  15231. hold += input[next++] << bits;
  15232. bits += 8;
  15233. //---//
  15234. }
  15235. if (here_val < 16) {
  15236. //--- DROPBITS(here.bits) ---//
  15237. hold >>>= here_bits;
  15238. bits -= here_bits;
  15239. //---//
  15240. state.lens[state.have++] = here_val;
  15241. }
  15242. else {
  15243. if (here_val === 16) {
  15244. //=== NEEDBITS(here.bits + 2);
  15245. n = here_bits + 2;
  15246. while (bits < n) {
  15247. if (have === 0) { break inf_leave; }
  15248. have--;
  15249. hold += input[next++] << bits;
  15250. bits += 8;
  15251. }
  15252. //===//
  15253. //--- DROPBITS(here.bits) ---//
  15254. hold >>>= here_bits;
  15255. bits -= here_bits;
  15256. //---//
  15257. if (state.have === 0) {
  15258. strm.msg = 'invalid bit length repeat';
  15259. state.mode = BAD;
  15260. break;
  15261. }
  15262. len = state.lens[state.have - 1];
  15263. copy = 3 + (hold & 0x03);//BITS(2);
  15264. //--- DROPBITS(2) ---//
  15265. hold >>>= 2;
  15266. bits -= 2;
  15267. //---//
  15268. }
  15269. else if (here_val === 17) {
  15270. //=== NEEDBITS(here.bits + 3);
  15271. n = here_bits + 3;
  15272. while (bits < n) {
  15273. if (have === 0) { break inf_leave; }
  15274. have--;
  15275. hold += input[next++] << bits;
  15276. bits += 8;
  15277. }
  15278. //===//
  15279. //--- DROPBITS(here.bits) ---//
  15280. hold >>>= here_bits;
  15281. bits -= here_bits;
  15282. //---//
  15283. len = 0;
  15284. copy = 3 + (hold & 0x07);//BITS(3);
  15285. //--- DROPBITS(3) ---//
  15286. hold >>>= 3;
  15287. bits -= 3;
  15288. //---//
  15289. }
  15290. else {
  15291. //=== NEEDBITS(here.bits + 7);
  15292. n = here_bits + 7;
  15293. while (bits < n) {
  15294. if (have === 0) { break inf_leave; }
  15295. have--;
  15296. hold += input[next++] << bits;
  15297. bits += 8;
  15298. }
  15299. //===//
  15300. //--- DROPBITS(here.bits) ---//
  15301. hold >>>= here_bits;
  15302. bits -= here_bits;
  15303. //---//
  15304. len = 0;
  15305. copy = 11 + (hold & 0x7f);//BITS(7);
  15306. //--- DROPBITS(7) ---//
  15307. hold >>>= 7;
  15308. bits -= 7;
  15309. //---//
  15310. }
  15311. if (state.have + copy > state.nlen + state.ndist) {
  15312. strm.msg = 'invalid bit length repeat';
  15313. state.mode = BAD;
  15314. break;
  15315. }
  15316. while (copy--) {
  15317. state.lens[state.have++] = len;
  15318. }
  15319. }
  15320. }
  15321. /* handle error breaks in while */
  15322. if (state.mode === BAD) { break; }
  15323. /* check for end-of-block code (better have one) */
  15324. if (state.lens[256] === 0) {
  15325. strm.msg = 'invalid code -- missing end-of-block';
  15326. state.mode = BAD;
  15327. break;
  15328. }
  15329. /* build code tables -- note: do not change the lenbits or distbits
  15330. values here (9 and 6) without reading the comments in inftrees.h
  15331. concerning the ENOUGH constants, which depend on those values */
  15332. state.lenbits = 9;
  15333. opts = {bits: state.lenbits};
  15334. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  15335. // We have separate tables & no pointers. 2 commented lines below not needed.
  15336. // state.next_index = opts.table_index;
  15337. state.lenbits = opts.bits;
  15338. // state.lencode = state.next;
  15339. if (ret) {
  15340. strm.msg = 'invalid literal/lengths set';
  15341. state.mode = BAD;
  15342. break;
  15343. }
  15344. state.distbits = 6;
  15345. //state.distcode.copy(state.codes);
  15346. // Switch to use dynamic table
  15347. state.distcode = state.distdyn;
  15348. opts = {bits: state.distbits};
  15349. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  15350. // We have separate tables & no pointers. 2 commented lines below not needed.
  15351. // state.next_index = opts.table_index;
  15352. state.distbits = opts.bits;
  15353. // state.distcode = state.next;
  15354. if (ret) {
  15355. strm.msg = 'invalid distances set';
  15356. state.mode = BAD;
  15357. break;
  15358. }
  15359. //Tracev((stderr, 'inflate: codes ok\n'));
  15360. state.mode = LEN_;
  15361. if (flush === Z_TREES) { break inf_leave; }
  15362. /* falls through */
  15363. case LEN_:
  15364. state.mode = LEN;
  15365. /* falls through */
  15366. case LEN:
  15367. if (have >= 6 && left >= 258) {
  15368. //--- RESTORE() ---
  15369. strm.next_out = put;
  15370. strm.avail_out = left;
  15371. strm.next_in = next;
  15372. strm.avail_in = have;
  15373. state.hold = hold;
  15374. state.bits = bits;
  15375. //---
  15376. inflate_fast(strm, _out);
  15377. //--- LOAD() ---
  15378. put = strm.next_out;
  15379. output = strm.output;
  15380. left = strm.avail_out;
  15381. next = strm.next_in;
  15382. input = strm.input;
  15383. have = strm.avail_in;
  15384. hold = state.hold;
  15385. bits = state.bits;
  15386. //---
  15387. if (state.mode === TYPE) {
  15388. state.back = -1;
  15389. }
  15390. break;
  15391. }
  15392. state.back = 0;
  15393. for (;;) {
  15394. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  15395. here_bits = here >>> 24;
  15396. here_op = (here >>> 16) & 0xff;
  15397. here_val = here & 0xffff;
  15398. if (here_bits <= bits) { break; }
  15399. //--- PULLBYTE() ---//
  15400. if (have === 0) { break inf_leave; }
  15401. have--;
  15402. hold += input[next++] << bits;
  15403. bits += 8;
  15404. //---//
  15405. }
  15406. if (here_op && (here_op & 0xf0) === 0) {
  15407. last_bits = here_bits;
  15408. last_op = here_op;
  15409. last_val = here_val;
  15410. for (;;) {
  15411. here = state.lencode[last_val +
  15412. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  15413. here_bits = here >>> 24;
  15414. here_op = (here >>> 16) & 0xff;
  15415. here_val = here & 0xffff;
  15416. if ((last_bits + here_bits) <= bits) { break; }
  15417. //--- PULLBYTE() ---//
  15418. if (have === 0) { break inf_leave; }
  15419. have--;
  15420. hold += input[next++] << bits;
  15421. bits += 8;
  15422. //---//
  15423. }
  15424. //--- DROPBITS(last.bits) ---//
  15425. hold >>>= last_bits;
  15426. bits -= last_bits;
  15427. //---//
  15428. state.back += last_bits;
  15429. }
  15430. //--- DROPBITS(here.bits) ---//
  15431. hold >>>= here_bits;
  15432. bits -= here_bits;
  15433. //---//
  15434. state.back += here_bits;
  15435. state.length = here_val;
  15436. if (here_op === 0) {
  15437. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  15438. // "inflate: literal '%c'\n" :
  15439. // "inflate: literal 0x%02x\n", here.val));
  15440. state.mode = LIT;
  15441. break;
  15442. }
  15443. if (here_op & 32) {
  15444. //Tracevv((stderr, "inflate: end of block\n"));
  15445. state.back = -1;
  15446. state.mode = TYPE;
  15447. break;
  15448. }
  15449. if (here_op & 64) {
  15450. strm.msg = 'invalid literal/length code';
  15451. state.mode = BAD;
  15452. break;
  15453. }
  15454. state.extra = here_op & 15;
  15455. state.mode = LENEXT;
  15456. /* falls through */
  15457. case LENEXT:
  15458. if (state.extra) {
  15459. //=== NEEDBITS(state.extra);
  15460. n = state.extra;
  15461. while (bits < n) {
  15462. if (have === 0) { break inf_leave; }
  15463. have--;
  15464. hold += input[next++] << bits;
  15465. bits += 8;
  15466. }
  15467. //===//
  15468. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  15469. //--- DROPBITS(state.extra) ---//
  15470. hold >>>= state.extra;
  15471. bits -= state.extra;
  15472. //---//
  15473. state.back += state.extra;
  15474. }
  15475. //Tracevv((stderr, "inflate: length %u\n", state.length));
  15476. state.was = state.length;
  15477. state.mode = DIST;
  15478. /* falls through */
  15479. case DIST:
  15480. for (;;) {
  15481. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  15482. here_bits = here >>> 24;
  15483. here_op = (here >>> 16) & 0xff;
  15484. here_val = here & 0xffff;
  15485. if ((here_bits) <= bits) { break; }
  15486. //--- PULLBYTE() ---//
  15487. if (have === 0) { break inf_leave; }
  15488. have--;
  15489. hold += input[next++] << bits;
  15490. bits += 8;
  15491. //---//
  15492. }
  15493. if ((here_op & 0xf0) === 0) {
  15494. last_bits = here_bits;
  15495. last_op = here_op;
  15496. last_val = here_val;
  15497. for (;;) {
  15498. here = state.distcode[last_val +
  15499. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  15500. here_bits = here >>> 24;
  15501. here_op = (here >>> 16) & 0xff;
  15502. here_val = here & 0xffff;
  15503. if ((last_bits + here_bits) <= bits) { break; }
  15504. //--- PULLBYTE() ---//
  15505. if (have === 0) { break inf_leave; }
  15506. have--;
  15507. hold += input[next++] << bits;
  15508. bits += 8;
  15509. //---//
  15510. }
  15511. //--- DROPBITS(last.bits) ---//
  15512. hold >>>= last_bits;
  15513. bits -= last_bits;
  15514. //---//
  15515. state.back += last_bits;
  15516. }
  15517. //--- DROPBITS(here.bits) ---//
  15518. hold >>>= here_bits;
  15519. bits -= here_bits;
  15520. //---//
  15521. state.back += here_bits;
  15522. if (here_op & 64) {
  15523. strm.msg = 'invalid distance code';
  15524. state.mode = BAD;
  15525. break;
  15526. }
  15527. state.offset = here_val;
  15528. state.extra = (here_op) & 15;
  15529. state.mode = DISTEXT;
  15530. /* falls through */
  15531. case DISTEXT:
  15532. if (state.extra) {
  15533. //=== NEEDBITS(state.extra);
  15534. n = state.extra;
  15535. while (bits < n) {
  15536. if (have === 0) { break inf_leave; }
  15537. have--;
  15538. hold += input[next++] << bits;
  15539. bits += 8;
  15540. }
  15541. //===//
  15542. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  15543. //--- DROPBITS(state.extra) ---//
  15544. hold >>>= state.extra;
  15545. bits -= state.extra;
  15546. //---//
  15547. state.back += state.extra;
  15548. }
  15549. //#ifdef INFLATE_STRICT
  15550. if (state.offset > state.dmax) {
  15551. strm.msg = 'invalid distance too far back';
  15552. state.mode = BAD;
  15553. break;
  15554. }
  15555. //#endif
  15556. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  15557. state.mode = MATCH;
  15558. /* falls through */
  15559. case MATCH:
  15560. if (left === 0) { break inf_leave; }
  15561. copy = _out - left;
  15562. if (state.offset > copy) { /* copy from window */
  15563. copy = state.offset - copy;
  15564. if (copy > state.whave) {
  15565. if (state.sane) {
  15566. strm.msg = 'invalid distance too far back';
  15567. state.mode = BAD;
  15568. break;
  15569. }
  15570. // (!) This block is disabled in zlib defailts,
  15571. // don't enable it for binary compatibility
  15572. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  15573. // Trace((stderr, "inflate.c too far\n"));
  15574. // copy -= state.whave;
  15575. // if (copy > state.length) { copy = state.length; }
  15576. // if (copy > left) { copy = left; }
  15577. // left -= copy;
  15578. // state.length -= copy;
  15579. // do {
  15580. // output[put++] = 0;
  15581. // } while (--copy);
  15582. // if (state.length === 0) { state.mode = LEN; }
  15583. // break;
  15584. //#endif
  15585. }
  15586. if (copy > state.wnext) {
  15587. copy -= state.wnext;
  15588. from = state.wsize - copy;
  15589. }
  15590. else {
  15591. from = state.wnext - copy;
  15592. }
  15593. if (copy > state.length) { copy = state.length; }
  15594. from_source = state.window;
  15595. }
  15596. else { /* copy from output */
  15597. from_source = output;
  15598. from = put - state.offset;
  15599. copy = state.length;
  15600. }
  15601. if (copy > left) { copy = left; }
  15602. left -= copy;
  15603. state.length -= copy;
  15604. do {
  15605. output[put++] = from_source[from++];
  15606. } while (--copy);
  15607. if (state.length === 0) { state.mode = LEN; }
  15608. break;
  15609. case LIT:
  15610. if (left === 0) { break inf_leave; }
  15611. output[put++] = state.length;
  15612. left--;
  15613. state.mode = LEN;
  15614. break;
  15615. case CHECK:
  15616. if (state.wrap) {
  15617. //=== NEEDBITS(32);
  15618. while (bits < 32) {
  15619. if (have === 0) { break inf_leave; }
  15620. have--;
  15621. // Use '|' insdead of '+' to make sure that result is signed
  15622. hold |= input[next++] << bits;
  15623. bits += 8;
  15624. }
  15625. //===//
  15626. _out -= left;
  15627. strm.total_out += _out;
  15628. state.total += _out;
  15629. if (_out) {
  15630. strm.adler = state.check =
  15631. /*UPDATE(state.check, put - _out, _out);*/
  15632. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  15633. }
  15634. _out = left;
  15635. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  15636. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  15637. strm.msg = 'incorrect data check';
  15638. state.mode = BAD;
  15639. break;
  15640. }
  15641. //=== INITBITS();
  15642. hold = 0;
  15643. bits = 0;
  15644. //===//
  15645. //Tracev((stderr, "inflate: check matches trailer\n"));
  15646. }
  15647. state.mode = LENGTH;
  15648. /* falls through */
  15649. case LENGTH:
  15650. if (state.wrap && state.flags) {
  15651. //=== NEEDBITS(32);
  15652. while (bits < 32) {
  15653. if (have === 0) { break inf_leave; }
  15654. have--;
  15655. hold += input[next++] << bits;
  15656. bits += 8;
  15657. }
  15658. //===//
  15659. if (hold !== (state.total & 0xffffffff)) {
  15660. strm.msg = 'incorrect length check';
  15661. state.mode = BAD;
  15662. break;
  15663. }
  15664. //=== INITBITS();
  15665. hold = 0;
  15666. bits = 0;
  15667. //===//
  15668. //Tracev((stderr, "inflate: length matches trailer\n"));
  15669. }
  15670. state.mode = DONE;
  15671. /* falls through */
  15672. case DONE:
  15673. ret = Z_STREAM_END;
  15674. break inf_leave;
  15675. case BAD:
  15676. ret = Z_DATA_ERROR;
  15677. break inf_leave;
  15678. case MEM:
  15679. return Z_MEM_ERROR;
  15680. case SYNC:
  15681. /* falls through */
  15682. default:
  15683. return Z_STREAM_ERROR;
  15684. }
  15685. }
  15686. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  15687. /*
  15688. Return from inflate(), updating the total counts and the check value.
  15689. If there was no progress during the inflate() call, return a buffer
  15690. error. Call updatewindow() to create and/or update the window state.
  15691. Note: a memory error from inflate() is non-recoverable.
  15692. */
  15693. //--- RESTORE() ---
  15694. strm.next_out = put;
  15695. strm.avail_out = left;
  15696. strm.next_in = next;
  15697. strm.avail_in = have;
  15698. state.hold = hold;
  15699. state.bits = bits;
  15700. //---
  15701. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  15702. (state.mode < CHECK || flush !== Z_FINISH))) {
  15703. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  15704. state.mode = MEM;
  15705. return Z_MEM_ERROR;
  15706. }
  15707. }
  15708. _in -= strm.avail_in;
  15709. _out -= strm.avail_out;
  15710. strm.total_in += _in;
  15711. strm.total_out += _out;
  15712. state.total += _out;
  15713. if (state.wrap && _out) {
  15714. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  15715. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  15716. }
  15717. strm.data_type = state.bits + (state.last ? 64 : 0) +
  15718. (state.mode === TYPE ? 128 : 0) +
  15719. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  15720. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  15721. ret = Z_BUF_ERROR;
  15722. }
  15723. return ret;
  15724. }
  15725. function inflateEnd(strm) {
  15726. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  15727. return Z_STREAM_ERROR;
  15728. }
  15729. var state = strm.state;
  15730. if (state.window) {
  15731. state.window = null;
  15732. }
  15733. strm.state = null;
  15734. return Z_OK;
  15735. }
  15736. function inflateGetHeader(strm, head) {
  15737. var state;
  15738. /* check state */
  15739. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15740. state = strm.state;
  15741. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  15742. /* save header structure */
  15743. state.head = head;
  15744. head.done = false;
  15745. return Z_OK;
  15746. }
  15747. exports.inflateReset = inflateReset;
  15748. exports.inflateReset2 = inflateReset2;
  15749. exports.inflateResetKeep = inflateResetKeep;
  15750. exports.inflateInit = inflateInit;
  15751. exports.inflateInit2 = inflateInit2;
  15752. exports.inflate = inflate;
  15753. exports.inflateEnd = inflateEnd;
  15754. exports.inflateGetHeader = inflateGetHeader;
  15755. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  15756. /* Not implemented
  15757. exports.inflateCopy = inflateCopy;
  15758. exports.inflateGetDictionary = inflateGetDictionary;
  15759. exports.inflateMark = inflateMark;
  15760. exports.inflatePrime = inflatePrime;
  15761. exports.inflateSetDictionary = inflateSetDictionary;
  15762. exports.inflateSync = inflateSync;
  15763. exports.inflateSyncPoint = inflateSyncPoint;
  15764. exports.inflateUndermine = inflateUndermine;
  15765. */
  15766. },{"../utils/common":45,"./adler32":47,"./crc32":49,"./inffast":52,"./inftrees":54}],54:[function(require,module,exports){
  15767. 'use strict';
  15768. var utils = require('../utils/common');
  15769. var MAXBITS = 15;
  15770. var ENOUGH_LENS = 852;
  15771. var ENOUGH_DISTS = 592;
  15772. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  15773. var CODES = 0;
  15774. var LENS = 1;
  15775. var DISTS = 2;
  15776. var lbase = [ /* Length codes 257..285 base */
  15777. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  15778. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  15779. ];
  15780. var lext = [ /* Length codes 257..285 extra */
  15781. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  15782. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  15783. ];
  15784. var dbase = [ /* Distance codes 0..29 base */
  15785. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  15786. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  15787. 8193, 12289, 16385, 24577, 0, 0
  15788. ];
  15789. var dext = [ /* Distance codes 0..29 extra */
  15790. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  15791. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  15792. 28, 28, 29, 29, 64, 64
  15793. ];
  15794. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  15795. {
  15796. var bits = opts.bits;
  15797. //here = opts.here; /* table entry for duplication */
  15798. var len = 0; /* a code's length in bits */
  15799. var sym = 0; /* index of code symbols */
  15800. var min = 0, max = 0; /* minimum and maximum code lengths */
  15801. var root = 0; /* number of index bits for root table */
  15802. var curr = 0; /* number of index bits for current table */
  15803. var drop = 0; /* code bits to drop for sub-table */
  15804. var left = 0; /* number of prefix codes available */
  15805. var used = 0; /* code entries in table used */
  15806. var huff = 0; /* Huffman code */
  15807. var incr; /* for incrementing code, index */
  15808. var fill; /* index for replicating entries */
  15809. var low; /* low bits for current root entry */
  15810. var mask; /* mask for low root bits */
  15811. var next; /* next available space in table */
  15812. var base = null; /* base value table to use */
  15813. var base_index = 0;
  15814. // var shoextra; /* extra bits table to use */
  15815. var end; /* use base and extra for symbol > end */
  15816. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  15817. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  15818. var extra = null;
  15819. var extra_index = 0;
  15820. var here_bits, here_op, here_val;
  15821. /*
  15822. Process a set of code lengths to create a canonical Huffman code. The
  15823. code lengths are lens[0..codes-1]. Each length corresponds to the
  15824. symbols 0..codes-1. The Huffman code is generated by first sorting the
  15825. symbols by length from short to long, and retaining the symbol order
  15826. for codes with equal lengths. Then the code starts with all zero bits
  15827. for the first code of the shortest length, and the codes are integer
  15828. increments for the same length, and zeros are appended as the length
  15829. increases. For the deflate format, these bits are stored backwards
  15830. from their more natural integer increment ordering, and so when the
  15831. decoding tables are built in the large loop below, the integer codes
  15832. are incremented backwards.
  15833. This routine assumes, but does not check, that all of the entries in
  15834. lens[] are in the range 0..MAXBITS. The caller must assure this.
  15835. 1..MAXBITS is interpreted as that code length. zero means that that
  15836. symbol does not occur in this code.
  15837. The codes are sorted by computing a count of codes for each length,
  15838. creating from that a table of starting indices for each length in the
  15839. sorted table, and then entering the symbols in order in the sorted
  15840. table. The sorted table is work[], with that space being provided by
  15841. the caller.
  15842. The length counts are used for other purposes as well, i.e. finding
  15843. the minimum and maximum length codes, determining if there are any
  15844. codes at all, checking for a valid set of lengths, and looking ahead
  15845. at length counts to determine sub-table sizes when building the
  15846. decoding tables.
  15847. */
  15848. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  15849. for (len = 0; len <= MAXBITS; len++) {
  15850. count[len] = 0;
  15851. }
  15852. for (sym = 0; sym < codes; sym++) {
  15853. count[lens[lens_index + sym]]++;
  15854. }
  15855. /* bound code lengths, force root to be within code lengths */
  15856. root = bits;
  15857. for (max = MAXBITS; max >= 1; max--) {
  15858. if (count[max] !== 0) { break; }
  15859. }
  15860. if (root > max) {
  15861. root = max;
  15862. }
  15863. if (max === 0) { /* no symbols to code at all */
  15864. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  15865. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  15866. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  15867. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  15868. //table.op[opts.table_index] = 64;
  15869. //table.bits[opts.table_index] = 1;
  15870. //table.val[opts.table_index++] = 0;
  15871. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  15872. opts.bits = 1;
  15873. return 0; /* no symbols, but wait for decoding to report error */
  15874. }
  15875. for (min = 1; min < max; min++) {
  15876. if (count[min] !== 0) { break; }
  15877. }
  15878. if (root < min) {
  15879. root = min;
  15880. }
  15881. /* check for an over-subscribed or incomplete set of lengths */
  15882. left = 1;
  15883. for (len = 1; len <= MAXBITS; len++) {
  15884. left <<= 1;
  15885. left -= count[len];
  15886. if (left < 0) {
  15887. return -1;
  15888. } /* over-subscribed */
  15889. }
  15890. if (left > 0 && (type === CODES || max !== 1)) {
  15891. return -1; /* incomplete set */
  15892. }
  15893. /* generate offsets into symbol table for each length for sorting */
  15894. offs[1] = 0;
  15895. for (len = 1; len < MAXBITS; len++) {
  15896. offs[len + 1] = offs[len] + count[len];
  15897. }
  15898. /* sort symbols by length, by symbol order within each length */
  15899. for (sym = 0; sym < codes; sym++) {
  15900. if (lens[lens_index + sym] !== 0) {
  15901. work[offs[lens[lens_index + sym]]++] = sym;
  15902. }
  15903. }
  15904. /*
  15905. Create and fill in decoding tables. In this loop, the table being
  15906. filled is at next and has curr index bits. The code being used is huff
  15907. with length len. That code is converted to an index by dropping drop
  15908. bits off of the bottom. For codes where len is less than drop + curr,
  15909. those top drop + curr - len bits are incremented through all values to
  15910. fill the table with replicated entries.
  15911. root is the number of index bits for the root table. When len exceeds
  15912. root, sub-tables are created pointed to by the root entry with an index
  15913. of the low root bits of huff. This is saved in low to check for when a
  15914. new sub-table should be started. drop is zero when the root table is
  15915. being filled, and drop is root when sub-tables are being filled.
  15916. When a new sub-table is needed, it is necessary to look ahead in the
  15917. code lengths to determine what size sub-table is needed. The length
  15918. counts are used for this, and so count[] is decremented as codes are
  15919. entered in the tables.
  15920. used keeps track of how many table entries have been allocated from the
  15921. provided *table space. It is checked for LENS and DIST tables against
  15922. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  15923. the initial root table size constants. See the comments in inftrees.h
  15924. for more information.
  15925. sym increments through all symbols, and the loop terminates when
  15926. all codes of length max, i.e. all codes, have been processed. This
  15927. routine permits incomplete codes, so another loop after this one fills
  15928. in the rest of the decoding tables with invalid code markers.
  15929. */
  15930. /* set up for code type */
  15931. // poor man optimization - use if-else instead of switch,
  15932. // to avoid deopts in old v8
  15933. if (type === CODES) {
  15934. base = extra = work; /* dummy value--not used */
  15935. end = 19;
  15936. } else if (type === LENS) {
  15937. base = lbase;
  15938. base_index -= 257;
  15939. extra = lext;
  15940. extra_index -= 257;
  15941. end = 256;
  15942. } else { /* DISTS */
  15943. base = dbase;
  15944. extra = dext;
  15945. end = -1;
  15946. }
  15947. /* initialize opts for loop */
  15948. huff = 0; /* starting code */
  15949. sym = 0; /* starting code symbol */
  15950. len = min; /* starting code length */
  15951. next = table_index; /* current table to fill in */
  15952. curr = root; /* current table index bits */
  15953. drop = 0; /* current bits to drop from code for index */
  15954. low = -1; /* trigger new sub-table when len > root */
  15955. used = 1 << root; /* use root table entries */
  15956. mask = used - 1; /* mask for comparing low */
  15957. /* check available table space */
  15958. if ((type === LENS && used > ENOUGH_LENS) ||
  15959. (type === DISTS && used > ENOUGH_DISTS)) {
  15960. return 1;
  15961. }
  15962. var i=0;
  15963. /* process all codes and make table entries */
  15964. for (;;) {
  15965. i++;
  15966. /* create table entry */
  15967. here_bits = len - drop;
  15968. if (work[sym] < end) {
  15969. here_op = 0;
  15970. here_val = work[sym];
  15971. }
  15972. else if (work[sym] > end) {
  15973. here_op = extra[extra_index + work[sym]];
  15974. here_val = base[base_index + work[sym]];
  15975. }
  15976. else {
  15977. here_op = 32 + 64; /* end of block */
  15978. here_val = 0;
  15979. }
  15980. /* replicate for those indices with low len bits equal to huff */
  15981. incr = 1 << (len - drop);
  15982. fill = 1 << curr;
  15983. min = fill; /* save offset to next table */
  15984. do {
  15985. fill -= incr;
  15986. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  15987. } while (fill !== 0);
  15988. /* backwards increment the len-bit code huff */
  15989. incr = 1 << (len - 1);
  15990. while (huff & incr) {
  15991. incr >>= 1;
  15992. }
  15993. if (incr !== 0) {
  15994. huff &= incr - 1;
  15995. huff += incr;
  15996. } else {
  15997. huff = 0;
  15998. }
  15999. /* go to next symbol, update count, len */
  16000. sym++;
  16001. if (--count[len] === 0) {
  16002. if (len === max) { break; }
  16003. len = lens[lens_index + work[sym]];
  16004. }
  16005. /* create new sub-table if needed */
  16006. if (len > root && (huff & mask) !== low) {
  16007. /* if first time, transition to sub-tables */
  16008. if (drop === 0) {
  16009. drop = root;
  16010. }
  16011. /* increment past last table */
  16012. next += min; /* here min is 1 << curr */
  16013. /* determine length of next table */
  16014. curr = len - drop;
  16015. left = 1 << curr;
  16016. while (curr + drop < max) {
  16017. left -= count[curr + drop];
  16018. if (left <= 0) { break; }
  16019. curr++;
  16020. left <<= 1;
  16021. }
  16022. /* check for enough space */
  16023. used += 1 << curr;
  16024. if ((type === LENS && used > ENOUGH_LENS) ||
  16025. (type === DISTS && used > ENOUGH_DISTS)) {
  16026. return 1;
  16027. }
  16028. /* point entry in root table to sub-table */
  16029. low = huff & mask;
  16030. /*table.op[low] = curr;
  16031. table.bits[low] = root;
  16032. table.val[low] = next - opts.table_index;*/
  16033. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  16034. }
  16035. }
  16036. /* fill in remaining table entry if code is incomplete (guaranteed to have
  16037. at most one remaining entry, since if the code is incomplete, the
  16038. maximum code length that was allowed to get this far is one bit) */
  16039. if (huff !== 0) {
  16040. //table.op[next + huff] = 64; /* invalid code marker */
  16041. //table.bits[next + huff] = len - drop;
  16042. //table.val[next + huff] = 0;
  16043. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  16044. }
  16045. /* set return parameters */
  16046. //opts.table_index += used;
  16047. opts.bits = root;
  16048. return 0;
  16049. };
  16050. },{"../utils/common":45}],55:[function(require,module,exports){
  16051. 'use strict';
  16052. module.exports = {
  16053. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  16054. '1': 'stream end', /* Z_STREAM_END 1 */
  16055. '0': '', /* Z_OK 0 */
  16056. '-1': 'file error', /* Z_ERRNO (-1) */
  16057. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  16058. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  16059. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  16060. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  16061. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  16062. };
  16063. },{}],56:[function(require,module,exports){
  16064. 'use strict';
  16065. var utils = require('../utils/common');
  16066. /* Public constants ==========================================================*/
  16067. /* ===========================================================================*/
  16068. //var Z_FILTERED = 1;
  16069. //var Z_HUFFMAN_ONLY = 2;
  16070. //var Z_RLE = 3;
  16071. var Z_FIXED = 4;
  16072. //var Z_DEFAULT_STRATEGY = 0;
  16073. /* Possible values of the data_type field (though see inflate()) */
  16074. var Z_BINARY = 0;
  16075. var Z_TEXT = 1;
  16076. //var Z_ASCII = 1; // = Z_TEXT
  16077. var Z_UNKNOWN = 2;
  16078. /*============================================================================*/
  16079. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  16080. // From zutil.h
  16081. var STORED_BLOCK = 0;
  16082. var STATIC_TREES = 1;
  16083. var DYN_TREES = 2;
  16084. /* The three kinds of block type */
  16085. var MIN_MATCH = 3;
  16086. var MAX_MATCH = 258;
  16087. /* The minimum and maximum match lengths */
  16088. // From deflate.h
  16089. /* ===========================================================================
  16090. * Internal compression state.
  16091. */
  16092. var LENGTH_CODES = 29;
  16093. /* number of length codes, not counting the special END_BLOCK code */
  16094. var LITERALS = 256;
  16095. /* number of literal bytes 0..255 */
  16096. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  16097. /* number of Literal or Length codes, including the END_BLOCK code */
  16098. var D_CODES = 30;
  16099. /* number of distance codes */
  16100. var BL_CODES = 19;
  16101. /* number of codes used to transfer the bit lengths */
  16102. var HEAP_SIZE = 2*L_CODES + 1;
  16103. /* maximum heap size */
  16104. var MAX_BITS = 15;
  16105. /* All codes must not exceed MAX_BITS bits */
  16106. var Buf_size = 16;
  16107. /* size of bit buffer in bi_buf */
  16108. /* ===========================================================================
  16109. * Constants
  16110. */
  16111. var MAX_BL_BITS = 7;
  16112. /* Bit length codes must not exceed MAX_BL_BITS bits */
  16113. var END_BLOCK = 256;
  16114. /* end of block literal code */
  16115. var REP_3_6 = 16;
  16116. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  16117. var REPZ_3_10 = 17;
  16118. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  16119. var REPZ_11_138 = 18;
  16120. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  16121. var extra_lbits = /* extra bits for each length code */
  16122. [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];
  16123. var extra_dbits = /* extra bits for each distance code */
  16124. [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];
  16125. var extra_blbits = /* extra bits for each bit length code */
  16126. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  16127. var bl_order =
  16128. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  16129. /* The lengths of the bit length codes are sent in order of decreasing
  16130. * probability, to avoid transmitting the lengths for unused bit length codes.
  16131. */
  16132. /* ===========================================================================
  16133. * Local data. These are initialized only once.
  16134. */
  16135. // We pre-fill arrays with 0 to avoid uninitialized gaps
  16136. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  16137. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  16138. var static_ltree = new Array((L_CODES+2) * 2);
  16139. zero(static_ltree);
  16140. /* The static literal tree. Since the bit lengths are imposed, there is no
  16141. * need for the L_CODES extra codes used during heap construction. However
  16142. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  16143. * below).
  16144. */
  16145. var static_dtree = new Array(D_CODES * 2);
  16146. zero(static_dtree);
  16147. /* The static distance tree. (Actually a trivial tree since all codes use
  16148. * 5 bits.)
  16149. */
  16150. var _dist_code = new Array(DIST_CODE_LEN);
  16151. zero(_dist_code);
  16152. /* Distance codes. The first 256 values correspond to the distances
  16153. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  16154. * the 15 bit distances.
  16155. */
  16156. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  16157. zero(_length_code);
  16158. /* length code for each normalized match length (0 == MIN_MATCH) */
  16159. var base_length = new Array(LENGTH_CODES);
  16160. zero(base_length);
  16161. /* First normalized length for each code (0 = MIN_MATCH) */
  16162. var base_dist = new Array(D_CODES);
  16163. zero(base_dist);
  16164. /* First normalized distance for each code (0 = distance of 1) */
  16165. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  16166. this.static_tree = static_tree; /* static tree or NULL */
  16167. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  16168. this.extra_base = extra_base; /* base index for extra_bits */
  16169. this.elems = elems; /* max number of elements in the tree */
  16170. this.max_length = max_length; /* max bit length for the codes */
  16171. // show if `static_tree` has data or dummy - needed for monomorphic objects
  16172. this.has_stree = static_tree && static_tree.length;
  16173. };
  16174. var static_l_desc;
  16175. var static_d_desc;
  16176. var static_bl_desc;
  16177. var TreeDesc = function(dyn_tree, stat_desc) {
  16178. this.dyn_tree = dyn_tree; /* the dynamic tree */
  16179. this.max_code = 0; /* largest code with non zero frequency */
  16180. this.stat_desc = stat_desc; /* the corresponding static tree */
  16181. };
  16182. function d_code(dist) {
  16183. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  16184. }
  16185. /* ===========================================================================
  16186. * Output a short LSB first on the stream.
  16187. * IN assertion: there is enough room in pendingBuf.
  16188. */
  16189. function put_short (s, w) {
  16190. // put_byte(s, (uch)((w) & 0xff));
  16191. // put_byte(s, (uch)((ush)(w) >> 8));
  16192. s.pending_buf[s.pending++] = (w) & 0xff;
  16193. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  16194. }
  16195. /* ===========================================================================
  16196. * Send a value on a given number of bits.
  16197. * IN assertion: length <= 16 and value fits in length bits.
  16198. */
  16199. function send_bits(s, value, length) {
  16200. if (s.bi_valid > (Buf_size - length)) {
  16201. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  16202. put_short(s, s.bi_buf);
  16203. s.bi_buf = value >> (Buf_size - s.bi_valid);
  16204. s.bi_valid += length - Buf_size;
  16205. } else {
  16206. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  16207. s.bi_valid += length;
  16208. }
  16209. }
  16210. function send_code(s, c, tree) {
  16211. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  16212. }
  16213. /* ===========================================================================
  16214. * Reverse the first len bits of a code, using straightforward code (a faster
  16215. * method would use a table)
  16216. * IN assertion: 1 <= len <= 15
  16217. */
  16218. function bi_reverse(code, len) {
  16219. var res = 0;
  16220. do {
  16221. res |= code & 1;
  16222. code >>>= 1;
  16223. res <<= 1;
  16224. } while (--len > 0);
  16225. return res >>> 1;
  16226. }
  16227. /* ===========================================================================
  16228. * Flush the bit buffer, keeping at most 7 bits in it.
  16229. */
  16230. function bi_flush(s) {
  16231. if (s.bi_valid === 16) {
  16232. put_short(s, s.bi_buf);
  16233. s.bi_buf = 0;
  16234. s.bi_valid = 0;
  16235. } else if (s.bi_valid >= 8) {
  16236. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  16237. s.bi_buf >>= 8;
  16238. s.bi_valid -= 8;
  16239. }
  16240. }
  16241. /* ===========================================================================
  16242. * Compute the optimal bit lengths for a tree and update the total bit length
  16243. * for the current block.
  16244. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  16245. * above are the tree nodes sorted by increasing frequency.
  16246. * OUT assertions: the field len is set to the optimal bit length, the
  16247. * array bl_count contains the frequencies for each bit length.
  16248. * The length opt_len is updated; static_len is also updated if stree is
  16249. * not null.
  16250. */
  16251. function gen_bitlen(s, desc)
  16252. // deflate_state *s;
  16253. // tree_desc *desc; /* the tree descriptor */
  16254. {
  16255. var tree = desc.dyn_tree;
  16256. var max_code = desc.max_code;
  16257. var stree = desc.stat_desc.static_tree;
  16258. var has_stree = desc.stat_desc.has_stree;
  16259. var extra = desc.stat_desc.extra_bits;
  16260. var base = desc.stat_desc.extra_base;
  16261. var max_length = desc.stat_desc.max_length;
  16262. var h; /* heap index */
  16263. var n, m; /* iterate over the tree elements */
  16264. var bits; /* bit length */
  16265. var xbits; /* extra bits */
  16266. var f; /* frequency */
  16267. var overflow = 0; /* number of elements with bit length too large */
  16268. for (bits = 0; bits <= MAX_BITS; bits++) {
  16269. s.bl_count[bits] = 0;
  16270. }
  16271. /* In a first pass, compute the optimal bit lengths (which may
  16272. * overflow in the case of the bit length tree).
  16273. */
  16274. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  16275. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  16276. n = s.heap[h];
  16277. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  16278. if (bits > max_length) {
  16279. bits = max_length;
  16280. overflow++;
  16281. }
  16282. tree[n*2 + 1]/*.Len*/ = bits;
  16283. /* We overwrite tree[n].Dad which is no longer needed */
  16284. if (n > max_code) { continue; } /* not a leaf node */
  16285. s.bl_count[bits]++;
  16286. xbits = 0;
  16287. if (n >= base) {
  16288. xbits = extra[n-base];
  16289. }
  16290. f = tree[n * 2]/*.Freq*/;
  16291. s.opt_len += f * (bits + xbits);
  16292. if (has_stree) {
  16293. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  16294. }
  16295. }
  16296. if (overflow === 0) { return; }
  16297. // Trace((stderr,"\nbit length overflow\n"));
  16298. /* This happens for example on obj2 and pic of the Calgary corpus */
  16299. /* Find the first bit length which could increase: */
  16300. do {
  16301. bits = max_length-1;
  16302. while (s.bl_count[bits] === 0) { bits--; }
  16303. s.bl_count[bits]--; /* move one leaf down the tree */
  16304. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  16305. s.bl_count[max_length]--;
  16306. /* The brother of the overflow item also moves one step up,
  16307. * but this does not affect bl_count[max_length]
  16308. */
  16309. overflow -= 2;
  16310. } while (overflow > 0);
  16311. /* Now recompute all bit lengths, scanning in increasing frequency.
  16312. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  16313. * lengths instead of fixing only the wrong ones. This idea is taken
  16314. * from 'ar' written by Haruhiko Okumura.)
  16315. */
  16316. for (bits = max_length; bits !== 0; bits--) {
  16317. n = s.bl_count[bits];
  16318. while (n !== 0) {
  16319. m = s.heap[--h];
  16320. if (m > max_code) { continue; }
  16321. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  16322. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  16323. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  16324. tree[m*2 + 1]/*.Len*/ = bits;
  16325. }
  16326. n--;
  16327. }
  16328. }
  16329. }
  16330. /* ===========================================================================
  16331. * Generate the codes for a given tree and bit counts (which need not be
  16332. * optimal).
  16333. * IN assertion: the array bl_count contains the bit length statistics for
  16334. * the given tree and the field len is set for all tree elements.
  16335. * OUT assertion: the field code is set for all tree elements of non
  16336. * zero code length.
  16337. */
  16338. function gen_codes(tree, max_code, bl_count)
  16339. // ct_data *tree; /* the tree to decorate */
  16340. // int max_code; /* largest code with non zero frequency */
  16341. // ushf *bl_count; /* number of codes at each bit length */
  16342. {
  16343. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  16344. var code = 0; /* running code value */
  16345. var bits; /* bit index */
  16346. var n; /* code index */
  16347. /* The distribution counts are first used to generate the code values
  16348. * without bit reversal.
  16349. */
  16350. for (bits = 1; bits <= MAX_BITS; bits++) {
  16351. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  16352. }
  16353. /* Check that the bit counts in bl_count are consistent. The last code
  16354. * must be all ones.
  16355. */
  16356. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  16357. // "inconsistent bit counts");
  16358. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  16359. for (n = 0; n <= max_code; n++) {
  16360. var len = tree[n*2 + 1]/*.Len*/;
  16361. if (len === 0) { continue; }
  16362. /* Now reverse the bits */
  16363. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  16364. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  16365. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  16366. }
  16367. }
  16368. /* ===========================================================================
  16369. * Initialize the various 'constant' tables.
  16370. */
  16371. function tr_static_init() {
  16372. var n; /* iterates over tree elements */
  16373. var bits; /* bit counter */
  16374. var length; /* length value */
  16375. var code; /* code value */
  16376. var dist; /* distance index */
  16377. var bl_count = new Array(MAX_BITS+1);
  16378. /* number of codes at each bit length for an optimal tree */
  16379. // do check in _tr_init()
  16380. //if (static_init_done) return;
  16381. /* For some embedded targets, global variables are not initialized: */
  16382. /*#ifdef NO_INIT_GLOBAL_POINTERS
  16383. static_l_desc.static_tree = static_ltree;
  16384. static_l_desc.extra_bits = extra_lbits;
  16385. static_d_desc.static_tree = static_dtree;
  16386. static_d_desc.extra_bits = extra_dbits;
  16387. static_bl_desc.extra_bits = extra_blbits;
  16388. #endif*/
  16389. /* Initialize the mapping length (0..255) -> length code (0..28) */
  16390. length = 0;
  16391. for (code = 0; code < LENGTH_CODES-1; code++) {
  16392. base_length[code] = length;
  16393. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  16394. _length_code[length++] = code;
  16395. }
  16396. }
  16397. //Assert (length == 256, "tr_static_init: length != 256");
  16398. /* Note that the length 255 (match length 258) can be represented
  16399. * in two different ways: code 284 + 5 bits or code 285, so we
  16400. * overwrite length_code[255] to use the best encoding:
  16401. */
  16402. _length_code[length-1] = code;
  16403. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  16404. dist = 0;
  16405. for (code = 0 ; code < 16; code++) {
  16406. base_dist[code] = dist;
  16407. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  16408. _dist_code[dist++] = code;
  16409. }
  16410. }
  16411. //Assert (dist == 256, "tr_static_init: dist != 256");
  16412. dist >>= 7; /* from now on, all distances are divided by 128 */
  16413. for (; code < D_CODES; code++) {
  16414. base_dist[code] = dist << 7;
  16415. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  16416. _dist_code[256 + dist++] = code;
  16417. }
  16418. }
  16419. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  16420. /* Construct the codes of the static literal tree */
  16421. for (bits = 0; bits <= MAX_BITS; bits++) {
  16422. bl_count[bits] = 0;
  16423. }
  16424. n = 0;
  16425. while (n <= 143) {
  16426. static_ltree[n*2 + 1]/*.Len*/ = 8;
  16427. n++;
  16428. bl_count[8]++;
  16429. }
  16430. while (n <= 255) {
  16431. static_ltree[n*2 + 1]/*.Len*/ = 9;
  16432. n++;
  16433. bl_count[9]++;
  16434. }
  16435. while (n <= 279) {
  16436. static_ltree[n*2 + 1]/*.Len*/ = 7;
  16437. n++;
  16438. bl_count[7]++;
  16439. }
  16440. while (n <= 287) {
  16441. static_ltree[n*2 + 1]/*.Len*/ = 8;
  16442. n++;
  16443. bl_count[8]++;
  16444. }
  16445. /* Codes 286 and 287 do not exist, but we must include them in the
  16446. * tree construction to get a canonical Huffman tree (longest code
  16447. * all ones)
  16448. */
  16449. gen_codes(static_ltree, L_CODES+1, bl_count);
  16450. /* The static distance tree is trivial: */
  16451. for (n = 0; n < D_CODES; n++) {
  16452. static_dtree[n*2 + 1]/*.Len*/ = 5;
  16453. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  16454. }
  16455. // Now data ready and we can init static trees
  16456. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  16457. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  16458. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  16459. //static_init_done = true;
  16460. }
  16461. /* ===========================================================================
  16462. * Initialize a new block.
  16463. */
  16464. function init_block(s) {
  16465. var n; /* iterates over tree elements */
  16466. /* Initialize the trees. */
  16467. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  16468. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  16469. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  16470. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  16471. s.opt_len = s.static_len = 0;
  16472. s.last_lit = s.matches = 0;
  16473. }
  16474. /* ===========================================================================
  16475. * Flush the bit buffer and align the output on a byte boundary
  16476. */
  16477. function bi_windup(s)
  16478. {
  16479. if (s.bi_valid > 8) {
  16480. put_short(s, s.bi_buf);
  16481. } else if (s.bi_valid > 0) {
  16482. //put_byte(s, (Byte)s->bi_buf);
  16483. s.pending_buf[s.pending++] = s.bi_buf;
  16484. }
  16485. s.bi_buf = 0;
  16486. s.bi_valid = 0;
  16487. }
  16488. /* ===========================================================================
  16489. * Copy a stored block, storing first the length and its
  16490. * one's complement if requested.
  16491. */
  16492. function copy_block(s, buf, len, header)
  16493. //DeflateState *s;
  16494. //charf *buf; /* the input data */
  16495. //unsigned len; /* its length */
  16496. //int header; /* true if block header must be written */
  16497. {
  16498. bi_windup(s); /* align on byte boundary */
  16499. if (header) {
  16500. put_short(s, len);
  16501. put_short(s, ~len);
  16502. }
  16503. // while (len--) {
  16504. // put_byte(s, *buf++);
  16505. // }
  16506. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  16507. s.pending += len;
  16508. }
  16509. /* ===========================================================================
  16510. * Compares to subtrees, using the tree depth as tie breaker when
  16511. * the subtrees have equal frequency. This minimizes the worst case length.
  16512. */
  16513. function smaller(tree, n, m, depth) {
  16514. var _n2 = n*2;
  16515. var _m2 = m*2;
  16516. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  16517. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  16518. }
  16519. /* ===========================================================================
  16520. * Restore the heap property by moving down the tree starting at node k,
  16521. * exchanging a node with the smallest of its two sons if necessary, stopping
  16522. * when the heap property is re-established (each father smaller than its
  16523. * two sons).
  16524. */
  16525. function pqdownheap(s, tree, k)
  16526. // deflate_state *s;
  16527. // ct_data *tree; /* the tree to restore */
  16528. // int k; /* node to move down */
  16529. {
  16530. var v = s.heap[k];
  16531. var j = k << 1; /* left son of k */
  16532. while (j <= s.heap_len) {
  16533. /* Set j to the smallest of the two sons: */
  16534. if (j < s.heap_len &&
  16535. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  16536. j++;
  16537. }
  16538. /* Exit if v is smaller than both sons */
  16539. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  16540. /* Exchange v with the smallest son */
  16541. s.heap[k] = s.heap[j];
  16542. k = j;
  16543. /* And continue down the tree, setting j to the left son of k */
  16544. j <<= 1;
  16545. }
  16546. s.heap[k] = v;
  16547. }
  16548. // inlined manually
  16549. // var SMALLEST = 1;
  16550. /* ===========================================================================
  16551. * Send the block data compressed using the given Huffman trees
  16552. */
  16553. function compress_block(s, ltree, dtree)
  16554. // deflate_state *s;
  16555. // const ct_data *ltree; /* literal tree */
  16556. // const ct_data *dtree; /* distance tree */
  16557. {
  16558. var dist; /* distance of matched string */
  16559. var lc; /* match length or unmatched char (if dist == 0) */
  16560. var lx = 0; /* running index in l_buf */
  16561. var code; /* the code to send */
  16562. var extra; /* number of extra bits to send */
  16563. if (s.last_lit !== 0) {
  16564. do {
  16565. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  16566. lc = s.pending_buf[s.l_buf + lx];
  16567. lx++;
  16568. if (dist === 0) {
  16569. send_code(s, lc, ltree); /* send a literal byte */
  16570. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  16571. } else {
  16572. /* Here, lc is the match length - MIN_MATCH */
  16573. code = _length_code[lc];
  16574. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  16575. extra = extra_lbits[code];
  16576. if (extra !== 0) {
  16577. lc -= base_length[code];
  16578. send_bits(s, lc, extra); /* send the extra length bits */
  16579. }
  16580. dist--; /* dist is now the match distance - 1 */
  16581. code = d_code(dist);
  16582. //Assert (code < D_CODES, "bad d_code");
  16583. send_code(s, code, dtree); /* send the distance code */
  16584. extra = extra_dbits[code];
  16585. if (extra !== 0) {
  16586. dist -= base_dist[code];
  16587. send_bits(s, dist, extra); /* send the extra distance bits */
  16588. }
  16589. } /* literal or match pair ? */
  16590. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  16591. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  16592. // "pendingBuf overflow");
  16593. } while (lx < s.last_lit);
  16594. }
  16595. send_code(s, END_BLOCK, ltree);
  16596. }
  16597. /* ===========================================================================
  16598. * Construct one Huffman tree and assigns the code bit strings and lengths.
  16599. * Update the total bit length for the current block.
  16600. * IN assertion: the field freq is set for all tree elements.
  16601. * OUT assertions: the fields len and code are set to the optimal bit length
  16602. * and corresponding code. The length opt_len is updated; static_len is
  16603. * also updated if stree is not null. The field max_code is set.
  16604. */
  16605. function build_tree(s, desc)
  16606. // deflate_state *s;
  16607. // tree_desc *desc; /* the tree descriptor */
  16608. {
  16609. var tree = desc.dyn_tree;
  16610. var stree = desc.stat_desc.static_tree;
  16611. var has_stree = desc.stat_desc.has_stree;
  16612. var elems = desc.stat_desc.elems;
  16613. var n, m; /* iterate over heap elements */
  16614. var max_code = -1; /* largest code with non zero frequency */
  16615. var node; /* new node being created */
  16616. /* Construct the initial heap, with least frequent element in
  16617. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  16618. * heap[0] is not used.
  16619. */
  16620. s.heap_len = 0;
  16621. s.heap_max = HEAP_SIZE;
  16622. for (n = 0; n < elems; n++) {
  16623. if (tree[n * 2]/*.Freq*/ !== 0) {
  16624. s.heap[++s.heap_len] = max_code = n;
  16625. s.depth[n] = 0;
  16626. } else {
  16627. tree[n*2 + 1]/*.Len*/ = 0;
  16628. }
  16629. }
  16630. /* The pkzip format requires that at least one distance code exists,
  16631. * and that at least one bit should be sent even if there is only one
  16632. * possible code. So to avoid special checks later on we force at least
  16633. * two codes of non zero frequency.
  16634. */
  16635. while (s.heap_len < 2) {
  16636. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  16637. tree[node * 2]/*.Freq*/ = 1;
  16638. s.depth[node] = 0;
  16639. s.opt_len--;
  16640. if (has_stree) {
  16641. s.static_len -= stree[node*2 + 1]/*.Len*/;
  16642. }
  16643. /* node is 0 or 1 so it does not have extra bits */
  16644. }
  16645. desc.max_code = max_code;
  16646. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  16647. * establish sub-heaps of increasing lengths:
  16648. */
  16649. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  16650. /* Construct the Huffman tree by repeatedly combining the least two
  16651. * frequent nodes.
  16652. */
  16653. node = elems; /* next internal node of the tree */
  16654. do {
  16655. //pqremove(s, tree, n); /* n = node of least frequency */
  16656. /*** pqremove ***/
  16657. n = s.heap[1/*SMALLEST*/];
  16658. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  16659. pqdownheap(s, tree, 1/*SMALLEST*/);
  16660. /***/
  16661. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  16662. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  16663. s.heap[--s.heap_max] = m;
  16664. /* Create a new node father of n and m */
  16665. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  16666. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  16667. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  16668. /* and insert the new node in the heap */
  16669. s.heap[1/*SMALLEST*/] = node++;
  16670. pqdownheap(s, tree, 1/*SMALLEST*/);
  16671. } while (s.heap_len >= 2);
  16672. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  16673. /* At this point, the fields freq and dad are set. We can now
  16674. * generate the bit lengths.
  16675. */
  16676. gen_bitlen(s, desc);
  16677. /* The field len is now set, we can generate the bit codes */
  16678. gen_codes(tree, max_code, s.bl_count);
  16679. }
  16680. /* ===========================================================================
  16681. * Scan a literal or distance tree to determine the frequencies of the codes
  16682. * in the bit length tree.
  16683. */
  16684. function scan_tree(s, tree, max_code)
  16685. // deflate_state *s;
  16686. // ct_data *tree; /* the tree to be scanned */
  16687. // int max_code; /* and its largest code of non zero frequency */
  16688. {
  16689. var n; /* iterates over all tree elements */
  16690. var prevlen = -1; /* last emitted length */
  16691. var curlen; /* length of current code */
  16692. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  16693. var count = 0; /* repeat count of the current code */
  16694. var max_count = 7; /* max repeat count */
  16695. var min_count = 4; /* min repeat count */
  16696. if (nextlen === 0) {
  16697. max_count = 138;
  16698. min_count = 3;
  16699. }
  16700. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  16701. for (n = 0; n <= max_code; n++) {
  16702. curlen = nextlen;
  16703. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  16704. if (++count < max_count && curlen === nextlen) {
  16705. continue;
  16706. } else if (count < min_count) {
  16707. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  16708. } else if (curlen !== 0) {
  16709. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  16710. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  16711. } else if (count <= 10) {
  16712. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  16713. } else {
  16714. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  16715. }
  16716. count = 0;
  16717. prevlen = curlen;
  16718. if (nextlen === 0) {
  16719. max_count = 138;
  16720. min_count = 3;
  16721. } else if (curlen === nextlen) {
  16722. max_count = 6;
  16723. min_count = 3;
  16724. } else {
  16725. max_count = 7;
  16726. min_count = 4;
  16727. }
  16728. }
  16729. }
  16730. /* ===========================================================================
  16731. * Send a literal or distance tree in compressed form, using the codes in
  16732. * bl_tree.
  16733. */
  16734. function send_tree(s, tree, max_code)
  16735. // deflate_state *s;
  16736. // ct_data *tree; /* the tree to be scanned */
  16737. // int max_code; /* and its largest code of non zero frequency */
  16738. {
  16739. var n; /* iterates over all tree elements */
  16740. var prevlen = -1; /* last emitted length */
  16741. var curlen; /* length of current code */
  16742. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  16743. var count = 0; /* repeat count of the current code */
  16744. var max_count = 7; /* max repeat count */
  16745. var min_count = 4; /* min repeat count */
  16746. /* tree[max_code+1].Len = -1; */ /* guard already set */
  16747. if (nextlen === 0) {
  16748. max_count = 138;
  16749. min_count = 3;
  16750. }
  16751. for (n = 0; n <= max_code; n++) {
  16752. curlen = nextlen;
  16753. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  16754. if (++count < max_count && curlen === nextlen) {
  16755. continue;
  16756. } else if (count < min_count) {
  16757. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  16758. } else if (curlen !== 0) {
  16759. if (curlen !== prevlen) {
  16760. send_code(s, curlen, s.bl_tree);
  16761. count--;
  16762. }
  16763. //Assert(count >= 3 && count <= 6, " 3_6?");
  16764. send_code(s, REP_3_6, s.bl_tree);
  16765. send_bits(s, count-3, 2);
  16766. } else if (count <= 10) {
  16767. send_code(s, REPZ_3_10, s.bl_tree);
  16768. send_bits(s, count-3, 3);
  16769. } else {
  16770. send_code(s, REPZ_11_138, s.bl_tree);
  16771. send_bits(s, count-11, 7);
  16772. }
  16773. count = 0;
  16774. prevlen = curlen;
  16775. if (nextlen === 0) {
  16776. max_count = 138;
  16777. min_count = 3;
  16778. } else if (curlen === nextlen) {
  16779. max_count = 6;
  16780. min_count = 3;
  16781. } else {
  16782. max_count = 7;
  16783. min_count = 4;
  16784. }
  16785. }
  16786. }
  16787. /* ===========================================================================
  16788. * Construct the Huffman tree for the bit lengths and return the index in
  16789. * bl_order of the last bit length code to send.
  16790. */
  16791. function build_bl_tree(s) {
  16792. var max_blindex; /* index of last bit length code of non zero freq */
  16793. /* Determine the bit length frequencies for literal and distance trees */
  16794. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  16795. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  16796. /* Build the bit length tree: */
  16797. build_tree(s, s.bl_desc);
  16798. /* opt_len now includes the length of the tree representations, except
  16799. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  16800. */
  16801. /* Determine the number of bit length codes to send. The pkzip format
  16802. * requires that at least 4 bit length codes be sent. (appnote.txt says
  16803. * 3 but the actual value used is 4.)
  16804. */
  16805. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  16806. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  16807. break;
  16808. }
  16809. }
  16810. /* Update opt_len to include the bit length tree and counts */
  16811. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  16812. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  16813. // s->opt_len, s->static_len));
  16814. return max_blindex;
  16815. }
  16816. /* ===========================================================================
  16817. * Send the header for a block using dynamic Huffman trees: the counts, the
  16818. * lengths of the bit length codes, the literal tree and the distance tree.
  16819. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  16820. */
  16821. function send_all_trees(s, lcodes, dcodes, blcodes)
  16822. // deflate_state *s;
  16823. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  16824. {
  16825. var rank; /* index in bl_order */
  16826. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  16827. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  16828. // "too many codes");
  16829. //Tracev((stderr, "\nbl counts: "));
  16830. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  16831. send_bits(s, dcodes-1, 5);
  16832. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  16833. for (rank = 0; rank < blcodes; rank++) {
  16834. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  16835. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  16836. }
  16837. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  16838. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  16839. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  16840. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  16841. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  16842. }
  16843. /* ===========================================================================
  16844. * Check if the data type is TEXT or BINARY, using the following algorithm:
  16845. * - TEXT if the two conditions below are satisfied:
  16846. * a) There are no non-portable control characters belonging to the
  16847. * "black list" (0..6, 14..25, 28..31).
  16848. * b) There is at least one printable character belonging to the
  16849. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  16850. * - BINARY otherwise.
  16851. * - The following partially-portable control characters form a
  16852. * "gray list" that is ignored in this detection algorithm:
  16853. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  16854. * IN assertion: the fields Freq of dyn_ltree are set.
  16855. */
  16856. function detect_data_type(s) {
  16857. /* black_mask is the bit mask of black-listed bytes
  16858. * set bits 0..6, 14..25, and 28..31
  16859. * 0xf3ffc07f = binary 11110011111111111100000001111111
  16860. */
  16861. var black_mask = 0xf3ffc07f;
  16862. var n;
  16863. /* Check for non-textual ("black-listed") bytes. */
  16864. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  16865. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  16866. return Z_BINARY;
  16867. }
  16868. }
  16869. /* Check for textual ("white-listed") bytes. */
  16870. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  16871. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  16872. return Z_TEXT;
  16873. }
  16874. for (n = 32; n < LITERALS; n++) {
  16875. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  16876. return Z_TEXT;
  16877. }
  16878. }
  16879. /* There are no "black-listed" or "white-listed" bytes:
  16880. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  16881. */
  16882. return Z_BINARY;
  16883. }
  16884. var static_init_done = false;
  16885. /* ===========================================================================
  16886. * Initialize the tree data structures for a new zlib stream.
  16887. */
  16888. function _tr_init(s)
  16889. {
  16890. if (!static_init_done) {
  16891. tr_static_init();
  16892. static_init_done = true;
  16893. }
  16894. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  16895. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  16896. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  16897. s.bi_buf = 0;
  16898. s.bi_valid = 0;
  16899. /* Initialize the first block of the first file: */
  16900. init_block(s);
  16901. }
  16902. /* ===========================================================================
  16903. * Send a stored block
  16904. */
  16905. function _tr_stored_block(s, buf, stored_len, last)
  16906. //DeflateState *s;
  16907. //charf *buf; /* input block */
  16908. //ulg stored_len; /* length of input block */
  16909. //int last; /* one if this is the last block for a file */
  16910. {
  16911. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  16912. copy_block(s, buf, stored_len, true); /* with header */
  16913. }
  16914. /* ===========================================================================
  16915. * Send one empty static block to give enough lookahead for inflate.
  16916. * This takes 10 bits, of which 7 may remain in the bit buffer.
  16917. */
  16918. function _tr_align(s) {
  16919. send_bits(s, STATIC_TREES<<1, 3);
  16920. send_code(s, END_BLOCK, static_ltree);
  16921. bi_flush(s);
  16922. }
  16923. /* ===========================================================================
  16924. * Determine the best encoding for the current block: dynamic trees, static
  16925. * trees or store, and output the encoded block to the zip file.
  16926. */
  16927. function _tr_flush_block(s, buf, stored_len, last)
  16928. //DeflateState *s;
  16929. //charf *buf; /* input block, or NULL if too old */
  16930. //ulg stored_len; /* length of input block */
  16931. //int last; /* one if this is the last block for a file */
  16932. {
  16933. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  16934. var max_blindex = 0; /* index of last bit length code of non zero freq */
  16935. /* Build the Huffman trees unless a stored block is forced */
  16936. if (s.level > 0) {
  16937. /* Check if the file is binary or text */
  16938. if (s.strm.data_type === Z_UNKNOWN) {
  16939. s.strm.data_type = detect_data_type(s);
  16940. }
  16941. /* Construct the literal and distance trees */
  16942. build_tree(s, s.l_desc);
  16943. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  16944. // s->static_len));
  16945. build_tree(s, s.d_desc);
  16946. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  16947. // s->static_len));
  16948. /* At this point, opt_len and static_len are the total bit lengths of
  16949. * the compressed block data, excluding the tree representations.
  16950. */
  16951. /* Build the bit length tree for the above two trees, and get the index
  16952. * in bl_order of the last bit length code to send.
  16953. */
  16954. max_blindex = build_bl_tree(s);
  16955. /* Determine the best encoding. Compute the block lengths in bytes. */
  16956. opt_lenb = (s.opt_len+3+7) >>> 3;
  16957. static_lenb = (s.static_len+3+7) >>> 3;
  16958. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  16959. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  16960. // s->last_lit));
  16961. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  16962. } else {
  16963. // Assert(buf != (char*)0, "lost buf");
  16964. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  16965. }
  16966. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  16967. /* 4: two words for the lengths */
  16968. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  16969. * Otherwise we can't have processed more than WSIZE input bytes since
  16970. * the last block flush, because compression would have been
  16971. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  16972. * transform a block into a stored block.
  16973. */
  16974. _tr_stored_block(s, buf, stored_len, last);
  16975. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  16976. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  16977. compress_block(s, static_ltree, static_dtree);
  16978. } else {
  16979. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  16980. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  16981. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  16982. }
  16983. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  16984. /* The above check is made mod 2^32, for files larger than 512 MB
  16985. * and uLong implemented on 32 bits.
  16986. */
  16987. init_block(s);
  16988. if (last) {
  16989. bi_windup(s);
  16990. }
  16991. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  16992. // s->compressed_len-7*last));
  16993. }
  16994. /* ===========================================================================
  16995. * Save the match info and tally the frequency counts. Return true if
  16996. * the current block must be flushed.
  16997. */
  16998. function _tr_tally(s, dist, lc)
  16999. // deflate_state *s;
  17000. // unsigned dist; /* distance of matched string */
  17001. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  17002. {
  17003. //var out_length, in_length, dcode;
  17004. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  17005. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  17006. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  17007. s.last_lit++;
  17008. if (dist === 0) {
  17009. /* lc is the unmatched char */
  17010. s.dyn_ltree[lc*2]/*.Freq*/++;
  17011. } else {
  17012. s.matches++;
  17013. /* Here, lc is the match length - MIN_MATCH */
  17014. dist--; /* dist = match distance - 1 */
  17015. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  17016. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  17017. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  17018. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  17019. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  17020. }
  17021. // (!) This block is disabled in zlib defailts,
  17022. // don't enable it for binary compatibility
  17023. //#ifdef TRUNCATE_BLOCK
  17024. // /* Try to guess if it is profitable to stop the current block here */
  17025. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  17026. // /* Compute an upper bound for the compressed length */
  17027. // out_length = s.last_lit*8;
  17028. // in_length = s.strstart - s.block_start;
  17029. //
  17030. // for (dcode = 0; dcode < D_CODES; dcode++) {
  17031. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  17032. // }
  17033. // out_length >>>= 3;
  17034. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  17035. // // s->last_lit, in_length, out_length,
  17036. // // 100L - out_length*100L/in_length));
  17037. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  17038. // return true;
  17039. // }
  17040. // }
  17041. //#endif
  17042. return (s.last_lit === s.lit_bufsize-1);
  17043. /* We avoid equality with lit_bufsize because of wraparound at 64K
  17044. * on 16 bit machines and because stored blocks are restricted to
  17045. * 64K-1 bytes.
  17046. */
  17047. }
  17048. exports._tr_init = _tr_init;
  17049. exports._tr_stored_block = _tr_stored_block;
  17050. exports._tr_flush_block = _tr_flush_block;
  17051. exports._tr_tally = _tr_tally;
  17052. exports._tr_align = _tr_align;
  17053. },{"../utils/common":45}],57:[function(require,module,exports){
  17054. 'use strict';
  17055. function ZStream() {
  17056. /* next input byte */
  17057. this.input = null; // JS specific, because we have no pointers
  17058. this.next_in = 0;
  17059. /* number of bytes available at input */
  17060. this.avail_in = 0;
  17061. /* total number of input bytes read so far */
  17062. this.total_in = 0;
  17063. /* next output byte should be put there */
  17064. this.output = null; // JS specific, because we have no pointers
  17065. this.next_out = 0;
  17066. /* remaining free space at output */
  17067. this.avail_out = 0;
  17068. /* total number of bytes output so far */
  17069. this.total_out = 0;
  17070. /* last error message, NULL if no error */
  17071. this.msg = ''/*Z_NULL*/;
  17072. /* not visible by applications */
  17073. this.state = null;
  17074. /* best guess about the data type: binary or text */
  17075. this.data_type = 2/*Z_UNKNOWN*/;
  17076. /* adler32 value of the uncompressed data */
  17077. this.adler = 0;
  17078. }
  17079. module.exports = ZStream;
  17080. },{}],58:[function(require,module,exports){
  17081. module.exports = function arrayEquals(array) {
  17082. // if the other array is a falsy value, return
  17083. if (!array)
  17084. return false;
  17085. // compare lengths - can save a lot of time
  17086. if (this.length != array.length)
  17087. return false;
  17088. for (var i = 0, l = this.length; i < l; i++) {
  17089. // Check if we have nested arrays
  17090. if (this[i] instanceof Array && array[i] instanceof Array) {
  17091. // recurse into the nested arrays
  17092. if (!arrayEquals.apply(this[i], [array[i]]))
  17093. return false;
  17094. } else if (this[i] != array[i]) {
  17095. // Warning - two different object instances will never be equal:
  17096. // {x:20} != {x:20}
  17097. return false;
  17098. }
  17099. }
  17100. return true;
  17101. }
  17102. },{}],59:[function(require,module,exports){
  17103. exports.Interop = require('./interop');
  17104. },{"./interop":60}],60:[function(require,module,exports){
  17105. "use strict";
  17106. var transform = require('./transform');
  17107. var arrayEquals = require('./array-equals');
  17108. function Interop() {
  17109. /**
  17110. * This map holds the most recent Unified Plan offer/answer SDP that was
  17111. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  17112. * the SDP string as values.
  17113. *
  17114. * @type {{}}
  17115. */
  17116. this.cache = {};
  17117. }
  17118. module.exports = Interop;
  17119. /**
  17120. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  17121. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  17122. * application.
  17123. *
  17124. * @param desc
  17125. * @returns {*}
  17126. */
  17127. Interop.prototype.toPlanB = function(desc) {
  17128. //#region Preliminary input validation.
  17129. if (typeof desc !== 'object' || desc === null ||
  17130. typeof desc.sdp !== 'string') {
  17131. console.warn('An empty description was passed as an argument.');
  17132. return desc;
  17133. }
  17134. // Objectify the SDP for easier manipulation.
  17135. var session = transform.parse(desc.sdp);
  17136. // If the SDP contains no media, there's nothing to transform.
  17137. if (typeof session.media === 'undefined' ||
  17138. !Array.isArray(session.media) || session.media.length === 0) {
  17139. console.warn('The description has no media.');
  17140. return desc;
  17141. }
  17142. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  17143. // SDP has a video, an audio and a data "channel" at most.
  17144. if (session.media.length <= 3 && session.media.every(function(m) {
  17145. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  17146. })) {
  17147. console.warn('This description does not look like Unified Plan.');
  17148. return desc;
  17149. }
  17150. //#endregion
  17151. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  17152. // -> Unified Plan transformation.
  17153. this.cache[desc.type] = desc.sdp;
  17154. //#region Convert from Unified Plan to Plan B.
  17155. // We rebuild the session.media array.
  17156. var media = session.media;
  17157. session.media = [];
  17158. // Associative array that maps channel types to channel objects for fast
  17159. // access to channel objects by their type, e.g. type2bl['audio']->channel
  17160. // obj.
  17161. var type2bl = {};
  17162. // Used to build the group:BUNDLE value after the channels construction
  17163. // loop.
  17164. var types = [];
  17165. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  17166. media.forEach(function(unifiedLine) {
  17167. // rtcp-mux is required in the Plan B SDP.
  17168. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  17169. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  17170. unifiedLine.direction !== 'inactive') {
  17171. throw new Error('Cannot convert to Plan B because m-lines ' +
  17172. 'without the rtcp-mux attribute were found.');
  17173. }
  17174. if (unifiedLine.type === 'application') {
  17175. session.media.push(unifiedLine);
  17176. types.push(unifiedLine.mid);
  17177. return;
  17178. }
  17179. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  17180. // as the channel basis.
  17181. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  17182. type2bl[unifiedLine.type] = unifiedLine;
  17183. }
  17184. // Add sources to the channel and handle a=msid.
  17185. if (typeof unifiedLine.sources === 'object') {
  17186. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  17187. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  17188. type2bl[unifiedLine.type].sources = {};
  17189. // Assign the sources to the channel.
  17190. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  17191. if (typeof unifiedLine.msid !== 'undefined') {
  17192. // In Plan B the msid is an SSRC attribute. Also, we don't
  17193. // care about the obsolete label and mslabel attributes.
  17194. //
  17195. // Note that it is not guaranteed that the unifiedLine will have
  17196. // an msid. recvonly channels in particular don't have one.
  17197. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  17198. }
  17199. // NOTE ssrcs in ssrc groups will share msids, as
  17200. // draft-uberti-rtcweb-plan-00 mandates.
  17201. });
  17202. }
  17203. // Add ssrc groups to the channel.
  17204. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  17205. Array.isArray(unifiedLine.ssrcGroups)) {
  17206. // Create the ssrcGroups array, if it's not defined.
  17207. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  17208. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  17209. type2bl[unifiedLine.type].ssrcGroups = [];
  17210. }
  17211. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  17212. }
  17213. if (type2bl[unifiedLine.type] === unifiedLine) {
  17214. // Copy ICE related stuff from the principal media line.
  17215. unifiedLine.candidates = media[0].candidates;
  17216. unifiedLine.iceUfrag = media[0].iceUfrag;
  17217. unifiedLine.icePwd = media[0].icePwd;
  17218. unifiedLine.fingerprint = media[0].fingerprint;
  17219. // Plan B mids are in ['audio', 'video', 'data']
  17220. unifiedLine.mid = unifiedLine.type;
  17221. // Plan B doesn't support/need the bundle-only attribute.
  17222. delete unifiedLine.bundleOnly;
  17223. // In Plan B the msid is an SSRC attribute.
  17224. delete unifiedLine.msid;
  17225. // Used to build the group:BUNDLE value after this loop.
  17226. types.push(unifiedLine.type);
  17227. // Add the channel to the new media array.
  17228. session.media.push(unifiedLine);
  17229. }
  17230. });
  17231. // We regenerate the BUNDLE group with the new mids.
  17232. session.groups.some(function(group) {
  17233. if (group.type === 'BUNDLE') {
  17234. group.mids = types.join(' ');
  17235. return true;
  17236. }
  17237. });
  17238. // msid semantic
  17239. session.msidSemantic = {
  17240. semantic: 'WMS',
  17241. token: '*'
  17242. };
  17243. var resStr = transform.write(session);
  17244. return new RTCSessionDescription({
  17245. type: desc.type,
  17246. sdp: resStr
  17247. });
  17248. //#endregion
  17249. };
  17250. /**
  17251. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  17252. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  17253. * to FF.
  17254. *
  17255. * @param desc
  17256. * @returns {*}
  17257. */
  17258. Interop.prototype.toUnifiedPlan = function(desc) {
  17259. //#region Preliminary input validation.
  17260. if (typeof desc !== 'object' || desc === null ||
  17261. typeof desc.sdp !== 'string') {
  17262. console.warn('An empty description was passed as an argument.');
  17263. return desc;
  17264. }
  17265. var session = transform.parse(desc.sdp);
  17266. // If the SDP contains no media, there's nothing to transform.
  17267. if (typeof session.media === 'undefined' ||
  17268. !Array.isArray(session.media) || session.media.length === 0) {
  17269. console.warn('The description has no media.');
  17270. return desc;
  17271. }
  17272. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  17273. // a video, an audio and a data "channel" at most.
  17274. if (session.media.length > 3 || !session.media.every(function(m) {
  17275. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  17276. })) {
  17277. console.warn('This description does not look like Plan B.');
  17278. return desc;
  17279. }
  17280. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  17281. var mids = [];
  17282. session.media.forEach(function(m) {
  17283. mids.push(m.mid);
  17284. });
  17285. var hasBundle = false;
  17286. if (typeof session.groups !== 'undefined' &&
  17287. Array.isArray(session.groups)) {
  17288. hasBundle = session.groups.every(function(g) {
  17289. return g.type !== 'BUNDLE' ||
  17290. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  17291. });
  17292. }
  17293. if (!hasBundle) {
  17294. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  17295. " are not bundled were found.");
  17296. }
  17297. //#endregion
  17298. //#region Convert from Plan B to Unified Plan.
  17299. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  17300. // rebuild an equivalent Unified Plan offer/answer.
  17301. //
  17302. // For example, if this is a local answer (in Unified Plan style) that we
  17303. // convert to Plan B prior to handing it over to the application (the
  17304. // PeerConnection wrapper called us, for instance, after a successful
  17305. // createAnswer), we want to remember the m-line at which we've seen the
  17306. // (local) SSRC. That's because when the application wants to do call the
  17307. // SLD method, forcing us to do the inverse transformation (from Plan B to
  17308. // Unified Plan), we need to know to which m-line to assign the (local)
  17309. // SSRC. We also need to know all the other m-lines that the original
  17310. // answer had and include them in the transformed answer as well.
  17311. //
  17312. // Another example is if this is a remote offer that we convert to Plan B
  17313. // prior to giving it to the application, we want to remember the mid at
  17314. // which we've seen the (remote) SSRC.
  17315. //
  17316. // In the iteration that follows, we use the cached Unified Plan (if it
  17317. // exists) to assign mids to ssrcs.
  17318. var cached;
  17319. if (typeof this.cache[desc.type] !== 'undefined') {
  17320. cached = transform.parse(this.cache[desc.type]);
  17321. }
  17322. // A helper map that sends mids to m-line objects. We use it later to
  17323. // rebuild the Unified Plan style session.media array.
  17324. var mid2ul = {};
  17325. session.media.forEach(function(bLine) {
  17326. if ((typeof bLine.rtcpMux !== 'string' ||
  17327. bLine.rtcpMux !== 'rtcp-mux') &&
  17328. bLine.direction !== 'inactive') {
  17329. throw new Error("Cannot convert to Unified Plan because m-lines " +
  17330. "without the rtcp-mux attribute were found.");
  17331. }
  17332. if (bLine.type === 'application') {
  17333. mid2ul[bLine.mid] = bLine;
  17334. return;
  17335. }
  17336. // With rtcp-mux and bundle all the channels should have the same ICE
  17337. // stuff.
  17338. var sources = bLine.sources;
  17339. var ssrcGroups = bLine.ssrcGroups;
  17340. var candidates = bLine.candidates;
  17341. var iceUfrag = bLine.iceUfrag;
  17342. var icePwd = bLine.icePwd;
  17343. var fingerprint = bLine.fingerprint;
  17344. var port = bLine.port;
  17345. // We'll use the "bLine" object as a prototype for each new "mLine"
  17346. // that we create, but first we need to clean it up a bit.
  17347. delete bLine.sources;
  17348. delete bLine.ssrcGroups;
  17349. delete bLine.candidates;
  17350. delete bLine.iceUfrag;
  17351. delete bLine.icePwd;
  17352. delete bLine.fingerprint;
  17353. delete bLine.port;
  17354. delete bLine.mid;
  17355. // inverted ssrc group map
  17356. var ssrc2group = {};
  17357. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  17358. ssrcGroups.forEach(function (ssrcGroup) {
  17359. // TODO(gp) find out how to receive simulcast with FF. For the
  17360. // time being, hide it.
  17361. if (ssrcGroup.semantics === 'SIM') {
  17362. return;
  17363. }
  17364. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  17365. Array.isArray(ssrcGroup.ssrcs)) {
  17366. ssrcGroup.ssrcs.forEach(function (ssrc) {
  17367. if (typeof ssrc2group[ssrc] === 'undefined') {
  17368. ssrc2group[ssrc] = [];
  17369. }
  17370. ssrc2group[ssrc].push(ssrcGroup);
  17371. });
  17372. }
  17373. });
  17374. }
  17375. // ssrc to m-line index.
  17376. var ssrc2ml = {};
  17377. if (typeof sources === 'object') {
  17378. // Explode the Plan B channel sources with one m-line per source.
  17379. Object.keys(sources).forEach(function(ssrc) {
  17380. // The (unified) m-line for this SSRC. We either create it from
  17381. // scratch or, if it's a grouped SSRC, we re-use a related
  17382. // mline. In other words, if the source is grouped with another
  17383. // source, put the two together in the same m-line.
  17384. var unifiedLine;
  17385. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  17386. Array.isArray(ssrc2group[ssrc])) {
  17387. ssrc2group[ssrc].some(function (ssrcGroup) {
  17388. // ssrcGroup.ssrcs *is* an Array, no need to check
  17389. // again here.
  17390. return ssrcGroup.ssrcs.some(function (related) {
  17391. if (typeof ssrc2ml[related] === 'object') {
  17392. unifiedLine = ssrc2ml[related];
  17393. return true;
  17394. }
  17395. });
  17396. });
  17397. }
  17398. if (typeof unifiedLine === 'object') {
  17399. // the m-line already exists. Just add the source.
  17400. unifiedLine.sources[ssrc] = sources[ssrc];
  17401. delete sources[ssrc].msid;
  17402. } else {
  17403. // Use the "bLine" as a prototype for the "unifiedLine".
  17404. unifiedLine = Object.create(bLine);
  17405. ssrc2ml[ssrc] = unifiedLine;
  17406. if (typeof sources[ssrc].msid !== 'undefined') {
  17407. // Assign the msid of the source to the m-line. Note
  17408. // that it is not guaranteed that the source will have
  17409. // msid. In particular "recvonly" sources don't have an
  17410. // msid. Note that "recvonly" is a term only defined
  17411. // for m-lines.
  17412. unifiedLine.msid = sources[ssrc].msid;
  17413. delete sources[ssrc].msid;
  17414. }
  17415. // We assign one SSRC per media line.
  17416. unifiedLine.sources = {};
  17417. unifiedLine.sources[ssrc] = sources[ssrc];
  17418. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  17419. // Use the cached Unified Plan SDP (if it exists) to assign
  17420. // SSRCs to mids.
  17421. if (typeof cached !== 'undefined' &&
  17422. typeof cached.media !== 'undefined' &&
  17423. Array.isArray(cached.media)) {
  17424. cached.media.forEach(function (m) {
  17425. if (typeof m.sources === 'object') {
  17426. Object.keys(m.sources).forEach(function (s) {
  17427. if (s === ssrc) {
  17428. unifiedLine.mid = m.mid;
  17429. }
  17430. });
  17431. }
  17432. });
  17433. }
  17434. if (typeof unifiedLine.mid === 'undefined') {
  17435. // If this is an SSRC that we see for the first time
  17436. // assign it a new mid. This is typically the case when
  17437. // this method is called to transform a remote
  17438. // description for the first time or when there is a
  17439. // new SSRC in the remote description because a new
  17440. // peer has joined the conference. Local SSRCs should
  17441. // have already been added to the map in the toPlanB
  17442. // method.
  17443. //
  17444. // Because FF generates answers in Unified Plan style,
  17445. // we MUST already have a cached answer with all the
  17446. // local SSRCs mapped to some m-line/mid.
  17447. if (desc.type === 'answer') {
  17448. throw new Error("An unmapped SSRC was found.");
  17449. }
  17450. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  17451. }
  17452. // Include the candidates in the 1st media line.
  17453. unifiedLine.candidates = candidates;
  17454. unifiedLine.iceUfrag = iceUfrag;
  17455. unifiedLine.icePwd = icePwd;
  17456. unifiedLine.fingerprint = fingerprint;
  17457. unifiedLine.port = port;
  17458. mid2ul[unifiedLine.mid] = unifiedLine;
  17459. }
  17460. });
  17461. }
  17462. });
  17463. // Rebuild the media array in the right order and add the missing mLines
  17464. // (missing from the Plan B SDP).
  17465. session.media = [];
  17466. mids = []; // reuse
  17467. if (desc.type === 'answer') {
  17468. // The media lines in the answer must match the media lines in the
  17469. // offer. The order is important too. Here we assume that Firefox is the
  17470. // answerer, so we merely have to use the reconstructed (unified) answer
  17471. // to update the cached (unified) answer accordingly.
  17472. //
  17473. // In the general case, one would have to use the cached (unified) offer
  17474. // to find the m-lines that are missing from the reconstructed answer,
  17475. // potentially grabbing them from the cached (unified) answer. One has
  17476. // to be carefull with this approach because inactive m-lines do not
  17477. // always have an mid, making it tricky (impossible?) to find where
  17478. // exactly and which m-lines are missing from the reconstructed answer.
  17479. for (var i = 0; i < cached.media.length; i++) {
  17480. var unifiedLine = cached.media[i];
  17481. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  17482. // The mid isn't in the reconstructed (unified) answer.
  17483. // This is either a (unified) m-line containing a remote
  17484. // track only, or a (unified) m-line containing a remote
  17485. // track and a local track that has been removed.
  17486. // In either case, it MUST exist in the cached
  17487. // (unified) answer.
  17488. //
  17489. // In case this is a removed local track, clean-up
  17490. // the (unified) m-line and make sure it's 'recvonly' or
  17491. // 'inactive'.
  17492. delete unifiedLine.msid;
  17493. delete unifiedLine.sources;
  17494. delete unifiedLine.ssrcGroups;
  17495. if (!unifiedLine.direction
  17496. || unifiedLine.direction === 'sendrecv')
  17497. unifiedLine.direction = 'recvonly';
  17498. if (!unifiedLine.direction
  17499. || unifiedLine.direction === 'sendonly')
  17500. unifiedLine.direction = 'inactive';
  17501. } else {
  17502. // This is an (unified) m-line/channel that contains a local
  17503. // track (sendrecv or sendonly channel) or it's a unified
  17504. // recvonly m-line/channel. In either case, since we're
  17505. // going from PlanB -> Unified Plan this m-line MUST
  17506. // exist in the cached answer.
  17507. }
  17508. session.media.push(unifiedLine);
  17509. if (typeof unifiedLine.mid === 'string') {
  17510. // inactive lines don't/may not have an mid.
  17511. mids.push(unifiedLine.mid);
  17512. }
  17513. }
  17514. } else {
  17515. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  17516. // under any circumstances. If we are no longer interested in sending a
  17517. // track, we just remove the msid and ssrc attributes and set it to
  17518. // either a=recvonly (as the reofferer, we must use recvonly if the
  17519. // other side was previously sending on the m-section, but we can also
  17520. // leave the possibility open if it wasn't previously in use), or
  17521. // a=inacive.
  17522. if (typeof cached !== 'undefined' &&
  17523. typeof cached.media !== 'undefined' &&
  17524. Array.isArray(cached.media)) {
  17525. cached.media.forEach(function(unifiedLine) {
  17526. mids.push(unifiedLine.mid);
  17527. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  17528. session.media.push(mid2ul[unifiedLine.mid]);
  17529. } else {
  17530. delete unifiedLine.msid;
  17531. delete unifiedLine.sources;
  17532. delete unifiedLine.ssrcGroups;
  17533. if (!unifiedLine.direction
  17534. || unifiedLine.direction === 'sendrecv')
  17535. unifiedLine.direction = 'recvonly';
  17536. if (!unifiedLine.direction
  17537. || unifiedLine.direction === 'sendonly')
  17538. unifiedLine.direction = 'inactive';
  17539. session.media.push(unifiedLine);
  17540. }
  17541. });
  17542. }
  17543. // Add all the remaining (new) m-lines of the transformed SDP.
  17544. Object.keys(mid2ul).forEach(function(mid) {
  17545. if (mids.indexOf(mid) === -1) {
  17546. mids.push(mid);
  17547. if (typeof mid2ul[mid].direction === 'recvonly') {
  17548. // This is a remote recvonly channel. Add its SSRC to the
  17549. // appropriate sendrecv or sendonly channel.
  17550. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  17551. session.media.some(function (unifiedLine) {
  17552. if ((unifiedLine.direction === 'sendrecv' ||
  17553. unifiedLine.direction === 'sendonly') &&
  17554. unifiedLine.type === mid2ul[mid].type) {
  17555. // mid2ul[mid] shouldn't have any ssrc-groups
  17556. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  17557. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  17558. });
  17559. return true;
  17560. }
  17561. });
  17562. } else {
  17563. session.media.push(mid2ul[mid]);
  17564. }
  17565. }
  17566. });
  17567. }
  17568. // We regenerate the BUNDLE group (since we regenerated the mids)
  17569. session.groups.some(function(group) {
  17570. if (group.type === 'BUNDLE') {
  17571. group.mids = mids.join(' ');
  17572. return true;
  17573. }
  17574. });
  17575. // msid semantic
  17576. session.msidSemantic = {
  17577. semantic: 'WMS',
  17578. token: '*'
  17579. };
  17580. var resStr = transform.write(session);
  17581. // Cache the transformed SDP (Unified Plan) for later re-use in this
  17582. // function.
  17583. this.cache[desc.type] = resStr;
  17584. return new RTCSessionDescription({
  17585. type: desc.type,
  17586. sdp: resStr
  17587. });
  17588. //#endregion
  17589. };
  17590. },{"./array-equals":58,"./transform":61}],61:[function(require,module,exports){
  17591. var transform = require('sdp-transform');
  17592. exports.write = function(session, opts) {
  17593. if (typeof session !== 'undefined' &&
  17594. typeof session.media !== 'undefined' &&
  17595. Array.isArray(session.media)) {
  17596. session.media.forEach(function (mLine) {
  17597. // expand sources to ssrcs
  17598. if (typeof mLine.sources !== 'undefined' &&
  17599. Object.keys(mLine.sources).length !== 0) {
  17600. mLine.ssrcs = [];
  17601. Object.keys(mLine.sources).forEach(function (ssrc) {
  17602. var source = mLine.sources[ssrc];
  17603. Object.keys(source).forEach(function (attribute) {
  17604. mLine.ssrcs.push({
  17605. id: ssrc,
  17606. attribute: attribute,
  17607. value: source[attribute]
  17608. });
  17609. });
  17610. });
  17611. delete mLine.sources;
  17612. }
  17613. // join ssrcs in ssrc groups
  17614. if (typeof mLine.ssrcGroups !== 'undefined' &&
  17615. Array.isArray(mLine.ssrcGroups)) {
  17616. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  17617. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  17618. Array.isArray(ssrcGroup.ssrcs)) {
  17619. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  17620. }
  17621. });
  17622. }
  17623. });
  17624. }
  17625. // join group mids
  17626. if (typeof session !== 'undefined' &&
  17627. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  17628. session.groups.forEach(function (g) {
  17629. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  17630. g.mids = g.mids.join(' ');
  17631. }
  17632. });
  17633. }
  17634. return transform.write(session, opts);
  17635. };
  17636. exports.parse = function(sdp) {
  17637. var session = transform.parse(sdp);
  17638. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  17639. Array.isArray(session.media)) {
  17640. session.media.forEach(function (mLine) {
  17641. // group sources attributes by ssrc
  17642. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  17643. mLine.sources = {};
  17644. mLine.ssrcs.forEach(function (ssrc) {
  17645. if (!mLine.sources[ssrc.id])
  17646. mLine.sources[ssrc.id] = {};
  17647. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  17648. });
  17649. delete mLine.ssrcs;
  17650. }
  17651. // split ssrcs in ssrc groups
  17652. if (typeof mLine.ssrcGroups !== 'undefined' &&
  17653. Array.isArray(mLine.ssrcGroups)) {
  17654. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  17655. if (typeof ssrcGroup.ssrcs === 'string') {
  17656. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  17657. }
  17658. });
  17659. }
  17660. });
  17661. }
  17662. // split group mids
  17663. if (typeof session !== 'undefined' &&
  17664. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  17665. session.groups.forEach(function (g) {
  17666. if (typeof g.mids === 'string') {
  17667. g.mids = g.mids.split(' ');
  17668. }
  17669. });
  17670. }
  17671. return session;
  17672. };
  17673. },{"sdp-transform":63}],62:[function(require,module,exports){
  17674. var grammar = module.exports = {
  17675. v: [{
  17676. name: 'version',
  17677. reg: /^(\d*)$/
  17678. }],
  17679. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  17680. // NB: sessionId will be a String in most cases because it is huge
  17681. name: 'origin',
  17682. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  17683. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  17684. format: "%s %s %d %s IP%d %s"
  17685. }],
  17686. // default parsing of these only (though some of these feel outdated)
  17687. s: [{ name: 'name' }],
  17688. i: [{ name: 'description' }],
  17689. u: [{ name: 'uri' }],
  17690. e: [{ name: 'email' }],
  17691. p: [{ name: 'phone' }],
  17692. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  17693. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  17694. //k: [{}], // outdated thing ignored
  17695. t: [{ //t=0 0
  17696. name: 'timing',
  17697. reg: /^(\d*) (\d*)/,
  17698. names: ['start', 'stop'],
  17699. format: "%d %d"
  17700. }],
  17701. c: [{ //c=IN IP4 10.47.197.26
  17702. name: 'connection',
  17703. reg: /^IN IP(\d) (\S*)/,
  17704. names: ['version', 'ip'],
  17705. format: "IN IP%d %s"
  17706. }],
  17707. b: [{ //b=AS:4000
  17708. push: 'bandwidth',
  17709. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  17710. names: ['type', 'limit'],
  17711. format: "%s:%s"
  17712. }],
  17713. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  17714. // NB: special - pushes to session
  17715. // TODO: rtp/fmtp should be filtered by the payloads found here?
  17716. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  17717. names: ['type', 'port', 'protocol', 'payloads'],
  17718. format: "%s %d %s %s"
  17719. }],
  17720. a: [
  17721. { //a=rtpmap:110 opus/48000/2
  17722. push: 'rtp',
  17723. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  17724. names: ['payload', 'codec', 'rate', 'encoding'],
  17725. format: function (o) {
  17726. return (o.encoding) ?
  17727. "rtpmap:%d %s/%s/%s":
  17728. "rtpmap:%d %s/%s";
  17729. }
  17730. },
  17731. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  17732. push: 'fmtp',
  17733. reg: /^fmtp:(\d*) (\S*)/,
  17734. names: ['payload', 'config'],
  17735. format: "fmtp:%d %s"
  17736. },
  17737. { //a=control:streamid=0
  17738. name: 'control',
  17739. reg: /^control:(.*)/,
  17740. format: "control:%s"
  17741. },
  17742. { //a=rtcp:65179 IN IP4 193.84.77.194
  17743. name: 'rtcp',
  17744. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  17745. names: ['port', 'netType', 'ipVer', 'address'],
  17746. format: function (o) {
  17747. return (o.address != null) ?
  17748. "rtcp:%d %s IP%d %s":
  17749. "rtcp:%d";
  17750. }
  17751. },
  17752. { //a=rtcp-fb:98 trr-int 100
  17753. push: 'rtcpFbTrrInt',
  17754. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  17755. names: ['payload', 'value'],
  17756. format: "rtcp-fb:%d trr-int %d"
  17757. },
  17758. { //a=rtcp-fb:98 nack rpsi
  17759. push: 'rtcpFb',
  17760. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  17761. names: ['payload', 'type', 'subtype'],
  17762. format: function (o) {
  17763. return (o.subtype != null) ?
  17764. "rtcp-fb:%s %s %s":
  17765. "rtcp-fb:%s %s";
  17766. }
  17767. },
  17768. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  17769. //a=extmap:1/recvonly URI-gps-string
  17770. push: 'ext',
  17771. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  17772. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  17773. format: function (o) {
  17774. return (o.config != null) ?
  17775. "extmap:%s %s %s":
  17776. "extmap:%s %s";
  17777. }
  17778. },
  17779. {
  17780. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  17781. push: 'crypto',
  17782. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  17783. names: ['id', 'suite', 'config', 'sessionConfig'],
  17784. format: function (o) {
  17785. return (o.sessionConfig != null) ?
  17786. "crypto:%d %s %s %s":
  17787. "crypto:%d %s %s";
  17788. }
  17789. },
  17790. { //a=setup:actpass
  17791. name: 'setup',
  17792. reg: /^setup:(\w*)/,
  17793. format: "setup:%s"
  17794. },
  17795. { //a=mid:1
  17796. name: 'mid',
  17797. reg: /^mid:([^\s]*)/,
  17798. format: "mid:%s"
  17799. },
  17800. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  17801. name: 'msid',
  17802. reg: /^msid:(.*)/,
  17803. format: "msid:%s"
  17804. },
  17805. { //a=ptime:20
  17806. name: 'ptime',
  17807. reg: /^ptime:(\d*)/,
  17808. format: "ptime:%d"
  17809. },
  17810. { //a=maxptime:60
  17811. name: 'maxptime',
  17812. reg: /^maxptime:(\d*)/,
  17813. format: "maxptime:%d"
  17814. },
  17815. { //a=sendrecv
  17816. name: 'direction',
  17817. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  17818. },
  17819. { //a=ice-lite
  17820. name: 'icelite',
  17821. reg: /^(ice-lite)/
  17822. },
  17823. { //a=ice-ufrag:F7gI
  17824. name: 'iceUfrag',
  17825. reg: /^ice-ufrag:(\S*)/,
  17826. format: "ice-ufrag:%s"
  17827. },
  17828. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  17829. name: 'icePwd',
  17830. reg: /^ice-pwd:(\S*)/,
  17831. format: "ice-pwd:%s"
  17832. },
  17833. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  17834. name: 'fingerprint',
  17835. reg: /^fingerprint:(\S*) (\S*)/,
  17836. names: ['type', 'hash'],
  17837. format: "fingerprint:%s %s"
  17838. },
  17839. {
  17840. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  17841. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  17842. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  17843. push:'candidates',
  17844. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  17845. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  17846. format: function (o) {
  17847. var str = "candidate:%s %d %s %d %s %d typ %s";
  17848. // NB: candidate has two optional chunks, so %void middle one if it's missing
  17849. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  17850. if (o.generation != null) {
  17851. str += " generation %d";
  17852. }
  17853. return str;
  17854. }
  17855. },
  17856. { //a=end-of-candidates (keep after the candidates line for readability)
  17857. name: 'endOfCandidates',
  17858. reg: /^(end-of-candidates)/
  17859. },
  17860. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  17861. name: 'remoteCandidates',
  17862. reg: /^remote-candidates:(.*)/,
  17863. format: "remote-candidates:%s"
  17864. },
  17865. { //a=ice-options:google-ice
  17866. name: 'iceOptions',
  17867. reg: /^ice-options:(\S*)/,
  17868. format: "ice-options:%s"
  17869. },
  17870. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  17871. push: "ssrcs",
  17872. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  17873. names: ['id', 'attribute', 'value'],
  17874. format: "ssrc:%d %s:%s"
  17875. },
  17876. { //a=ssrc-group:FEC 1 2
  17877. push: "ssrcGroups",
  17878. reg: /^ssrc-group:(\w*) (.*)/,
  17879. names: ['semantics', 'ssrcs'],
  17880. format: "ssrc-group:%s %s"
  17881. },
  17882. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  17883. name: "msidSemantic",
  17884. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  17885. names: ['semantic', 'token'],
  17886. format: "msid-semantic: %s %s" // space after ":" is not accidental
  17887. },
  17888. { //a=group:BUNDLE audio video
  17889. push: 'groups',
  17890. reg: /^group:(\w*) (.*)/,
  17891. names: ['type', 'mids'],
  17892. format: "group:%s %s"
  17893. },
  17894. { //a=rtcp-mux
  17895. name: 'rtcpMux',
  17896. reg: /^(rtcp-mux)/
  17897. },
  17898. { //a=rtcp-rsize
  17899. name: 'rtcpRsize',
  17900. reg: /^(rtcp-rsize)/
  17901. },
  17902. { // any a= that we don't understand is kepts verbatim on media.invalid
  17903. push: 'invalid',
  17904. names: ["value"]
  17905. }
  17906. ]
  17907. };
  17908. // set sensible defaults to avoid polluting the grammar with boring details
  17909. Object.keys(grammar).forEach(function (key) {
  17910. var objs = grammar[key];
  17911. objs.forEach(function (obj) {
  17912. if (!obj.reg) {
  17913. obj.reg = /(.*)/;
  17914. }
  17915. if (!obj.format) {
  17916. obj.format = "%s";
  17917. }
  17918. });
  17919. });
  17920. },{}],63:[function(require,module,exports){
  17921. var parser = require('./parser');
  17922. var writer = require('./writer');
  17923. exports.write = writer;
  17924. exports.parse = parser.parse;
  17925. exports.parseFmtpConfig = parser.parseFmtpConfig;
  17926. exports.parsePayloads = parser.parsePayloads;
  17927. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  17928. },{"./parser":64,"./writer":65}],64:[function(require,module,exports){
  17929. var toIntIfInt = function (v) {
  17930. return String(Number(v)) === v ? Number(v) : v;
  17931. };
  17932. var attachProperties = function (match, location, names, rawName) {
  17933. if (rawName && !names) {
  17934. location[rawName] = toIntIfInt(match[1]);
  17935. }
  17936. else {
  17937. for (var i = 0; i < names.length; i += 1) {
  17938. if (match[i+1] != null) {
  17939. location[names[i]] = toIntIfInt(match[i+1]);
  17940. }
  17941. }
  17942. }
  17943. };
  17944. var parseReg = function (obj, location, content) {
  17945. var needsBlank = obj.name && obj.names;
  17946. if (obj.push && !location[obj.push]) {
  17947. location[obj.push] = [];
  17948. }
  17949. else if (needsBlank && !location[obj.name]) {
  17950. location[obj.name] = {};
  17951. }
  17952. var keyLocation = obj.push ?
  17953. {} : // blank object that will be pushed
  17954. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  17955. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  17956. if (obj.push) {
  17957. location[obj.push].push(keyLocation);
  17958. }
  17959. };
  17960. var grammar = require('./grammar');
  17961. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  17962. exports.parse = function (sdp) {
  17963. var session = {}
  17964. , media = []
  17965. , location = session; // points at where properties go under (one of the above)
  17966. // parse lines we understand
  17967. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  17968. var type = l[0];
  17969. var content = l.slice(2);
  17970. if (type === 'm') {
  17971. media.push({rtp: [], fmtp: []});
  17972. location = media[media.length-1]; // point at latest media line
  17973. }
  17974. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  17975. var obj = grammar[type][j];
  17976. if (obj.reg.test(content)) {
  17977. return parseReg(obj, location, content);
  17978. }
  17979. }
  17980. });
  17981. session.media = media; // link it up
  17982. return session;
  17983. };
  17984. var fmtpReducer = function (acc, expr) {
  17985. var s = expr.split('=');
  17986. if (s.length === 2) {
  17987. acc[s[0]] = toIntIfInt(s[1]);
  17988. }
  17989. return acc;
  17990. };
  17991. exports.parseFmtpConfig = function (str) {
  17992. return str.split(';').reduce(fmtpReducer, {});
  17993. };
  17994. exports.parsePayloads = function (str) {
  17995. return str.split(' ').map(Number);
  17996. };
  17997. exports.parseRemoteCandidates = function (str) {
  17998. var candidates = [];
  17999. var parts = str.split(' ').map(toIntIfInt);
  18000. for (var i = 0; i < parts.length; i += 3) {
  18001. candidates.push({
  18002. component: parts[i],
  18003. ip: parts[i + 1],
  18004. port: parts[i + 2]
  18005. });
  18006. }
  18007. return candidates;
  18008. };
  18009. },{"./grammar":62}],65:[function(require,module,exports){
  18010. var grammar = require('./grammar');
  18011. // customized util.format - discards excess arguments and can void middle ones
  18012. var formatRegExp = /%[sdv%]/g;
  18013. var format = function (formatStr) {
  18014. var i = 1;
  18015. var args = arguments;
  18016. var len = args.length;
  18017. return formatStr.replace(formatRegExp, function (x) {
  18018. if (i >= len) {
  18019. return x; // missing argument
  18020. }
  18021. var arg = args[i];
  18022. i += 1;
  18023. switch (x) {
  18024. case '%%':
  18025. return '%';
  18026. case '%s':
  18027. return String(arg);
  18028. case '%d':
  18029. return Number(arg);
  18030. case '%v':
  18031. return '';
  18032. }
  18033. });
  18034. // NB: we discard excess arguments - they are typically undefined from makeLine
  18035. };
  18036. var makeLine = function (type, obj, location) {
  18037. var str = obj.format instanceof Function ?
  18038. (obj.format(obj.push ? location : location[obj.name])) :
  18039. obj.format;
  18040. var args = [type + '=' + str];
  18041. if (obj.names) {
  18042. for (var i = 0; i < obj.names.length; i += 1) {
  18043. var n = obj.names[i];
  18044. if (obj.name) {
  18045. args.push(location[obj.name][n]);
  18046. }
  18047. else { // for mLine and push attributes
  18048. args.push(location[obj.names[i]]);
  18049. }
  18050. }
  18051. }
  18052. else {
  18053. args.push(location[obj.name]);
  18054. }
  18055. return format.apply(null, args);
  18056. };
  18057. // RFC specified order
  18058. // TODO: extend this with all the rest
  18059. var defaultOuterOrder = [
  18060. 'v', 'o', 's', 'i',
  18061. 'u', 'e', 'p', 'c',
  18062. 'b', 't', 'r', 'z', 'a'
  18063. ];
  18064. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  18065. module.exports = function (session, opts) {
  18066. opts = opts || {};
  18067. // ensure certain properties exist
  18068. if (session.version == null) {
  18069. session.version = 0; // "v=0" must be there (only defined version atm)
  18070. }
  18071. if (session.name == null) {
  18072. session.name = " "; // "s= " must be there if no meaningful name set
  18073. }
  18074. session.media.forEach(function (mLine) {
  18075. if (mLine.payloads == null) {
  18076. mLine.payloads = "";
  18077. }
  18078. });
  18079. var outerOrder = opts.outerOrder || defaultOuterOrder;
  18080. var innerOrder = opts.innerOrder || defaultInnerOrder;
  18081. var sdp = [];
  18082. // loop through outerOrder for matching properties on session
  18083. outerOrder.forEach(function (type) {
  18084. grammar[type].forEach(function (obj) {
  18085. if (obj.name in session && session[obj.name] != null) {
  18086. sdp.push(makeLine(type, obj, session));
  18087. }
  18088. else if (obj.push in session && session[obj.push] != null) {
  18089. session[obj.push].forEach(function (el) {
  18090. sdp.push(makeLine(type, obj, el));
  18091. });
  18092. }
  18093. });
  18094. });
  18095. // then for each media line, follow the innerOrder
  18096. session.media.forEach(function (mLine) {
  18097. sdp.push(makeLine('m', grammar.m[0], mLine));
  18098. innerOrder.forEach(function (type) {
  18099. grammar[type].forEach(function (obj) {
  18100. if (obj.name in mLine && mLine[obj.name] != null) {
  18101. sdp.push(makeLine(type, obj, mLine));
  18102. }
  18103. else if (obj.push in mLine && mLine[obj.push] != null) {
  18104. mLine[obj.push].forEach(function (el) {
  18105. sdp.push(makeLine(type, obj, el));
  18106. });
  18107. }
  18108. });
  18109. });
  18110. });
  18111. return sdp.join('\r\n') + '\r\n';
  18112. };
  18113. },{"./grammar":62}],66:[function(require,module,exports){
  18114. var transform = require('sdp-transform');
  18115. var transformUtils = require('./transform-utils');
  18116. var parseSsrcs = transformUtils.parseSsrcs;
  18117. var writeSsrcs = transformUtils.writeSsrcs;
  18118. //region Constants
  18119. var DEFAULT_NUM_OF_LAYERS = 3;
  18120. //endregion
  18121. //region Ctor
  18122. function Simulcast(options) {
  18123. this.options = options ? options : {};
  18124. if (!this.options.numOfLayers) {
  18125. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  18126. }
  18127. this.layers = [];
  18128. }
  18129. //endregion
  18130. //region Stateless private utility functions
  18131. /**
  18132. * Returns a random integer between min (included) and max (excluded)
  18133. * Using Math.round() gives a non-uniform distribution!
  18134. * @returns {number}
  18135. */
  18136. function generateSSRC() {
  18137. var min = 0, max = 0xffffffff;
  18138. return Math.floor(Math.random() * (max - min)) + min;
  18139. };
  18140. function processVideo(session, action) {
  18141. if (session == null || !Array.isArray(session.media)) {
  18142. return;
  18143. }
  18144. session.media.forEach(function (mLine) {
  18145. if (mLine.type === 'video') {
  18146. action(mLine);
  18147. }
  18148. });
  18149. }
  18150. function validateDescription(desc)
  18151. {
  18152. return desc && desc != null
  18153. && desc.type && desc.type != ''
  18154. && desc.sdp && desc.sdp != '';
  18155. }
  18156. function explodeRemoteSimulcast(mLine) {
  18157. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  18158. return;
  18159. }
  18160. var sources = parseSsrcs(mLine);
  18161. var order = [];
  18162. // Find the SIM group and explode its sources.
  18163. var j = mLine.ssrcGroups.length;
  18164. while (j--) {
  18165. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  18166. continue;
  18167. }
  18168. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  18169. for (var i = 0; i < simulcastSsrcs.length; i++) {
  18170. var ssrc = simulcastSsrcs[i];
  18171. order.push(ssrc);
  18172. var parts = sources[ssrc].msid.split(' ');
  18173. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  18174. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  18175. // Remove all the groups that this SSRC participates in.
  18176. mLine.ssrcGroups.forEach(function (relatedGroup) {
  18177. if (relatedGroup.semantics === 'SIM') {
  18178. return;
  18179. }
  18180. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  18181. if (relatedSsrcs.indexOf(ssrc) === -1) {
  18182. return;
  18183. }
  18184. // Nuke all the related SSRCs.
  18185. relatedSsrcs.forEach(function (relatedSSRC) {
  18186. sources[relatedSSRC].msid = sources[ssrc].msid;
  18187. sources[relatedSSRC].cname = sources[ssrc].cname;
  18188. if (relatedSSRC !== ssrc) {
  18189. order.push(relatedSSRC);
  18190. }
  18191. });
  18192. // Schedule the related group for nuking.
  18193. })
  18194. }
  18195. mLine.ssrcs = writeSsrcs(sources, order);
  18196. mLine.ssrcGroups.splice(j, 1);
  18197. };
  18198. }
  18199. function squeezeRemoteSimulcast(mLine) {
  18200. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  18201. return;
  18202. }
  18203. var sources = parseSsrcs(mLine);
  18204. // Find the SIM group and nuke it.
  18205. mLine.ssrcGroups.some(function (simulcastGroup) {
  18206. if (simulcastGroup.semantics !== 'SIM') {
  18207. return false;
  18208. }
  18209. // Schedule the SIM group for nuking.
  18210. simulcastGroup.nuke = true;
  18211. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  18212. // Nuke all the higher layer SSRCs.
  18213. for (var i = 1; i < simulcastSsrcs.length; i++) {
  18214. var ssrc = simulcastSsrcs[i];
  18215. delete sources[ssrc];
  18216. // Remove all the groups that this SSRC participates in.
  18217. mLine.ssrcGroups.forEach(function (relatedGroup) {
  18218. if (relatedGroup.semantics === 'SIM') {
  18219. return;
  18220. }
  18221. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  18222. if (relatedSsrcs.indexOf(ssrc) === -1) {
  18223. return;
  18224. }
  18225. // Nuke all the related SSRCs.
  18226. relatedSsrcs.forEach(function (relatedSSRC) {
  18227. delete sources[relatedSSRC];
  18228. });
  18229. // Schedule the related group for nuking.
  18230. relatedGroup.nuke = true;
  18231. })
  18232. }
  18233. return true;
  18234. });
  18235. mLine.ssrcs = writeSsrcs(sources);
  18236. // Nuke all the scheduled groups.
  18237. var i = mLine.ssrcGroups.length;
  18238. while (i--) {
  18239. if (mLine.ssrcGroups[i].nuke) {
  18240. mLine.ssrcGroups.splice(i, 1);
  18241. }
  18242. }
  18243. }
  18244. function removeGoogConference(mLine) {
  18245. if (!mLine || !Array.isArray(mLine.invalid)) {
  18246. return;
  18247. }
  18248. var i = mLine.invalid.length;
  18249. while (i--) {
  18250. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  18251. mLine.invalid.splice(i, 1);
  18252. }
  18253. }
  18254. }
  18255. function assertGoogConference(mLine) {
  18256. if (!mLine) {
  18257. return;
  18258. }
  18259. if (!Array.isArray(mLine.invalid)) {
  18260. mLine.invalid = [];
  18261. }
  18262. if (!mLine.invalid.some(
  18263. function (i) { return i.value === 'x-google-flag:conference' })) {
  18264. mLine.invalid.push({'value': 'x-google-flag:conference'});
  18265. }
  18266. }
  18267. //endregion
  18268. //region "Private" functions
  18269. /**
  18270. *
  18271. * @param mLine
  18272. * @private
  18273. */
  18274. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  18275. if (!mLine || mLine.type !== 'video') {
  18276. return;
  18277. }
  18278. var sources = parseSsrcs(mLine);
  18279. if (Object.keys(sources).length === 0) {
  18280. // no sources, disable simulcast.
  18281. if (this.layers.length !== 0) {
  18282. this.layers = [];
  18283. }
  18284. return;
  18285. }
  18286. // find the base layer (we'll reuse its msid and cname).
  18287. var baseLayerSSRC = Object.keys(sources)[0];
  18288. var baseLayer = sources[baseLayerSSRC];
  18289. // todo(gp) handle screen sharing.
  18290. // check if base CNAME has changed and reinitialise layers.
  18291. if (this.layers.length > 0
  18292. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  18293. this.layers = [];
  18294. }
  18295. // (re)initialise layers
  18296. if (this.layers.length < 1) {
  18297. // first push the base layer.
  18298. this.layers.push({
  18299. ssrc: baseLayerSSRC,
  18300. msid: baseLayer.msid,
  18301. cname: baseLayer.cname
  18302. });
  18303. var rtx = false; // RFC 4588
  18304. if (Array.isArray(mLine.rtp)) {
  18305. rtx = mLine.rtp.some(
  18306. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  18307. }
  18308. if (rtx) {
  18309. this.layers[0].rtx = generateSSRC();
  18310. }
  18311. // now push additional layers.
  18312. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  18313. var layer = { ssrc: generateSSRC() };
  18314. if (rtx) {
  18315. layer.rtx = generateSSRC();
  18316. }
  18317. this.layers.push(layer);
  18318. }
  18319. }
  18320. };
  18321. /**
  18322. *
  18323. * @param mLine
  18324. * @private
  18325. */
  18326. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  18327. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  18328. var sources = {};
  18329. var msid = this.layers[0].msid;
  18330. var cname = this.layers[0].cname;
  18331. var simulcastSsrcs = [];
  18332. var ssrcGroups = [];
  18333. for (var i = 0; i < this.layers.length; i++) {
  18334. var layer = this.layers[i];
  18335. sources[layer.ssrc] = { msid: msid, cname: cname };
  18336. simulcastSsrcs.push(layer.ssrc);
  18337. if (layer.rtx) {
  18338. sources[layer.rtx] = {
  18339. msid: msid,
  18340. cname: cname
  18341. }
  18342. ssrcGroups.push({
  18343. semantics: 'FID',
  18344. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  18345. });
  18346. }
  18347. }
  18348. ssrcGroups.push({
  18349. semantics: 'SIM',
  18350. ssrcs: simulcastSsrcs.join(' ')
  18351. });
  18352. mLine.ssrcGroups = ssrcGroups;
  18353. mLine.ssrcs = writeSsrcs(sources);
  18354. }
  18355. }
  18356. //endregion
  18357. //region "Public" functions
  18358. Simulcast.prototype.isSupported = function () {
  18359. return window.chrome;
  18360. // TODO this needs improvements. For example I doubt that Chrome in Android
  18361. // has simulcast support. Also, only recent versions of Chromium have native
  18362. // simulcast support.
  18363. }
  18364. /**
  18365. *
  18366. * @param desc
  18367. * @returns {RTCSessionDescription}
  18368. */
  18369. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  18370. if (!validateDescription(desc)) {
  18371. return desc;
  18372. }
  18373. var session = transform.parse(desc.sdp);
  18374. var self = this;
  18375. processVideo(session, function (mLine) {
  18376. // Handle simulcast reception.
  18377. if (self.options.explodeRemoteSimulcast) {
  18378. explodeRemoteSimulcast(mLine);
  18379. } else {
  18380. squeezeRemoteSimulcast(mLine);
  18381. }
  18382. // If native simulcast is enabled, we must append the x-goog-conference
  18383. // attribute to the SDP.
  18384. if (self.layers.length < 1) {
  18385. removeGoogConference(mLine);
  18386. } else {
  18387. assertGoogConference(mLine);
  18388. }
  18389. });
  18390. return new RTCSessionDescription({
  18391. type: desc.type,
  18392. sdp: transform.write(session)
  18393. });
  18394. };
  18395. /**
  18396. *
  18397. * @param desc
  18398. * @returns {RTCSessionDescription}
  18399. */
  18400. Simulcast.prototype.mungeLocalDescription = function (desc) {
  18401. if (!validateDescription(desc) || !this.isSupported()) {
  18402. return desc;
  18403. }
  18404. var session = transform.parse(desc.sdp);
  18405. var self = this;
  18406. processVideo(session, function (mLine) {
  18407. // Initialize native simulcast layers, if not already done.
  18408. self._maybeInitializeLayers(mLine);
  18409. // Update the SDP with the simulcast layers.
  18410. self._restoreSimulcastView(mLine);
  18411. });
  18412. return new RTCSessionDescription({
  18413. type: desc.type,
  18414. sdp: transform.write(session)
  18415. });
  18416. };
  18417. //endregion
  18418. module.exports = Simulcast;
  18419. },{"./transform-utils":67,"sdp-transform":69}],67:[function(require,module,exports){
  18420. exports.writeSsrcs = function(sources, order) {
  18421. var ssrcs = [];
  18422. // expand sources to ssrcs
  18423. if (typeof sources !== 'undefined' &&
  18424. Object.keys(sources).length !== 0) {
  18425. if (Array.isArray(order)) {
  18426. for (var i = 0; i < order.length; i++) {
  18427. var ssrc = order[i];
  18428. var source = sources[ssrc];
  18429. Object.keys(source).forEach(function (attribute) {
  18430. ssrcs.push({
  18431. id: ssrc,
  18432. attribute: attribute,
  18433. value: source[attribute]
  18434. });
  18435. });
  18436. }
  18437. } else {
  18438. Object.keys(sources).forEach(function (ssrc) {
  18439. var source = sources[ssrc];
  18440. Object.keys(source).forEach(function (attribute) {
  18441. ssrcs.push({
  18442. id: ssrc,
  18443. attribute: attribute,
  18444. value: source[attribute]
  18445. });
  18446. });
  18447. });
  18448. }
  18449. }
  18450. return ssrcs;
  18451. };
  18452. exports.parseSsrcs = function (mLine) {
  18453. var sources = {};
  18454. // group sources attributes by ssrc.
  18455. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  18456. mLine.ssrcs.forEach(function (ssrc) {
  18457. if (!sources[ssrc.id])
  18458. sources[ssrc.id] = {};
  18459. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  18460. });
  18461. }
  18462. return sources;
  18463. };
  18464. },{}],68:[function(require,module,exports){
  18465. arguments[4][62][0].apply(exports,arguments)
  18466. },{"dup":62}],69:[function(require,module,exports){
  18467. arguments[4][63][0].apply(exports,arguments)
  18468. },{"./parser":70,"./writer":71,"dup":63}],70:[function(require,module,exports){
  18469. arguments[4][64][0].apply(exports,arguments)
  18470. },{"./grammar":68,"dup":64}],71:[function(require,module,exports){
  18471. arguments[4][65][0].apply(exports,arguments)
  18472. },{"./grammar":68,"dup":65}],72:[function(require,module,exports){
  18473. var grammar = module.exports = {
  18474. v: [{
  18475. name: 'version',
  18476. reg: /^(\d*)$/
  18477. }],
  18478. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  18479. // NB: sessionId will be a String in most cases because it is huge
  18480. name: 'origin',
  18481. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  18482. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  18483. format: "%s %s %d %s IP%d %s"
  18484. }],
  18485. // default parsing of these only (though some of these feel outdated)
  18486. s: [{ name: 'name' }],
  18487. i: [{ name: 'description' }],
  18488. u: [{ name: 'uri' }],
  18489. e: [{ name: 'email' }],
  18490. p: [{ name: 'phone' }],
  18491. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  18492. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  18493. //k: [{}], // outdated thing ignored
  18494. t: [{ //t=0 0
  18495. name: 'timing',
  18496. reg: /^(\d*) (\d*)/,
  18497. names: ['start', 'stop'],
  18498. format: "%d %d"
  18499. }],
  18500. c: [{ //c=IN IP4 10.47.197.26
  18501. name: 'connection',
  18502. reg: /^IN IP(\d) (\S*)/,
  18503. names: ['version', 'ip'],
  18504. format: "IN IP%d %s"
  18505. }],
  18506. b: [{ //b=AS:4000
  18507. push: 'bandwidth',
  18508. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  18509. names: ['type', 'limit'],
  18510. format: "%s:%s"
  18511. }],
  18512. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  18513. // NB: special - pushes to session
  18514. // TODO: rtp/fmtp should be filtered by the payloads found here?
  18515. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  18516. names: ['type', 'port', 'protocol', 'payloads'],
  18517. format: "%s %d %s %s"
  18518. }],
  18519. a: [
  18520. { //a=rtpmap:110 opus/48000/2
  18521. push: 'rtp',
  18522. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  18523. names: ['payload', 'codec', 'rate', 'encoding'],
  18524. format: function (o) {
  18525. return (o.encoding) ?
  18526. "rtpmap:%d %s/%s/%s":
  18527. "rtpmap:%d %s/%s";
  18528. }
  18529. },
  18530. {
  18531. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  18532. //a=fmtp:111 minptime=10; useinbandfec=1
  18533. push: 'fmtp',
  18534. reg: /^fmtp:(\d*) ([\S| ]*)/,
  18535. names: ['payload', 'config'],
  18536. format: "fmtp:%d %s"
  18537. },
  18538. { //a=control:streamid=0
  18539. name: 'control',
  18540. reg: /^control:(.*)/,
  18541. format: "control:%s"
  18542. },
  18543. { //a=rtcp:65179 IN IP4 193.84.77.194
  18544. name: 'rtcp',
  18545. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  18546. names: ['port', 'netType', 'ipVer', 'address'],
  18547. format: function (o) {
  18548. return (o.address != null) ?
  18549. "rtcp:%d %s IP%d %s":
  18550. "rtcp:%d";
  18551. }
  18552. },
  18553. { //a=rtcp-fb:98 trr-int 100
  18554. push: 'rtcpFbTrrInt',
  18555. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  18556. names: ['payload', 'value'],
  18557. format: "rtcp-fb:%d trr-int %d"
  18558. },
  18559. { //a=rtcp-fb:98 nack rpsi
  18560. push: 'rtcpFb',
  18561. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  18562. names: ['payload', 'type', 'subtype'],
  18563. format: function (o) {
  18564. return (o.subtype != null) ?
  18565. "rtcp-fb:%s %s %s":
  18566. "rtcp-fb:%s %s";
  18567. }
  18568. },
  18569. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  18570. //a=extmap:1/recvonly URI-gps-string
  18571. push: 'ext',
  18572. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  18573. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  18574. format: function (o) {
  18575. return (o.config != null) ?
  18576. "extmap:%s %s %s":
  18577. "extmap:%s %s";
  18578. }
  18579. },
  18580. {
  18581. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  18582. push: 'crypto',
  18583. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  18584. names: ['id', 'suite', 'config', 'sessionConfig'],
  18585. format: function (o) {
  18586. return (o.sessionConfig != null) ?
  18587. "crypto:%d %s %s %s":
  18588. "crypto:%d %s %s";
  18589. }
  18590. },
  18591. { //a=setup:actpass
  18592. name: 'setup',
  18593. reg: /^setup:(\w*)/,
  18594. format: "setup:%s"
  18595. },
  18596. { //a=mid:1
  18597. name: 'mid',
  18598. reg: /^mid:([^\s]*)/,
  18599. format: "mid:%s"
  18600. },
  18601. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  18602. name: 'msid',
  18603. reg: /^msid:(.*)/,
  18604. format: "msid:%s"
  18605. },
  18606. { //a=ptime:20
  18607. name: 'ptime',
  18608. reg: /^ptime:(\d*)/,
  18609. format: "ptime:%d"
  18610. },
  18611. { //a=maxptime:60
  18612. name: 'maxptime',
  18613. reg: /^maxptime:(\d*)/,
  18614. format: "maxptime:%d"
  18615. },
  18616. { //a=sendrecv
  18617. name: 'direction',
  18618. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  18619. },
  18620. { //a=ice-lite
  18621. name: 'icelite',
  18622. reg: /^(ice-lite)/
  18623. },
  18624. { //a=ice-ufrag:F7gI
  18625. name: 'iceUfrag',
  18626. reg: /^ice-ufrag:(\S*)/,
  18627. format: "ice-ufrag:%s"
  18628. },
  18629. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  18630. name: 'icePwd',
  18631. reg: /^ice-pwd:(\S*)/,
  18632. format: "ice-pwd:%s"
  18633. },
  18634. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  18635. name: 'fingerprint',
  18636. reg: /^fingerprint:(\S*) (\S*)/,
  18637. names: ['type', 'hash'],
  18638. format: "fingerprint:%s %s"
  18639. },
  18640. {
  18641. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  18642. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  18643. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  18644. push:'candidates',
  18645. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  18646. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  18647. format: function (o) {
  18648. var str = "candidate:%s %d %s %d %s %d typ %s";
  18649. // NB: candidate has two optional chunks, so %void middle one if it's missing
  18650. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  18651. if (o.generation != null) {
  18652. str += " generation %d";
  18653. }
  18654. return str;
  18655. }
  18656. },
  18657. { //a=end-of-candidates (keep after the candidates line for readability)
  18658. name: 'endOfCandidates',
  18659. reg: /^(end-of-candidates)/
  18660. },
  18661. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  18662. name: 'remoteCandidates',
  18663. reg: /^remote-candidates:(.*)/,
  18664. format: "remote-candidates:%s"
  18665. },
  18666. { //a=ice-options:google-ice
  18667. name: 'iceOptions',
  18668. reg: /^ice-options:(\S*)/,
  18669. format: "ice-options:%s"
  18670. },
  18671. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  18672. push: "ssrcs",
  18673. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  18674. names: ['id', 'attribute', 'value'],
  18675. format: "ssrc:%d %s:%s"
  18676. },
  18677. { //a=ssrc-group:FEC 1 2
  18678. push: "ssrcGroups",
  18679. reg: /^ssrc-group:(\w*) (.*)/,
  18680. names: ['semantics', 'ssrcs'],
  18681. format: "ssrc-group:%s %s"
  18682. },
  18683. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  18684. name: "msidSemantic",
  18685. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  18686. names: ['semantic', 'token'],
  18687. format: "msid-semantic: %s %s" // space after ":" is not accidental
  18688. },
  18689. { //a=group:BUNDLE audio video
  18690. push: 'groups',
  18691. reg: /^group:(\w*) (.*)/,
  18692. names: ['type', 'mids'],
  18693. format: "group:%s %s"
  18694. },
  18695. { //a=rtcp-mux
  18696. name: 'rtcpMux',
  18697. reg: /^(rtcp-mux)/
  18698. },
  18699. { //a=rtcp-rsize
  18700. name: 'rtcpRsize',
  18701. reg: /^(rtcp-rsize)/
  18702. },
  18703. { // any a= that we don't understand is kepts verbatim on media.invalid
  18704. push: 'invalid',
  18705. names: ["value"]
  18706. }
  18707. ]
  18708. };
  18709. // set sensible defaults to avoid polluting the grammar with boring details
  18710. Object.keys(grammar).forEach(function (key) {
  18711. var objs = grammar[key];
  18712. objs.forEach(function (obj) {
  18713. if (!obj.reg) {
  18714. obj.reg = /(.*)/;
  18715. }
  18716. if (!obj.format) {
  18717. obj.format = "%s";
  18718. }
  18719. });
  18720. });
  18721. },{}],73:[function(require,module,exports){
  18722. arguments[4][63][0].apply(exports,arguments)
  18723. },{"./parser":74,"./writer":75,"dup":63}],74:[function(require,module,exports){
  18724. var toIntIfInt = function (v) {
  18725. return String(Number(v)) === v ? Number(v) : v;
  18726. };
  18727. var attachProperties = function (match, location, names, rawName) {
  18728. if (rawName && !names) {
  18729. location[rawName] = toIntIfInt(match[1]);
  18730. }
  18731. else {
  18732. for (var i = 0; i < names.length; i += 1) {
  18733. if (match[i+1] != null) {
  18734. location[names[i]] = toIntIfInt(match[i+1]);
  18735. }
  18736. }
  18737. }
  18738. };
  18739. var parseReg = function (obj, location, content) {
  18740. var needsBlank = obj.name && obj.names;
  18741. if (obj.push && !location[obj.push]) {
  18742. location[obj.push] = [];
  18743. }
  18744. else if (needsBlank && !location[obj.name]) {
  18745. location[obj.name] = {};
  18746. }
  18747. var keyLocation = obj.push ?
  18748. {} : // blank object that will be pushed
  18749. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  18750. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  18751. if (obj.push) {
  18752. location[obj.push].push(keyLocation);
  18753. }
  18754. };
  18755. var grammar = require('./grammar');
  18756. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  18757. exports.parse = function (sdp) {
  18758. var session = {}
  18759. , media = []
  18760. , location = session; // points at where properties go under (one of the above)
  18761. // parse lines we understand
  18762. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  18763. var type = l[0];
  18764. var content = l.slice(2);
  18765. if (type === 'm') {
  18766. media.push({rtp: [], fmtp: []});
  18767. location = media[media.length-1]; // point at latest media line
  18768. }
  18769. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  18770. var obj = grammar[type][j];
  18771. if (obj.reg.test(content)) {
  18772. return parseReg(obj, location, content);
  18773. }
  18774. }
  18775. });
  18776. session.media = media; // link it up
  18777. return session;
  18778. };
  18779. var fmtpReducer = function (acc, expr) {
  18780. var s = expr.split('=');
  18781. if (s.length === 2) {
  18782. acc[s[0]] = toIntIfInt(s[1]);
  18783. }
  18784. return acc;
  18785. };
  18786. exports.parseFmtpConfig = function (str) {
  18787. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  18788. };
  18789. exports.parsePayloads = function (str) {
  18790. return str.split(' ').map(Number);
  18791. };
  18792. exports.parseRemoteCandidates = function (str) {
  18793. var candidates = [];
  18794. var parts = str.split(' ').map(toIntIfInt);
  18795. for (var i = 0; i < parts.length; i += 3) {
  18796. candidates.push({
  18797. component: parts[i],
  18798. ip: parts[i + 1],
  18799. port: parts[i + 2]
  18800. });
  18801. }
  18802. return candidates;
  18803. };
  18804. },{"./grammar":72}],75:[function(require,module,exports){
  18805. arguments[4][65][0].apply(exports,arguments)
  18806. },{"./grammar":72,"dup":65}],76:[function(require,module,exports){
  18807. var MediaStreamType = {
  18808. VIDEO_TYPE: "Video",
  18809. AUDIO_TYPE: "Audio"
  18810. };
  18811. module.exports = MediaStreamType;
  18812. },{}],77:[function(require,module,exports){
  18813. var RTCEvents = {
  18814. RTC_READY: "rtc.ready",
  18815. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  18816. LASTN_CHANGED: "rtc.lastn_changed",
  18817. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  18818. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  18819. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  18820. };
  18821. module.exports = RTCEvents;
  18822. },{}],78:[function(require,module,exports){
  18823. var Resolutions = {
  18824. "1080": {
  18825. width: 1920,
  18826. height: 1080,
  18827. order: 7
  18828. },
  18829. "fullhd": {
  18830. width: 1920,
  18831. height: 1080,
  18832. order: 7
  18833. },
  18834. "720": {
  18835. width: 1280,
  18836. height: 720,
  18837. order: 6
  18838. },
  18839. "hd": {
  18840. width: 1280,
  18841. height: 720,
  18842. order: 6
  18843. },
  18844. "960": {
  18845. width: 960,
  18846. height: 720,
  18847. order: 5
  18848. },
  18849. "640": {
  18850. width: 640,
  18851. height: 480,
  18852. order: 4
  18853. },
  18854. "vga": {
  18855. width: 640,
  18856. height: 480,
  18857. order: 4
  18858. },
  18859. "360": {
  18860. width: 640,
  18861. height: 360,
  18862. order: 3
  18863. },
  18864. "320": {
  18865. width: 320,
  18866. height: 240,
  18867. order: 2
  18868. },
  18869. "180": {
  18870. width: 320,
  18871. height: 180,
  18872. order: 1
  18873. }
  18874. };
  18875. module.exports = Resolutions;
  18876. },{}],79:[function(require,module,exports){
  18877. var StreamEventTypes = {
  18878. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  18879. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  18880. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  18881. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  18882. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  18883. TRACK_MUTE_CHANGED: "rtc.track_mute_changed"
  18884. };
  18885. module.exports = StreamEventTypes;
  18886. },{}],80:[function(require,module,exports){
  18887. var AuthenticationEvents = {
  18888. /**
  18889. * Event callback arguments:
  18890. * function(authenticationEnabled, userIdentity)
  18891. * authenticationEnabled - indicates whether authentication has been enabled
  18892. * in this session
  18893. * userIdentity - if user has been logged in then it contains user name. If
  18894. * contains 'null' or 'undefined' then user is not logged in.
  18895. */
  18896. IDENTITY_UPDATED: "authentication.identity_updated"
  18897. };
  18898. module.exports = AuthenticationEvents;
  18899. },{}],81:[function(require,module,exports){
  18900. var DesktopSharingEventTypes = {
  18901. INIT: "ds.init",
  18902. SWITCHING_DONE: "ds.switching_done",
  18903. NEW_STREAM_CREATED: "ds.new_stream_created"
  18904. };
  18905. module.exports = DesktopSharingEventTypes;
  18906. },{}],82:[function(require,module,exports){
  18907. var Constants = {
  18908. LOCAL_JID: 'local'
  18909. };
  18910. module.exports = Constants;
  18911. },{}],83:[function(require,module,exports){
  18912. var XMPPEvents = {
  18913. CONNECTION_FAILED: "xmpp.connection.failed",
  18914. // Indicates an interrupted connection event.
  18915. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  18916. // Indicates a restored connection event.
  18917. CONNECTION_RESTORED: "xmpp.connection.restored",
  18918. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  18919. CALL_INCOMING: "xmpp.callincoming.jingle",
  18920. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  18921. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  18922. KICKED: "xmpp.kicked",
  18923. BRIDGE_DOWN: "xmpp.bridge_down",
  18924. USER_ID_CHANGED: "xmpp.user_id_changed",
  18925. // We joined the MUC
  18926. MUC_JOINED: "xmpp.muc_joined",
  18927. // A member joined the MUC
  18928. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  18929. // A member left the MUC
  18930. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  18931. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  18932. MUC_DESTROYED: "xmpp.muc_destroyed",
  18933. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  18934. REMOTE_STATS: "xmpp.remote_stats",
  18935. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  18936. PRESENCE_STATUS: "xmpp.presence_status",
  18937. RESERVATION_ERROR: "xmpp.room_reservation_error",
  18938. SUBJECT_CHANGED: "xmpp.subject_changed",
  18939. MESSAGE_RECEIVED: "xmpp.message_received",
  18940. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  18941. PASSWORD_REQUIRED: "xmpp.password_required",
  18942. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  18943. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  18944. ETHERPAD: "xmpp.etherpad",
  18945. DEVICE_AVAILABLE: "xmpp.device_available",
  18946. VIDEO_TYPE: "xmpp.video_type",
  18947. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  18948. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  18949. AUDIO_MUTED: "xmpp.audio_muted",
  18950. VIDEO_MUTED: "xmpp.video_muted",
  18951. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  18952. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  18953. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  18954. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  18955. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  18956. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  18957. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  18958. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  18959. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  18960. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  18961. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  18962. // xmpp is connected and obtained user media
  18963. READY_TO_JOIN: 'xmpp.ready_to_join',
  18964. FOCUS_LEFT: "xmpp.focus_left",
  18965. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received"
  18966. };
  18967. module.exports = XMPPEvents;
  18968. },{}]},{},[7])(7)
  18969. });