選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

lib-jitsi-meet.js 748KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946
  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. (function (__filename){
  3. /* global Strophe, $ */
  4. /* jshint -W101 */
  5. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6. var RTC = require("./modules/RTC/RTC");
  7. var XMPPEvents = require("./service/xmpp/XMPPEvents");
  8. var StreamEventTypes = require("./service/RTC/StreamEventTypes");
  9. var RTCEvents = require("./service/RTC/RTCEvents");
  10. var EventEmitter = require("events");
  11. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  12. var JitsiParticipant = require("./JitsiParticipant");
  13. var Statistics = require("./modules/statistics/statistics");
  14. var JitsiDTMFManager = require('./modules/DTMF/JitsiDTMFManager');
  15. /**
  16. * Creates a JitsiConference object with the given name and properties.
  17. * Note: this constructor is not a part of the public API (objects should be
  18. * created using JitsiConnection.createConference).
  19. * @param options.config properties / settings related to the conference that will be created.
  20. * @param options.name the name of the conference
  21. * @param options.connection the JitsiConnection object for this JitsiConference.
  22. * @constructor
  23. */
  24. function JitsiConference(options) {
  25. if(!options.name || options.name.toLowerCase() !== options.name) {
  26. logger.error("Invalid conference name (no conference name passed or it"
  27. + "contains invalid characters like capital letters)!");
  28. return;
  29. }
  30. this.options = options;
  31. this.connection = this.options.connection;
  32. this.xmpp = this.connection.xmpp;
  33. this.eventEmitter = new EventEmitter();
  34. this.room = this.xmpp.createRoom(this.options.name, null, null, this.options.config);
  35. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  36. this.rtc = new RTC(this.room, options);
  37. if(!options.config.disableAudioLevels)
  38. this.statistics = new Statistics();
  39. setupListeners(this);
  40. this.participants = {};
  41. this.lastActiveSpeaker = null;
  42. this.dtmfManager = null;
  43. this.somebodySupportsDTMF = false;
  44. }
  45. /**
  46. * Joins the conference.
  47. * @param password {string} the password
  48. */
  49. JitsiConference.prototype.join = function (password) {
  50. if(this.room)
  51. this.room.join(password, this.connection.tokenPassword);
  52. };
  53. /**
  54. * Leaves the conference.
  55. */
  56. JitsiConference.prototype.leave = function () {
  57. if(this.xmpp)
  58. this.xmpp.leaveRoom(this.room.roomjid);
  59. this.room = null;
  60. };
  61. /**
  62. * Returns the local tracks.
  63. */
  64. JitsiConference.prototype.getLocalTracks = function () {
  65. if (this.rtc) {
  66. return this.rtc.localStreams;
  67. } else {
  68. return [];
  69. }
  70. };
  71. /**
  72. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  73. * in JitsiConferenceEvents.
  74. * @param eventId the event ID.
  75. * @param handler handler for the event.
  76. *
  77. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  78. */
  79. JitsiConference.prototype.on = function (eventId, handler) {
  80. if(this.eventEmitter)
  81. this.eventEmitter.on(eventId, handler);
  82. };
  83. /**
  84. * Removes event listener
  85. * @param eventId the event ID.
  86. * @param [handler] optional, the specific handler to unbind
  87. *
  88. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  89. */
  90. JitsiConference.prototype.off = function (eventId, handler) {
  91. if(this.eventEmitter)
  92. this.eventEmitter.removeListener(eventId, handler);
  93. };
  94. // Common aliases for event emitter
  95. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  96. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  97. /**
  98. * Receives notifications from another participants for commands / custom events(send by sendPresenceCommand method).
  99. * @param command {String} the name of the command
  100. * @param handler {Function} handler for the command
  101. */
  102. JitsiConference.prototype.addCommandListener = function (command, handler) {
  103. if(this.room)
  104. this.room.addPresenceListener(command, handler);
  105. };
  106. /**
  107. * Removes command listener
  108. * @param command {String} the name of the command
  109. */
  110. JitsiConference.prototype.removeCommandListener = function (command) {
  111. if(this.room)
  112. this.room.removePresenceListener(command);
  113. };
  114. /**
  115. * Sends text message to the other participants in the conference
  116. * @param message the text message.
  117. */
  118. JitsiConference.prototype.sendTextMessage = function (message) {
  119. if(this.room)
  120. this.room.sendMessage(message);
  121. };
  122. /**
  123. * Send presence command.
  124. * @param name the name of the command.
  125. * @param values Object with keys and values that will be send.
  126. **/
  127. JitsiConference.prototype.sendCommand = function (name, values) {
  128. if(this.room) {
  129. this.room.addToPresence(name, values);
  130. this.room.sendPresence();
  131. }
  132. };
  133. /**
  134. * Send presence command one time.
  135. * @param name the name of the command.
  136. * @param values Object with keys and values that will be send.
  137. **/
  138. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  139. this.sendCommand(name, values);
  140. this.removeCommand(name);
  141. };
  142. /**
  143. * Send presence command.
  144. * @param name the name of the command.
  145. * @param values Object with keys and values that will be send.
  146. * @param persistent if false the command will be sent only one time
  147. **/
  148. JitsiConference.prototype.removeCommand = function (name) {
  149. if(this.room)
  150. this.room.removeFromPresence(name);
  151. };
  152. /**
  153. * Sets the display name for this conference.
  154. * @param name the display name to set
  155. */
  156. JitsiConference.prototype.setDisplayName = function(name) {
  157. if(this.room){
  158. this.room.addToPresence("nick", {
  159. attributes: {
  160. xmlns: 'http://jabber.org/protocol/nick'
  161. }, value: name
  162. });
  163. this.room.sendPresence();
  164. }
  165. };
  166. /**
  167. * Adds JitsiLocalTrack object to the conference.
  168. * @param track the JitsiLocalTrack object.
  169. */
  170. JitsiConference.prototype.addTrack = function (track) {
  171. this.rtc.addLocalStream(track);
  172. this.room.addStream(track.getOriginalStream(), function () {});
  173. };
  174. /**
  175. * Removes JitsiLocalTrack object to the conference.
  176. * @param track the JitsiLocalTrack object.
  177. */
  178. JitsiConference.prototype.removeTrack = function (track) {
  179. this.room.removeStream(track.getOriginalStream());
  180. this.rtc.removeLocalStream(track);
  181. };
  182. /**
  183. * Get role of the local user.
  184. * @returns {string} user role: 'moderator' or 'none'
  185. */
  186. JitsiConference.prototype.getRole = function () {
  187. return this.room.role;
  188. };
  189. /**
  190. * Check if local user is moderator.
  191. * @returns {boolean} true if local user is moderator, false otherwise.
  192. */
  193. JitsiConference.prototype.isModerator = function () {
  194. return this.room.isModerator();
  195. };
  196. /**
  197. * Elects the participant with the given id to be the selected participant or the speaker.
  198. * @param id the identifier of the participant
  199. */
  200. JitsiConference.prototype.selectParticipant = function(participantId) {
  201. if (this.rtc) {
  202. this.rtc.selectedEndpoint(participantId);
  203. }
  204. };
  205. /**
  206. *
  207. * @param id the identifier of the participant
  208. */
  209. JitsiConference.prototype.pinParticipant = function(participantId) {
  210. if (this.rtc) {
  211. this.rtc.pinEndpoint(participantId);
  212. }
  213. };
  214. /**
  215. * Returns the list of participants for this conference.
  216. * @return Array<JitsiParticipant> a list of participant identifiers containing all conference participants.
  217. */
  218. JitsiConference.prototype.getParticipants = function() {
  219. return Object.keys(this.participants).map(function (key) {
  220. return this.participants[key];
  221. }, this);
  222. };
  223. /**
  224. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  225. * undefined if there isn't one).
  226. * @param id the id of the participant.
  227. */
  228. JitsiConference.prototype.getParticipantById = function(id) {
  229. return this.participants[id];
  230. };
  231. JitsiConference.prototype.onMemberJoined = function (jid, email, nick) {
  232. var id = Strophe.getResourceFromJid(jid);
  233. var participant = new JitsiParticipant(id, this, nick);
  234. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, id);
  235. this.participants[id] = participant;
  236. this.connection.xmpp.connection.disco.info(
  237. jid, "" /* node */, function(iq) {
  238. participant._supportsDTMF = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  239. this.updateDTMFSupport();
  240. }.bind(this)
  241. );
  242. };
  243. JitsiConference.prototype.onMemberLeft = function (jid) {
  244. var id = Strophe.getResourceFromJid(jid);
  245. delete this.participants[id];
  246. this.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, id);
  247. };
  248. JitsiConference.prototype.onUserRoleChanged = function (jid, role) {
  249. var id = Strophe.getResourceFromJid(jid);
  250. var participant = this.getParticipantById(id);
  251. if (!participant) {
  252. return;
  253. }
  254. participant._role = role;
  255. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  256. };
  257. JitsiConference.prototype.onDisplayNameChanged = function (jid, displayName) {
  258. var id = Strophe.getResourceFromJid(jid);
  259. var participant = this.getParticipantById(id);
  260. if (!participant) {
  261. return;
  262. }
  263. participant._displayName = displayName;
  264. this.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED, id, displayName);
  265. };
  266. JitsiConference.prototype.onTrackAdded = function (track) {
  267. var id = track.getParticipantId();
  268. var participant = this.getParticipantById(id);
  269. participant._tracks.push(track);
  270. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  271. };
  272. JitsiConference.prototype.onTrackRemoved = function (track) {
  273. var id = track.getParticipantId();
  274. var participant = this.getParticipantById(id);
  275. var pos = participant._tracks.indexOf(track);
  276. if (pos > -1) {
  277. participant._tracks.splice(pos, 1);
  278. }
  279. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  280. };
  281. JitsiConference.prototype.updateDTMFSupport = function () {
  282. var somebodySupportsDTMF = false;
  283. var participants = this.getParticipants();
  284. // check if at least 1 participant supports DTMF
  285. for (var i = 0; i < participants.length; i += 1) {
  286. if (participants[i].supportsDTMF()) {
  287. somebodySupportsDTMF = true;
  288. break;
  289. }
  290. }
  291. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  292. this.somebodySupportsDTMF = somebodySupportsDTMF;
  293. this.eventEmitter.emit(JitsiConferenceEvents.DTMF_SUPPORT_CHANGED, somebodySupportsDTMF);
  294. }
  295. };
  296. /**
  297. * Allows to check if there is at least one user in the conference
  298. * that supports DTMF.
  299. * @returns {boolean} true if somebody supports DTMF, false otherwise
  300. */
  301. JitsiConference.prototype.isDTMFSupported = function () {
  302. return this.somebodySupportsDTMF;
  303. };
  304. /**
  305. * Returns the local user's ID
  306. * @return {string} local user's ID
  307. */
  308. JitsiConference.prototype.myUserId = function () {
  309. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  310. };
  311. JitsiConference.prototype.sendTones = function (tones, duration, pause) {
  312. if (!this.dtmfManager) {
  313. var connection = this.connection.xmpp.connection.jingle.activecall.peerconnection;
  314. if (!connection) {
  315. logger.warn("cannot sendTones: no conneciton");
  316. return;
  317. }
  318. var tracks = this.getLocalTracks().filter(function (track) {
  319. return track.isAudioTrack();
  320. });
  321. if (!tracks.length) {
  322. logger.warn("cannot sendTones: no local audio stream");
  323. return;
  324. }
  325. this.dtmfManager = new JitsiDTMFManager(tracks[0], connection);
  326. }
  327. this.dtmfManager.sendTones(tones, duration, pause);
  328. };
  329. /**
  330. * Setups the listeners needed for the conference.
  331. * @param conference the conference
  332. */
  333. function setupListeners(conference) {
  334. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  335. conference.rtc.onIncommingCall(event);
  336. if(conference.statistics)
  337. conference.statistics.startRemoteStats(event.peerconnection);
  338. });
  339. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  340. conference.rtc.createRemoteStream.bind(conference.rtc));
  341. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  342. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  343. });
  344. // FIXME
  345. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  346. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  347. // });
  348. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  349. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT, conference.onMemberLeft.bind(conference));
  350. conference.room.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, conference.onDisplayNameChanged.bind(conference));
  351. conference.room.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, function (role) {
  352. conference.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, conference.myUserId(), role);
  353. });
  354. conference.room.addListener(XMPPEvents.MUC_ROLE_CHANGED, conference.onUserRoleChanged.bind(conference));
  355. conference.room.addListener(XMPPEvents.CONNECTION_INTERRUPTED, function () {
  356. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  357. });
  358. conference.room.addListener(XMPPEvents.CONNECTION_RESTORED, function () {
  359. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  360. });
  361. conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  362. conference.eventEmitter.emit(JitsiConferenceEvents.SETUP_FAILED);
  363. });
  364. conference.rtc.addListener(
  365. StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, conference.onTrackAdded.bind(conference)
  366. );
  367. //FIXME: Maybe remove event should not be associated with the conference.
  368. conference.rtc.addListener(
  369. StreamEventTypes.EVENT_TYPE_REMOTE_ENDED, conference.onTrackRemoved.bind(conference)
  370. );
  371. //FIXME: Maybe remove event should not be associated with the conference.
  372. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, function (stream) {
  373. conference.removeTrack(stream);
  374. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, stream);
  375. });
  376. conference.rtc.addListener(StreamEventTypes.TRACK_MUTE_CHANGED, function (track) {
  377. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  378. });
  379. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  380. if(conference.lastActiveSpeaker !== id && conference.room) {
  381. conference.lastActiveSpeaker = id;
  382. conference.eventEmitter.emit(JitsiConferenceEvents.ACTIVE_SPEAKER_CHANGED, id);
  383. }
  384. });
  385. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  386. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  387. });
  388. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  389. function (lastNEndpoints, endpointsEnteringLastN) {
  390. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  391. lastNEndpoints, endpointsEnteringLastN);
  392. });
  393. if(conference.statistics) {
  394. //FIXME: Maybe remove event should not be associated with the conference.
  395. conference.statistics.addAudioLevelListener(function (ssrc, level) {
  396. var userId = null;
  397. if (ssrc === Statistics.LOCAL_JID) {
  398. userId = conference.myUserId();
  399. } else {
  400. var jid = conference.room.getJidBySSRC(ssrc);
  401. if (!jid)
  402. return;
  403. userId = Strophe.getResourceFromJid(jid);
  404. }
  405. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  406. userId, level);
  407. });
  408. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_LOCAL_CREATED, function (stream) {
  409. conference.statistics.startLocalStats(stream);
  410. });
  411. conference.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE,
  412. function () {
  413. conference.statistics.dispose();
  414. });
  415. // FIXME: Maybe we should move this.
  416. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  417. // conference.room.updateDeviceAvailability(devices);
  418. // });
  419. }
  420. }
  421. module.exports = JitsiConference;
  422. }).call(this,"/JitsiConference.js")
  423. },{"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./modules/DTMF/JitsiDTMFManager":11,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"./service/RTC/RTCEvents":79,"./service/RTC/StreamEventTypes":81,"./service/xmpp/XMPPEvents":86,"events":43,"jitsi-meet-logger":47}],2:[function(require,module,exports){
  424. /**
  425. * Enumeration with the errors for the conference.
  426. * @type {{string: string}}
  427. */
  428. var JitsiConferenceErrors = {
  429. /**
  430. * Indicates that a password is required in order to join the conference.
  431. */
  432. PASSWORD_REQUIRED: "conference.passwordRequired",
  433. /**
  434. * Indicates that a connection error occurred when trying to join a
  435. * conference.
  436. */
  437. CONNECTION_ERROR: "conference.connectionError",
  438. /**
  439. * Indicates that there is no available videobridge.
  440. */
  441. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  442. /**
  443. * Many more errors TBD here.
  444. */
  445. };
  446. module.exports = JitsiConferenceErrors;
  447. },{}],3:[function(require,module,exports){
  448. /**
  449. * Enumeration with the events for the conference.
  450. * @type {{string: string}}
  451. */
  452. var JitsiConferenceEvents = {
  453. /**
  454. * A new media track was added to the conference.
  455. */
  456. TRACK_ADDED: "conference.trackAdded",
  457. /**
  458. * The media track was removed from the conference.
  459. */
  460. TRACK_REMOVED: "conference.trackRemoved",
  461. /**
  462. * The active speaker was changed.
  463. */
  464. ACTIVE_SPEAKER_CHANGED: "conference.activeSpeaker",
  465. /**
  466. * A new user joinned the conference.
  467. */
  468. USER_JOINED: "conference.userJoined",
  469. /**
  470. * A user has left the conference.
  471. */
  472. USER_LEFT: "conference.userLeft",
  473. /**
  474. * User role changed.
  475. */
  476. USER_ROLE_CHANGED: "conference.roleChanged",
  477. /**
  478. * New text message was received.
  479. */
  480. MESSAGE_RECEIVED: "conference.messageReceived",
  481. /**
  482. * A user has changed it display name
  483. */
  484. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  485. /**
  486. * A participant avatar has changed.
  487. */
  488. AVATAR_CHANGED: "conference.avatarChanged",
  489. /**
  490. * New connection statistics are received.
  491. */
  492. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  493. /**
  494. * The Last N set is changed.
  495. */
  496. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  497. /**
  498. * You are included / excluded in somebody's last N set
  499. */
  500. IN_LAST_N_CHANGED: "conference.lastNEndpointsChanged",
  501. /**
  502. * A media track ( attached to the conference) mute status was changed.
  503. */
  504. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  505. /**
  506. * Audio levels of a media track ( attached to the conference) was changed.
  507. */
  508. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  509. /**
  510. * Indicates that the connection to the conference has been interrupted
  511. * for some reason.
  512. */
  513. CONNECTION_INTERRUPTED: "conference.connectionInterrupted",
  514. /**
  515. * Indicates that the connection to the conference has been restored.
  516. */
  517. CONNECTION_RESTORED: "conference.connectionRestored",
  518. /**
  519. * Indicates that the conference setup failed.
  520. */
  521. SETUP_FAILED: "conference.setup_failed",
  522. /**
  523. * Indicates that conference has been joined.
  524. */
  525. CONFERENCE_JOINED: "conference.joined",
  526. /**
  527. * Indicates that conference has been left.
  528. */
  529. CONFERENCE_LEFT: "conference.left",
  530. /**
  531. * Indicates that DTMF support changed.
  532. */
  533. DTMF_SUPPORT_CHANGED: "conference.dtmfSupportChanged"
  534. };
  535. module.exports = JitsiConferenceEvents;
  536. },{}],4:[function(require,module,exports){
  537. var JitsiConference = require("./JitsiConference");
  538. var XMPP = require("./modules/xmpp/xmpp");
  539. var RandomUtil = require("./modules/util/RandomUtil");
  540. /**
  541. * Utility method that generates user name based on random hex values.
  542. * Eg. 12345678-1234-1234-12345678
  543. * @returns {string}
  544. */
  545. function generateUserName() {
  546. return RandomUtil.randomHexString(8) + "-" + RandomUtil.randomHexString(4) +
  547. "-" + RandomUtil.randomHexString(4) + "-" +
  548. RandomUtil.randomHexDigit(8);
  549. }
  550. /**
  551. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  552. * JitsiConference interface.
  553. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  554. * @param tokenPassword secret generated by the provider of Jitsi Meet video conferencing services.
  555. * The token will be send to the provider from the Jitsi Meet server deployment for authorization of the current client.
  556. * The format is:
  557. * passwordToken = token + "_" + roomName + "_" + ts
  558. * See doc/tokens.md for more info on how tokens are generated.
  559. * @param options Object with properties / settings related to connection with the server.
  560. * @constructor
  561. */
  562. function JitsiConnection(appID, tokenPassword, options) {
  563. this.appID = appID;
  564. this.tokenPassword = tokenPassword;
  565. this.options = options;
  566. this.xmpp = new XMPP(options);
  567. this.conferences = {};
  568. }
  569. /**
  570. * Connect the client with the server.
  571. * @param options {object} connecting options (for example authentications parameters).
  572. */
  573. JitsiConnection.prototype.connect = function (options) {
  574. if(!options)
  575. options = {};
  576. // If we have token provided use it as a password and generate random username
  577. if (this.tokenPassword) {
  578. options.password = this.tokenPassword;
  579. if (!options.id) {
  580. options.id = generateUserName() + "@" + this.options.hosts.domain;
  581. }
  582. }
  583. this.xmpp.connect(options.id, options.password);
  584. }
  585. /**
  586. * Disconnect the client from the server.
  587. */
  588. JitsiConnection.prototype.disconnect = function () {
  589. this.xmpp.disconnect();
  590. }
  591. /**
  592. * This method allows renewal of the tokens if they are expiring.
  593. * @param token the new token.
  594. */
  595. JitsiConnection.prototype.setToken = function (token) {
  596. this.token = token;
  597. }
  598. /**
  599. * Creates and joins new conference.
  600. * @param name the name of the conference; if null - a generated name will be provided from the api
  601. * @param options Object with properties / settings related to the conference that will be created.
  602. * @returns {JitsiConference} returns the new conference object.
  603. */
  604. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  605. this.conferences[name] = new JitsiConference({name: name, config: options, connection: this});
  606. return this.conferences[name];
  607. }
  608. /**
  609. * Subscribes the passed listener to the event.
  610. * @param event {JitsiConnectionEvents} the connection event.
  611. * @param listener {Function} the function that will receive the event
  612. */
  613. JitsiConnection.prototype.addEventListener = function (event, listener) {
  614. this.xmpp.addListener(event, listener);
  615. }
  616. /**
  617. * Unsubscribes the passed handler.
  618. * @param event {JitsiConnectionEvents} the connection event.
  619. * @param listener {Function} the function that will receive the event
  620. */
  621. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  622. this.xmpp.removeListener(event, listener);
  623. }
  624. module.exports = JitsiConnection;
  625. },{"./JitsiConference":1,"./modules/util/RandomUtil":25,"./modules/xmpp/xmpp":41}],5:[function(require,module,exports){
  626. /**
  627. * Enumeration with the errors for the connection.
  628. * @type {{string: string}}
  629. */
  630. var JitsiConnectionErrors = {
  631. /**
  632. * Indicates that a password is required in order to join the conference.
  633. */
  634. PASSWORD_REQUIRED: "connection.passwordRequired",
  635. /**
  636. * Indicates that a connection error occurred when trying to join a
  637. * conference.
  638. */
  639. CONNECTION_ERROR: "connection.connectionError",
  640. /**
  641. * Not specified errors.
  642. */
  643. OTHER_ERROR: "connection.otherError"
  644. };
  645. module.exports = JitsiConnectionErrors;
  646. },{}],6:[function(require,module,exports){
  647. /**
  648. * Enumeration with the events for the connection.
  649. * @type {{string: string}}
  650. */
  651. var JitsiConnnectionEvents = {
  652. /**
  653. * Indicates that the connection has been failed for some reason.
  654. */
  655. CONNECTION_FAILED: "connection.connectionFailed",
  656. /**
  657. * Indicates that the connection has been established.
  658. */
  659. CONNECTION_ESTABLISHED: "connection.connectionEstablished",
  660. /**
  661. * Indicates that the connection has been disconnected.
  662. */
  663. CONNECTION_DISCONNECTED: "connection.connectionDisconnected",
  664. /**
  665. * Indicates that the perfomed action cannot be executed because the
  666. * connection is not in the correct state(connected, disconnected, etc.)
  667. */
  668. WRONG_STATE: "connection.wrongState"
  669. };
  670. module.exports = JitsiConnnectionEvents;
  671. },{}],7:[function(require,module,exports){
  672. var JitsiConnection = require("./JitsiConnection");
  673. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  674. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  675. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  676. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  677. var JitsiTrackEvents = require("./JitsiTrackEvents");
  678. var JitsiTrackErrors = require("./JitsiTrackErrors");
  679. var Logger = require("jitsi-meet-logger");
  680. var RTC = require("./modules/RTC/RTC");
  681. /**
  682. * Namespace for the interface of Jitsi Meet Library.
  683. */
  684. var LibJitsiMeet = {
  685. JitsiConnection: JitsiConnection,
  686. events: {
  687. conference: JitsiConferenceEvents,
  688. connection: JitsiConnectionEvents,
  689. track: JitsiTrackEvents
  690. },
  691. errors: {
  692. conference: JitsiConferenceErrors,
  693. connection: JitsiConnectionErrors,
  694. track: JitsiTrackErrors
  695. },
  696. logLevels: Logger.levels,
  697. init: function (options) {
  698. return RTC.init(options || {});
  699. },
  700. setLogLevel: function (level) {
  701. Logger.setLogLevel(level);
  702. },
  703. /**
  704. * Creates the media tracks and returns them trough the callback.
  705. * @param options Object with properties / settings specifying the tracks which should be created.
  706. * should be created or some additional configurations about resolution for example.
  707. * @param {Array} options.devices the devices that will be requested
  708. * @param {string} options.resolution resolution constraints
  709. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  710. * type: "audio" or "video", videoType: "camera" or "desktop"}
  711. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  712. * @param {string} options.cameraDeviceId
  713. * @param {string} options.micDeviceId
  714. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>} A promise that returns an array of created JitsiTracks if resolved,
  715. * or a JitsiConferenceError if rejected.
  716. */
  717. createLocalTracks: function (options) {
  718. return RTC.obtainAudioAndVideoPermissions(options || {});
  719. },
  720. isDeviceListAvailable: function () {
  721. return RTC.isDeviceListAvailable();
  722. },
  723. enumerateDevices: function (callback) {
  724. RTC.enumerateDevices(callback);
  725. }
  726. };
  727. require("es6-promise").polyfill()
  728. //Setups the promise object.
  729. window.Promise = window.Promise || require("es6-promise").Promise;
  730. module.exports = LibJitsiMeet;
  731. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./JitsiTrackErrors":9,"./JitsiTrackEvents":10,"./modules/RTC/RTC":16,"es6-promise":45,"jitsi-meet-logger":47}],8:[function(require,module,exports){
  732. /**
  733. * Represents a participant in (a member of) a conference.
  734. */
  735. function JitsiParticipant(id, conference, displayName){
  736. this._id = id;
  737. this._conference = conference;
  738. this._displayName = displayName;
  739. this._supportsDTMF = false;
  740. this._tracks = [];
  741. this._role = 'none';
  742. }
  743. /**
  744. * @returns {JitsiConference} The conference that this participant belongs to.
  745. */
  746. JitsiParticipant.prototype.getConference = function() {
  747. return this._conference;
  748. };
  749. /**
  750. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  751. */
  752. JitsiParticipant.prototype.getTracks = function() {
  753. return this._tracks;
  754. };
  755. /**
  756. * @returns {String} The ID (i.e. JID) of this participant.
  757. */
  758. JitsiParticipant.prototype.getId = function() {
  759. return this._id;
  760. };
  761. /**
  762. * @returns {String} The human-readable display name of this participant.
  763. */
  764. JitsiParticipant.prototype.getDisplayName = function() {
  765. return this._displayName;
  766. };
  767. /**
  768. * @returns {Boolean} Whether this participant is a moderator or not.
  769. */
  770. JitsiParticipant.prototype.isModerator = function() {
  771. return this._role === 'moderator';
  772. };
  773. // Gets a link to an etherpad instance advertised by the participant?
  774. //JitsiParticipant.prototype.getEtherpad = function() {
  775. //
  776. //}
  777. /*
  778. * @returns {Boolean} Whether this participant has muted their audio.
  779. */
  780. JitsiParticipant.prototype.isAudioMuted = function() {
  781. return this.getTracks().reduce(function (track, isAudioMuted) {
  782. return isAudioMuted && (track.isVideoTrack() || track.isMuted());
  783. }, true);
  784. };
  785. /*
  786. * @returns {Boolean} Whether this participant has muted their video.
  787. */
  788. JitsiParticipant.prototype.isVideoMuted = function() {
  789. return this.getTracks().reduce(function (track, isVideoMuted) {
  790. return isVideoMuted && (track.isAudioTrack() || track.isMuted());
  791. }, true);
  792. };
  793. /*
  794. * @returns {???} The latest statistics reported by this participant (i.e. info used to populate the GSM bars)
  795. * TODO: do we expose this or handle it internally?
  796. */
  797. JitsiParticipant.prototype.getLatestStats = function() {
  798. };
  799. /**
  800. * @returns {String} The role of this participant.
  801. */
  802. JitsiParticipant.prototype.getRole = function() {
  803. return this._role;
  804. };
  805. /*
  806. * @returns {Boolean} Whether this participant is the conference focus (i.e. jicofo).
  807. */
  808. JitsiParticipant.prototype.isFocus = function() {
  809. };
  810. /*
  811. * @returns {Boolean} Whether this participant is a conference recorder (i.e. jirecon).
  812. */
  813. JitsiParticipant.prototype.isRecorder = function() {
  814. };
  815. /*
  816. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  817. */
  818. JitsiParticipant.prototype.isSipGateway = function() {
  819. };
  820. /**
  821. * @returns {Boolean} Whether this participant is currently sharing their screen.
  822. */
  823. JitsiParticipant.prototype.isScreenSharing = function() {
  824. };
  825. /**
  826. * @returns {String} The user agent of this participant (i.e. browser userAgent string).
  827. */
  828. JitsiParticipant.prototype.getUserAgent = function() {
  829. };
  830. /**
  831. * Kicks the participant from the conference (requires certain privileges).
  832. */
  833. JitsiParticipant.prototype.kick = function() {
  834. };
  835. /**
  836. * Asks this participant to mute themselves.
  837. */
  838. JitsiParticipant.prototype.askToMute = function() {
  839. };
  840. JitsiParticipant.prototype.supportsDTMF = function () {
  841. return this._supportsDTMF;
  842. };
  843. module.exports = JitsiParticipant;
  844. },{}],9:[function(require,module,exports){
  845. module.exports = {
  846. /**
  847. * Returns JitsiTrackErrors based on the error object passed by GUM
  848. * @param error the error
  849. * @param {Object} options the options object given to GUM.
  850. */
  851. parseError: function (error, options) {
  852. options = options || {};
  853. if (typeof error == "object" && error.constraintName && error.name
  854. && (error.name == "ConstraintNotSatisfiedError" ||
  855. error.name == "OverconstrainedError") &&
  856. (error.constraintName == "minWidth" ||
  857. error.constraintName == "maxWidth" ||
  858. error.constraintName == "minHeight" ||
  859. error.constraintName == "maxHeight") &&
  860. options.devices.indexOf("video") !== -1) {
  861. return this.UNSUPPORTED_RESOLUTION;
  862. } else {
  863. return this.GENERAL;
  864. }
  865. },
  866. UNSUPPORTED_RESOLUTION: "gum.unsupported_resolution",
  867. GENERAL: "gum.general"
  868. };
  869. },{}],10:[function(require,module,exports){
  870. var JitsiTrackEvents = {
  871. /**
  872. * A media track mute status was changed.
  873. */
  874. TRACK_MUTE_CHANGED: "track.trackMuteChanged",
  875. /**
  876. * Audio levels of a this track was changed.
  877. */
  878. TRACK_AUDIO_LEVEL_CHANGED: "track.audioLevelsChanged",
  879. /**
  880. * The media track was removed to the conference.
  881. */
  882. TRACK_STOPPED: "track.TRACK_STOPPED",
  883. };
  884. module.exports = JitsiTrackEvents;
  885. },{}],11:[function(require,module,exports){
  886. (function (__filename){
  887. var logger = require("jitsi-meet-logger").getLogger(__filename);
  888. function JitsiDTMFManager (localAudio, peerConnection) {
  889. var tracks = localAudio._getTracks();
  890. if (!tracks.length) {
  891. throw new Error("Failed to initialize DTMFSender: no audio track.");
  892. }
  893. this.dtmfSender = peerConnection.peerconnection.createDTMFSender(tracks[0]);
  894. logger.debug("Initialized DTMFSender");
  895. }
  896. JitsiDTMFManager.prototype.sendTones = function (tones, duration, pause) {
  897. this.dtmfSender.insertDTMF(tones, (duration || 200), (pause || 200));
  898. };
  899. }).call(this,"/modules/DTMF/JitsiDTMFManager.js")
  900. },{"jitsi-meet-logger":47}],12:[function(require,module,exports){
  901. (function (__filename){
  902. /* global config, APP, Strophe */
  903. // cache datachannels to avoid garbage collection
  904. // https://code.google.com/p/chromium/issues/detail?id=405545
  905. var logger = require("jitsi-meet-logger").getLogger(__filename);
  906. var RTCEvents = require("../../service/RTC/RTCEvents");
  907. /**
  908. * Binds "ondatachannel" event listener to given PeerConnection instance.
  909. * @param peerConnection WebRTC peer connection instance.
  910. */
  911. function DataChannels(peerConnection, emitter) {
  912. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  913. this.eventEmitter = emitter;
  914. this._dataChannels = [];
  915. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  916. // Although it's not a requirement to open separate channels from both bridge
  917. // and peer as single channel can be used for sending and receiving data.
  918. // So either channel opened by the bridge or the one opened here is enough
  919. // for communication with the bridge.
  920. /*var dataChannelOptions =
  921. {
  922. reliable: true
  923. };
  924. var dataChannel
  925. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  926. // Can be used only when is in open state
  927. dataChannel.onopen = function ()
  928. {
  929. dataChannel.send("My channel !!!");
  930. };
  931. dataChannel.onmessage = function (event)
  932. {
  933. var msgData = event.data;
  934. logger.info("Got My Data Channel Message:", msgData, dataChannel);
  935. };*/
  936. };
  937. /**
  938. * Callback triggered by PeerConnection when new data channel is opened
  939. * on the bridge.
  940. * @param event the event info object.
  941. */
  942. DataChannels.prototype.onDataChannel = function (event) {
  943. var dataChannel = event.channel;
  944. var self = this;
  945. dataChannel.onopen = function () {
  946. logger.info("Data channel opened by the Videobridge!", dataChannel);
  947. // Code sample for sending string and/or binary data
  948. // Sends String message to the bridge
  949. //dataChannel.send("Hello bridge!");
  950. // Sends 12 bytes binary message to the bridge
  951. //dataChannel.send(new ArrayBuffer(12));
  952. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  953. };
  954. dataChannel.onerror = function (error) {
  955. logger.error("Data Channel Error:", error, dataChannel);
  956. };
  957. dataChannel.onmessage = function (event) {
  958. var data = event.data;
  959. // JSON
  960. var obj;
  961. try {
  962. obj = JSON.parse(data);
  963. }
  964. catch (e) {
  965. logger.error(
  966. "Failed to parse data channel message as JSON: ",
  967. data,
  968. dataChannel);
  969. }
  970. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  971. var colibriClass = obj.colibriClass;
  972. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  973. // Endpoint ID from the Videobridge.
  974. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  975. logger.info(
  976. "Data channel new dominant speaker event: ",
  977. dominantSpeakerEndpoint);
  978. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  979. }
  980. else if ("InLastNChangeEvent" === colibriClass) {
  981. var oldValue = obj.oldValue;
  982. var newValue = obj.newValue;
  983. // Make sure that oldValue and newValue are of type boolean.
  984. var type;
  985. if ((type = typeof oldValue) !== 'boolean') {
  986. if (type === 'string') {
  987. oldValue = (oldValue == "true");
  988. } else {
  989. oldValue = new Boolean(oldValue).valueOf();
  990. }
  991. }
  992. if ((type = typeof newValue) !== 'boolean') {
  993. if (type === 'string') {
  994. newValue = (newValue == "true");
  995. } else {
  996. newValue = new Boolean(newValue).valueOf();
  997. }
  998. }
  999. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  1000. }
  1001. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  1002. // The new/latest list of last-n endpoint IDs.
  1003. var lastNEndpoints = obj.lastNEndpoints;
  1004. // The list of endpoint IDs which are entering the list of
  1005. // last-n at this time i.e. were not in the old list of last-n
  1006. // endpoint IDs.
  1007. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  1008. logger.info(
  1009. "Data channel new last-n event: ",
  1010. lastNEndpoints, endpointsEnteringLastN, obj);
  1011. self.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1012. lastNEndpoints, endpointsEnteringLastN, obj);
  1013. }
  1014. else {
  1015. logger.debug("Data channel JSON-formatted message: ", obj);
  1016. // The received message appears to be appropriately formatted
  1017. // (i.e. is a JSON object which assigns a value to the mandatory
  1018. // property colibriClass) so don't just swallow it, expose it to
  1019. // public consumption.
  1020. self.eventEmitter.emit("rtc.datachannel." + colibriClass, obj);
  1021. }
  1022. }
  1023. };
  1024. dataChannel.onclose = function () {
  1025. logger.info("The Data Channel closed", dataChannel);
  1026. var idx = self._dataChannels.indexOf(dataChannel);
  1027. if (idx > -1)
  1028. self._dataChannels = self._dataChannels.splice(idx, 1);
  1029. };
  1030. this._dataChannels.push(dataChannel);
  1031. };
  1032. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  1033. this._onXXXEndpointChanged("selected", userResource);
  1034. }
  1035. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  1036. this._onXXXEndpointChanged("pinnned", userResource);
  1037. }
  1038. /**
  1039. * Notifies Videobridge about a change in the value of a specific
  1040. * endpoint-related property such as selected endpoint and pinnned endpoint.
  1041. *
  1042. * @param xxx the name of the endpoint-related property whose value changed
  1043. * @param userResource the new value of the endpoint-related property after the
  1044. * change
  1045. */
  1046. DataChannels.prototype._onXXXEndpointChanged = function (xxx, userResource) {
  1047. // Derive the correct words from xxx such as selected and Selected, pinned
  1048. // and Pinned.
  1049. var head = xxx.charAt(0);
  1050. var tail = xxx.substring(1);
  1051. var lower = head.toLowerCase() + tail;
  1052. var upper = head.toUpperCase() + tail;
  1053. // Notify Videobridge about the specified endpoint change.
  1054. console.log(lower + ' endpoint changed: ', userResource);
  1055. this._some(function (dataChannel) {
  1056. if (dataChannel.readyState == 'open') {
  1057. console.log(
  1058. 'sending ' + lower
  1059. + ' endpoint changed notification to the bridge: ',
  1060. userResource);
  1061. var jsonObject = {};
  1062. jsonObject.colibriClass = (upper + 'EndpointChangedEvent');
  1063. jsonObject[lower + "Endpoint"]
  1064. = (userResource ? userResource : null);
  1065. dataChannel.send(JSON.stringify(jsonObject));
  1066. return true;
  1067. }
  1068. });
  1069. }
  1070. DataChannels.prototype._some = function (callback, thisArg) {
  1071. var dataChannels = this._dataChannels;
  1072. if (dataChannels && dataChannels.length !== 0) {
  1073. if (thisArg)
  1074. return dataChannels.some(callback, thisArg);
  1075. else
  1076. return dataChannels.some(callback);
  1077. } else {
  1078. return false;
  1079. }
  1080. }
  1081. module.exports = DataChannels;
  1082. }).call(this,"/modules/RTC/DataChannels.js")
  1083. },{"../../service/RTC/RTCEvents":79,"jitsi-meet-logger":47}],13:[function(require,module,exports){
  1084. var JitsiTrack = require("./JitsiTrack");
  1085. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1086. var RTCBrowserType = require("./RTCBrowserType");
  1087. var RTC = require("./RTCUtils");
  1088. /**
  1089. * Represents a single media track (either audio or video).
  1090. * @constructor
  1091. */
  1092. function JitsiLocalTrack(stream, videoType,
  1093. resolution)
  1094. {
  1095. this.videoType = videoType;
  1096. this.dontFireRemoveEvent = false;
  1097. this.resolution = resolution;
  1098. var self = this;
  1099. JitsiTrack.call(this, null, stream,
  1100. function () {
  1101. if(!self.dontFireRemoveEvent && self.rtc)
  1102. self.rtc.eventEmitter.emit(
  1103. StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, self);
  1104. self.dontFireRemoveEvent = false;
  1105. });
  1106. }
  1107. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  1108. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  1109. /**
  1110. * Mutes / unmutes the track.
  1111. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  1112. */
  1113. JitsiLocalTrack.prototype._setMute = function (mute) {
  1114. if(!this.rtc) {
  1115. console.error("Mute is not supported for streams not attached to conference!");
  1116. return;
  1117. }
  1118. var isAudio = this.type === JitsiTrack.AUDIO;
  1119. this.dontFireRemoveEvent = false;
  1120. if ((window.location.protocol != "https:") ||
  1121. (isAudio) || this.videoType === "screen" ||
  1122. // FIXME FF does not support 'removeStream' method used to mute
  1123. RTCBrowserType.isFirefox()) {
  1124. var tracks = this._getTracks();
  1125. for (var idx = 0; idx < tracks.length; idx++) {
  1126. tracks[idx].enabled = !mute;
  1127. }
  1128. if(isAudio)
  1129. this.rtc.room.setAudioMute(mute);
  1130. else
  1131. this.rtc.room.setVideoMute(mute);
  1132. this.rtc.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  1133. } else {
  1134. if (mute) {
  1135. this.dontFireRemoveEvent = true;
  1136. this.rtc.room.removeStream(this.stream);
  1137. RTC.stopMediaStream(this.stream);
  1138. if(isAudio)
  1139. this.rtc.room.setAudioMute(mute);
  1140. else
  1141. this.rtc.room.setVideoMute(mute);
  1142. this.stream = null;
  1143. this.rtc.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  1144. //FIXME: Maybe here we should set the SRC for the containers to something
  1145. } else {
  1146. var self = this;
  1147. RTC.obtainAudioAndVideoPermissions({
  1148. devices: (isAudio ? ["audio"] : ["video"]),
  1149. resolution: self.resolution})
  1150. .then(function (streams) {
  1151. var stream = null;
  1152. for(var i = 0; i < streams.length; i++) {
  1153. stream = streams[i];
  1154. if(stream.type === self.type) {
  1155. self.stream = stream.stream;
  1156. self.videoType = stream.videoType;
  1157. break;
  1158. }
  1159. }
  1160. if(!stream)
  1161. return;
  1162. for(var i = 0; i < self.containers.length; i++)
  1163. {
  1164. RTC.attachMediaStream(self.containers[i], self.stream);
  1165. }
  1166. self.rtc.room.addStream(stream.stream,
  1167. function () {
  1168. if(isAudio)
  1169. self.rtc.room.setAudioMute(mute);
  1170. else
  1171. self.rtc.room.setVideoMute(mute);
  1172. self.rtc.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, self);
  1173. });
  1174. });
  1175. }
  1176. }
  1177. }
  1178. /**
  1179. * Stops sending the media track. And removes it from the HTML.
  1180. * NOTE: Works for local tracks only.
  1181. */
  1182. JitsiLocalTrack.prototype.stop = function () {
  1183. if(!this.stream)
  1184. return;
  1185. if(this.rtc)
  1186. this.rtc.room.removeStream(this.stream);
  1187. this.rtc.stopMediaStream(this.stream);
  1188. this.detach();
  1189. }
  1190. /**
  1191. * Returns <tt>true</tt> - if the stream is muted
  1192. * and <tt>false</tt> otherwise.
  1193. * @returns {boolean} <tt>true</tt> - if the stream is muted
  1194. * and <tt>false</tt> otherwise.
  1195. */
  1196. JitsiLocalTrack.prototype.isMuted = function () {
  1197. if (!this.stream)
  1198. return true;
  1199. var tracks = [];
  1200. var isAudio = this.type === JitsiTrack.AUDIO;
  1201. if (isAudio) {
  1202. tracks = this.stream.getAudioTracks();
  1203. } else {
  1204. if (!this.isActive())
  1205. return true;
  1206. tracks = this.stream.getVideoTracks();
  1207. }
  1208. for (var idx = 0; idx < tracks.length; idx++) {
  1209. if(tracks[idx].enabled)
  1210. return false;
  1211. }
  1212. return true;
  1213. };
  1214. /**
  1215. * Private method. Updates rtc property of the track.
  1216. * @param rtc the rtc instance.
  1217. */
  1218. JitsiLocalTrack.prototype._setRTC = function (rtc) {
  1219. this.rtc = rtc;
  1220. };
  1221. module.exports = JitsiLocalTrack;
  1222. },{"../../service/RTC/StreamEventTypes":81,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils":18}],14:[function(require,module,exports){
  1223. var JitsiTrack = require("./JitsiTrack");
  1224. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1225. /**
  1226. * Represents a single media track (either audio or video).
  1227. * @param RTC the rtc instance.
  1228. * @param data object with the stream and some details about it(participant id, video type, etc.)
  1229. * @param sid sid for the Media Stream
  1230. * @param ssrc ssrc for the Media Stream
  1231. * @param eventEmitter the event emitter
  1232. * @constructor
  1233. */
  1234. function JitsiRemoteTrack(RTC, data, sid, ssrc, eventEmitter) {
  1235. JitsiTrack.call(this, RTC, data.stream,
  1236. function () {
  1237. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_ENDED, self);
  1238. });
  1239. this.rtc = RTC;
  1240. this.sid = sid;
  1241. this.stream = data.stream;
  1242. this.peerjid = data.peerjid;
  1243. this.videoType = data.videoType;
  1244. this.ssrc = ssrc;
  1245. this.muted = false;
  1246. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  1247. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  1248. this.muted = true
  1249. }
  1250. this.eventEmitter = eventEmitter;
  1251. var self = this;
  1252. }
  1253. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  1254. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  1255. /**
  1256. * Sets current muted status and fires an events for the change.
  1257. * @param value the muted status.
  1258. */
  1259. JitsiRemoteTrack.prototype.setMute = function (value) {
  1260. this.stream.muted = value;
  1261. this.muted = value;
  1262. this.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  1263. };
  1264. /**
  1265. * Returns the current muted status of the track.
  1266. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  1267. */
  1268. JitsiRemoteTrack.prototype.isMuted = function () {
  1269. return this.muted;
  1270. }
  1271. /**
  1272. * Returns the participant id which owns the track.
  1273. * @returns {string} the id of the participants.
  1274. */
  1275. JitsiRemoteTrack.prototype.getParticipantId = function() {
  1276. return Strophe.getResourceFromJid(this.peerjid);
  1277. };
  1278. delete JitsiRemoteTrack.prototype.stop;
  1279. delete JitsiRemoteTrack.prototype.start;
  1280. module.exports = JitsiRemoteTrack;
  1281. },{"../../service/RTC/StreamEventTypes":81,"./JitsiTrack":15}],15:[function(require,module,exports){
  1282. var RTCBrowserType = require("./RTCBrowserType");
  1283. /**
  1284. * This implements 'onended' callback normally fired by WebRTC after the stream
  1285. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  1286. * @param jitsiTrack our track object holding the original WebRTC stream object
  1287. * to which 'onended' handling will be added.
  1288. */
  1289. function implementOnEndedHandling(jitsiTrack) {
  1290. var stream = jitsiTrack.getOriginalStream();
  1291. var originalStop = stream.stop;
  1292. stream.stop = function () {
  1293. originalStop.apply(stream);
  1294. if (jitsiTrack.isActive()) {
  1295. stream.onended();
  1296. }
  1297. };
  1298. }
  1299. /**
  1300. * Adds onended/oninactive handler to a MediaStream.
  1301. * @param mediaStream a MediaStream to attach onended/oninactive handler
  1302. * @param handler the handler
  1303. */
  1304. function addMediaStreamInactiveHandler(mediaStream, handler) {
  1305. if(RTCBrowserType.isTemasysPluginUsed()) {
  1306. // themasys
  1307. mediaStream.attachEvent('ended', function () {
  1308. handler(mediaStream);
  1309. });
  1310. }
  1311. else {
  1312. if(typeof mediaStream.active !== "undefined")
  1313. mediaStream.oninactive = handler;
  1314. else
  1315. mediaStream.onended = handler;
  1316. }
  1317. }
  1318. /**
  1319. * Represents a single media track (either audio or video).
  1320. * @constructor
  1321. * @param rtc the rtc instance
  1322. * @param stream the stream
  1323. * @param streamInactiveHandler the function that will handle
  1324. * onended/oninactive events of the stream.
  1325. */
  1326. function JitsiTrack(rtc, stream, streamInactiveHandler)
  1327. {
  1328. /**
  1329. * Array with the HTML elements that are displaying the streams.
  1330. * @type {Array}
  1331. */
  1332. this.containers = [];
  1333. this.rtc = rtc;
  1334. this.stream = stream;
  1335. this.type = (this.stream.getVideoTracks().length > 0)?
  1336. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  1337. if(this.type == "audio") {
  1338. this._getTracks = function () {
  1339. return this.stream.getAudioTracks();
  1340. }.bind(this);
  1341. } else {
  1342. this._getTracks = function () {
  1343. return this.stream.getVideoTracks();
  1344. }.bind(this);
  1345. }
  1346. if (RTCBrowserType.isFirefox() && this.stream) {
  1347. implementOnEndedHandling(this);
  1348. }
  1349. if(stream)
  1350. addMediaStreamInactiveHandler(stream, streamInactiveHandler);
  1351. }
  1352. /**
  1353. * JitsiTrack video type.
  1354. * @type {string}
  1355. */
  1356. JitsiTrack.VIDEO = "video";
  1357. /**
  1358. * JitsiTrack audio type.
  1359. * @type {string}
  1360. */
  1361. JitsiTrack.AUDIO = "audio";
  1362. /**
  1363. * Returns the type (audio or video) of this track.
  1364. */
  1365. JitsiTrack.prototype.getType = function() {
  1366. return this.type;
  1367. };
  1368. /**
  1369. * Check if this is audiotrack.
  1370. */
  1371. JitsiTrack.prototype.isAudioTrack = function () {
  1372. return this.getType() === JitsiTrack.AUDIO;
  1373. };
  1374. /**
  1375. * Check if this is videotrack.
  1376. */
  1377. JitsiTrack.prototype.isVideoTrack = function () {
  1378. return this.getType() === JitsiTrack.VIDEO;
  1379. };
  1380. /**
  1381. * Returns the RTCMediaStream from the browser (?).
  1382. */
  1383. JitsiTrack.prototype.getOriginalStream = function() {
  1384. return this.stream;
  1385. }
  1386. /**
  1387. * Mutes the track.
  1388. */
  1389. JitsiTrack.prototype.mute = function () {
  1390. this._setMute(true);
  1391. }
  1392. /**
  1393. * Unmutes the stream.
  1394. */
  1395. JitsiTrack.prototype.unmute = function () {
  1396. this._setMute(false);
  1397. }
  1398. /**
  1399. * Attaches the MediaStream of this track to an HTML container (?).
  1400. * Adds the container to the list of containers that are displaying the track.
  1401. * @param container the HTML container
  1402. */
  1403. JitsiTrack.prototype.attach = function (container) {
  1404. if(this.stream)
  1405. require("./RTCUtils").attachMediaStream(container, this.stream);
  1406. this.containers.push(container);
  1407. }
  1408. /**
  1409. * Removes the track from the passed HTML container.
  1410. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  1411. */
  1412. JitsiTrack.prototype.detach = function (container) {
  1413. for(var i = 0; i < this.containers.length; i++)
  1414. {
  1415. if(this.containers[i].is(container))
  1416. {
  1417. this.containers.splice(i,1);
  1418. }
  1419. if(!container)
  1420. {
  1421. this.containers[i].find(">video").remove();
  1422. }
  1423. }
  1424. if(container)
  1425. $(container).find(">video").remove();
  1426. }
  1427. /**
  1428. * Stops sending the media track. And removes it from the HTML.
  1429. * NOTE: Works for local tracks only.
  1430. */
  1431. JitsiTrack.prototype.stop = function () {
  1432. }
  1433. /**
  1434. * Returns true if this is a video track and the source of the video is a
  1435. * screen capture as opposed to a camera.
  1436. */
  1437. JitsiTrack.prototype.isScreenSharing = function(){
  1438. }
  1439. /**
  1440. * Returns id of the track.
  1441. * @returns {string} id of the track or null if this is fake track.
  1442. */
  1443. JitsiTrack.prototype.getId = function () {
  1444. var tracks = this.stream.getTracks();
  1445. if(!tracks || tracks.length === 0)
  1446. return null;
  1447. return tracks[0].id;
  1448. };
  1449. /**
  1450. * Checks whether the MediaStream is avtive/not ended.
  1451. * When there is no check for active we don't have information and so
  1452. * will return that stream is active (in case of FF).
  1453. * @returns {boolean} whether MediaStream is active.
  1454. */
  1455. JitsiTrack.prototype.isActive = function () {
  1456. if((typeof this.stream.active !== "undefined"))
  1457. return this.stream.active;
  1458. else
  1459. return true;
  1460. };
  1461. module.exports = JitsiTrack;
  1462. },{"./RTCBrowserType":17,"./RTCUtils":18}],16:[function(require,module,exports){
  1463. /* global APP */
  1464. var EventEmitter = require("events");
  1465. var RTCBrowserType = require("./RTCBrowserType");
  1466. var RTCUtils = require("./RTCUtils.js");
  1467. var JitsiTrack = require("./JitsiTrack");
  1468. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  1469. var DataChannels = require("./DataChannels");
  1470. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  1471. var DesktopSharingEventTypes
  1472. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1473. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  1474. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  1475. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  1476. function createLocalTracks(streams) {
  1477. var newStreams = []
  1478. for (var i = 0; i < streams.length; i++) {
  1479. var localStream = new JitsiLocalTrack(streams[i].stream,
  1480. streams[i].videoType, streams[i].resolution);
  1481. newStreams.push(localStream);
  1482. if (streams[i].isMuted === true)
  1483. localStream.setMute(true);
  1484. //FIXME:
  1485. // var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  1486. //
  1487. // eventEmitter.emit(eventType, localStream);
  1488. }
  1489. return newStreams;
  1490. }
  1491. function RTC(room, options) {
  1492. this.room = room;
  1493. this.localStreams = [];
  1494. this.remoteStreams = {};
  1495. this.localAudio = null;
  1496. this.localVideo = null;
  1497. this.eventEmitter = new EventEmitter();
  1498. var self = this;
  1499. this.options = options || {};
  1500. room.addPresenceListener("videomuted", function (values, from) {
  1501. if(self.remoteStreams[from])
  1502. self.remoteStreams[from][JitsiTrack.VIDEO].setMute(values.value == "true");
  1503. });
  1504. room.addPresenceListener("audiomuted", function (values, from) {
  1505. if(self.remoteStreams[from])
  1506. self.remoteStreams[from][JitsiTrack.AUDIO].setMute(values.value == "true");
  1507. });
  1508. }
  1509. /**
  1510. * Creates the local MediaStreams.
  1511. * @param {Object} [options] optional parameters
  1512. * @param {Array} options.devices the devices that will be requested
  1513. * @param {string} options.resolution resolution constraints
  1514. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1515. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1516. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1517. * @param {string} options.cameraDeviceId
  1518. * @param {string} options.micDeviceId
  1519. * @returns {*} Promise object that will receive the new JitsiTracks
  1520. */
  1521. RTC.obtainAudioAndVideoPermissions = function (options) {
  1522. return RTCUtils.obtainAudioAndVideoPermissions(options).then(createLocalTracks);
  1523. }
  1524. RTC.prototype.onIncommingCall = function(event) {
  1525. if(this.options.config.openSctp)
  1526. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  1527. for(var i = 0; i < this.localStreams.length; i++)
  1528. if(this.localStreams[i])
  1529. {
  1530. this.room.addStream(this.localStreams[i].getOriginalStream(), function () {});
  1531. }
  1532. }
  1533. RTC.prototype.selectedEndpoint = function (id) {
  1534. if(this.dataChannels)
  1535. this.dataChannels.handleSelectedEndpointEvent(id);
  1536. }
  1537. RTC.prototype.pinEndpoint = function (id) {
  1538. if(this.dataChannels)
  1539. this.dataChannels.handlePinnedEndpointEvent(id);
  1540. }
  1541. RTC.prototype.addListener = function (type, listener) {
  1542. this.eventEmitter.on(type, listener);
  1543. };
  1544. RTC.prototype.removeListener = function (eventType, listener) {
  1545. this.eventEmitter.removeListener(eventType, listener);
  1546. };
  1547. RTC.addListener = function (eventType, listener) {
  1548. RTCUtils.addListener(eventType, listener);
  1549. }
  1550. RTC.removeListener = function (eventType, listener) {
  1551. RTCUtils.removeListener(eventType, listener)
  1552. }
  1553. RTC.isRTCReady = function () {
  1554. return RTCUtils.isRTCReady();
  1555. }
  1556. RTC.init = function (options) {
  1557. return RTCUtils.init(options || {});
  1558. }
  1559. RTC.getDeviceAvailability = function () {
  1560. return RTCUtils.getDeviceAvailability();
  1561. }
  1562. RTC.prototype.addLocalStream = function (stream) {
  1563. this.localStreams.push(stream);
  1564. stream._setRTC(this);
  1565. if (stream.type == "audio") {
  1566. this.localAudio = stream;
  1567. } else {
  1568. this.localVideo = stream;
  1569. }
  1570. };
  1571. RTC.prototype.removeLocalStream = function (stream) {
  1572. for(var i = 0; i < this.localStreams.length; i++) {
  1573. if(this.localStreams[i].getOriginalStream() === stream) {
  1574. delete this.localStreams[i];
  1575. return;
  1576. }
  1577. }
  1578. };
  1579. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  1580. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc,
  1581. this.eventEmitter);
  1582. if(!data.peerjid)
  1583. return;
  1584. var jid = data.peerjid;
  1585. if(!this.remoteStreams[jid]) {
  1586. this.remoteStreams[jid] = {};
  1587. }
  1588. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  1589. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  1590. return remoteStream;
  1591. };
  1592. RTC.getPCConstraints = function () {
  1593. return RTCUtils.pc_constraints;
  1594. };
  1595. RTC.attachMediaStream = function (elSelector, stream) {
  1596. RTCUtils.attachMediaStream(elSelector, stream);
  1597. };
  1598. RTC.getStreamID = function (stream) {
  1599. return RTCUtils.getStreamID(stream);
  1600. };
  1601. RTC.getVideoSrc = function (element) {
  1602. return RTCUtils.getVideoSrc(element);
  1603. };
  1604. RTC.isDeviceListAvailable = function () {
  1605. return RTCUtils.isDeviceListAvailable();
  1606. };
  1607. /**
  1608. * Allows to receive list of available cameras/microphones.
  1609. * @param {function} callback would receive array of devices as an argument
  1610. */
  1611. RTC.enumerateDevices = function (callback) {
  1612. RTCUtils.enumerateDevices(callback);
  1613. };
  1614. RTC.setVideoSrc = function (element, src) {
  1615. RTCUtils.setVideoSrc(element, src);
  1616. };
  1617. /**
  1618. * A method to handle stopping of the stream.
  1619. * One point to handle the differences in various implementations.
  1620. * @param mediaStream MediaStream object to stop.
  1621. */
  1622. RTC.stopMediaStream = function (mediaStream) {
  1623. RTCUtils.stopMediaStream(mediaStream);
  1624. };
  1625. RTC.prototype.getVideoElementName = function () {
  1626. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  1627. };
  1628. RTC.prototype.dispose = function() {
  1629. };
  1630. RTC.prototype.muteRemoteVideoStream = function (jid, value) {
  1631. var stream;
  1632. if(this.remoteStreams[jid] &&
  1633. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1634. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  1635. }
  1636. if(!stream)
  1637. return true;
  1638. if (value != stream.muted) {
  1639. stream.setMute(value);
  1640. return true;
  1641. }
  1642. return false;
  1643. };
  1644. RTC.prototype.switchVideoStreams = function (newStream) {
  1645. this.localVideo.stream = newStream;
  1646. this.localStreams = [];
  1647. //in firefox we have only one stream object
  1648. if (this.localAudio.getOriginalStream() != newStream)
  1649. this.localStreams.push(this.localAudio);
  1650. this.localStreams.push(this.localVideo);
  1651. };
  1652. RTC.prototype.isVideoMuted = function (jid) {
  1653. if (jid === APP.xmpp.myJid()) {
  1654. var localVideo = APP.RTC.localVideo;
  1655. return (!localVideo || localVideo.isMuted());
  1656. } else {
  1657. if (!this.remoteStreams[jid] ||
  1658. !this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1659. return null;
  1660. }
  1661. return this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  1662. }
  1663. };
  1664. RTC.prototype.setVideoMute = function (mute, callback, options) {
  1665. if (!this.localVideo)
  1666. return;
  1667. if (mute == this.localVideo.isMuted())
  1668. {
  1669. APP.xmpp.sendVideoInfoPresence(mute);
  1670. if (callback)
  1671. callback(mute);
  1672. }
  1673. else
  1674. {
  1675. this.localVideo.setMute(mute);
  1676. this.room.setVideoMute(
  1677. mute,
  1678. callback,
  1679. options);
  1680. }
  1681. };
  1682. module.exports = RTC;
  1683. },{"../../service/RTC/MediaStreamTypes":78,"../../service/RTC/RTCEvents.js":79,"../../service/RTC/StreamEventTypes.js":81,"../../service/desktopsharing/DesktopSharingEventTypes":83,"./DataChannels":12,"./JitsiLocalTrack.js":13,"./JitsiRemoteTrack.js":14,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils.js":18,"events":43}],17:[function(require,module,exports){
  1684. var currentBrowser;
  1685. var browserVersion;
  1686. var isAndroid;
  1687. var RTCBrowserType = {
  1688. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  1689. RTC_BROWSER_OPERA: "rtc_browser.opera",
  1690. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  1691. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  1692. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  1693. getBrowserType: function () {
  1694. return currentBrowser;
  1695. },
  1696. isChrome: function () {
  1697. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  1698. },
  1699. isOpera: function () {
  1700. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  1701. },
  1702. isFirefox: function () {
  1703. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  1704. },
  1705. isIExplorer: function () {
  1706. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1707. },
  1708. isSafari: function () {
  1709. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  1710. },
  1711. isTemasysPluginUsed: function () {
  1712. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  1713. },
  1714. getFirefoxVersion: function () {
  1715. return RTCBrowserType.isFirefox() ? browserVersion : null;
  1716. },
  1717. getChromeVersion: function () {
  1718. return RTCBrowserType.isChrome() ? browserVersion : null;
  1719. },
  1720. usesPlanB: function() {
  1721. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  1722. RTCBrowserType.isTemasysPluginUsed();
  1723. },
  1724. usesUnifiedPlan: function() {
  1725. return RTCBrowserType.isFirefox();
  1726. },
  1727. /**
  1728. * Whether the browser is running on an android device.
  1729. */
  1730. isAndroid: function() {
  1731. return isAndroid;
  1732. }
  1733. // Add version getters for other browsers when needed
  1734. };
  1735. // detectOpera() must be called before detectChrome() !!!
  1736. // otherwise Opera wil be detected as Chrome
  1737. function detectChrome() {
  1738. if (navigator.webkitGetUserMedia) {
  1739. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  1740. var userAgent = navigator.userAgent.toLowerCase();
  1741. // We can assume that user agent is chrome, because it's
  1742. // enforced when 'ext' streaming method is set
  1743. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  1744. console.log("This appears to be Chrome, ver: " + ver);
  1745. return ver;
  1746. }
  1747. return null;
  1748. }
  1749. function detectOpera() {
  1750. var userAgent = navigator.userAgent;
  1751. if (userAgent.match(/Opera|OPR/)) {
  1752. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  1753. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  1754. console.info("This appears to be Opera, ver: " + version);
  1755. return version;
  1756. }
  1757. return null;
  1758. }
  1759. function detectFirefox() {
  1760. if (navigator.mozGetUserMedia) {
  1761. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1762. var version = parseInt(
  1763. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1764. console.log('This appears to be Firefox, ver: ' + version);
  1765. return version;
  1766. }
  1767. return null;
  1768. }
  1769. function detectSafari() {
  1770. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1771. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1772. console.info("This appears to be Safari");
  1773. // FIXME detect Safari version when needed
  1774. return 1;
  1775. }
  1776. return null;
  1777. }
  1778. function detectIE() {
  1779. var version;
  1780. var ua = window.navigator.userAgent;
  1781. var msie = ua.indexOf('MSIE ');
  1782. if (msie > 0) {
  1783. // IE 10 or older => return version number
  1784. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1785. }
  1786. var trident = ua.indexOf('Trident/');
  1787. if (!version && trident > 0) {
  1788. // IE 11 => return version number
  1789. var rv = ua.indexOf('rv:');
  1790. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1791. }
  1792. var edge = ua.indexOf('Edge/');
  1793. if (!version && edge > 0) {
  1794. // IE 12 => return version number
  1795. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1796. }
  1797. if (version) {
  1798. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1799. console.info("This appears to be IExplorer, ver: " + version);
  1800. }
  1801. return version;
  1802. }
  1803. function detectBrowser() {
  1804. var version;
  1805. var detectors = [
  1806. detectOpera,
  1807. detectChrome,
  1808. detectFirefox,
  1809. detectIE,
  1810. detectSafari
  1811. ];
  1812. // Try all browser detectors
  1813. for (var i = 0; i < detectors.length; i++) {
  1814. version = detectors[i]();
  1815. if (version)
  1816. return version;
  1817. }
  1818. console.error("Failed to detect browser type");
  1819. return undefined;
  1820. }
  1821. browserVersion = detectBrowser();
  1822. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1823. module.exports = RTCBrowserType;
  1824. },{}],18:[function(require,module,exports){
  1825. (function (__filename){
  1826. /* global config, require, attachMediaStream, getUserMedia */
  1827. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1828. var RTCBrowserType = require("./RTCBrowserType");
  1829. var Resolutions = require("../../service/RTC/Resolutions");
  1830. var RTCEvents = require("../../service/RTC/RTCEvents");
  1831. var AdapterJS = require("./adapter.screenshare");
  1832. var SDPUtil = require("../xmpp/SDPUtil");
  1833. var EventEmitter = require("events");
  1834. var screenObtainer = require("./ScreenObtainer");
  1835. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  1836. var eventEmitter = new EventEmitter();
  1837. var devices = {
  1838. audio: true,
  1839. video: true
  1840. }
  1841. var rtcReady = false;
  1842. function setResolutionConstraints(constraints, resolution) {
  1843. var isAndroid = RTCBrowserType.isAndroid();
  1844. if (Resolutions[resolution]) {
  1845. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1846. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1847. }
  1848. else if (isAndroid) {
  1849. // FIXME can't remember if the purpose of this was to always request
  1850. // low resolution on Android ? if yes it should be moved up front
  1851. constraints.video.mandatory.minWidth = 320;
  1852. constraints.video.mandatory.minHeight = 240;
  1853. constraints.video.mandatory.maxFrameRate = 15;
  1854. }
  1855. if (constraints.video.mandatory.minWidth)
  1856. constraints.video.mandatory.maxWidth =
  1857. constraints.video.mandatory.minWidth;
  1858. if (constraints.video.mandatory.minHeight)
  1859. constraints.video.mandatory.maxHeight =
  1860. constraints.video.mandatory.minHeight;
  1861. }
  1862. /**
  1863. * @param {string[]} um required user media types
  1864. *
  1865. * @param {Object} [options={}] optional parameters
  1866. * @param {string} options.resolution
  1867. * @param {number} options.bandwidth
  1868. * @param {number} options.fps
  1869. * @param {string} options.desktopStream
  1870. * @param {string} options.cameraDeviceId
  1871. * @param {string} options.micDeviceId
  1872. * @param {bool} firefox_fake_device
  1873. */
  1874. function getConstraints(um, options) {
  1875. var constraints = {audio: false, video: false};
  1876. if (um.indexOf('video') >= 0) {
  1877. // same behaviour as true
  1878. constraints.video = { mandatory: {}, optional: [] };
  1879. if (options.cameraDeviceId) {
  1880. constraints.video.optional.push({
  1881. sourceId: options.cameraDeviceId
  1882. });
  1883. }
  1884. constraints.video.optional.push({ googLeakyBucket: true });
  1885. setResolutionConstraints(constraints, options.resolution);
  1886. }
  1887. if (um.indexOf('audio') >= 0) {
  1888. if (!RTCBrowserType.isFirefox()) {
  1889. // same behaviour as true
  1890. constraints.audio = { mandatory: {}, optional: []};
  1891. if (options.micDeviceId) {
  1892. constraints.audio.optional.push({
  1893. sourceId: options.micDeviceId
  1894. });
  1895. }
  1896. // if it is good enough for hangouts...
  1897. constraints.audio.optional.push(
  1898. {googEchoCancellation: true},
  1899. {googAutoGainControl: true},
  1900. {googNoiseSupression: true},
  1901. {googHighpassFilter: true},
  1902. {googNoisesuppression2: true},
  1903. {googEchoCancellation2: true},
  1904. {googAutoGainControl2: true}
  1905. );
  1906. } else {
  1907. if (options.micDeviceId) {
  1908. constraints.audio = {
  1909. mandatory: {},
  1910. optional: [{
  1911. sourceId: options.micDeviceId
  1912. }]};
  1913. } else {
  1914. constraints.audio = true;
  1915. }
  1916. }
  1917. }
  1918. if (um.indexOf('screen') >= 0) {
  1919. if (RTCBrowserType.isChrome()) {
  1920. constraints.video = {
  1921. mandatory: {
  1922. chromeMediaSource: "screen",
  1923. googLeakyBucket: true,
  1924. maxWidth: window.screen.width,
  1925. maxHeight: window.screen.height,
  1926. maxFrameRate: 3
  1927. },
  1928. optional: []
  1929. };
  1930. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1931. constraints.video = {
  1932. optional: [
  1933. {
  1934. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1935. }
  1936. ]
  1937. };
  1938. } else if (RTCBrowserType.isFirefox()) {
  1939. constraints.video = {
  1940. mozMediaSource: "window",
  1941. mediaSource: "window"
  1942. };
  1943. } else {
  1944. logger.error(
  1945. "'screen' WebRTC media source is supported only in Chrome" +
  1946. " and with Temasys plugin");
  1947. }
  1948. }
  1949. if (um.indexOf('desktop') >= 0) {
  1950. constraints.video = {
  1951. mandatory: {
  1952. chromeMediaSource: "desktop",
  1953. chromeMediaSourceId: options.desktopStream,
  1954. googLeakyBucket: true,
  1955. maxWidth: window.screen.width,
  1956. maxHeight: window.screen.height,
  1957. maxFrameRate: 3
  1958. },
  1959. optional: []
  1960. };
  1961. }
  1962. if (options.bandwidth) {
  1963. if (!constraints.video) {
  1964. //same behaviour as true
  1965. constraints.video = {mandatory: {}, optional: []};
  1966. }
  1967. constraints.video.optional.push({bandwidth: options.bandwidth});
  1968. }
  1969. if (options.fps) {
  1970. // for some cameras it might be necessary to request 30fps
  1971. // so they choose 30fps mjpg over 10fps yuy2
  1972. if (!constraints.video) {
  1973. // same behaviour as true;
  1974. constraints.video = {mandatory: {}, optional: []};
  1975. }
  1976. constraints.video.mandatory.minFrameRate = options.fps;
  1977. }
  1978. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  1979. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  1980. // this later can be a problem with some of the tests
  1981. if(RTCBrowserType.isFirefox() && options.firefox_fake_device)
  1982. {
  1983. constraints.audio = true;
  1984. constraints.fake = true;
  1985. }
  1986. return constraints;
  1987. }
  1988. function setAvailableDevices(um, available) {
  1989. if (um.indexOf("video") != -1) {
  1990. devices.video = available;
  1991. }
  1992. if (um.indexOf("audio") != -1) {
  1993. devices.audio = available;
  1994. }
  1995. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  1996. }
  1997. // In case of IE we continue from 'onReady' callback
  1998. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  1999. // once it is initialized.
  2000. function onReady (options, GUM) {
  2001. rtcReady = true;
  2002. eventEmitter.emit(RTCEvents.RTC_READY, true);
  2003. screenObtainer.init(eventEmitter, options, GUM);
  2004. };
  2005. /**
  2006. * Apply function with arguments if function exists.
  2007. * Do nothing if function not provided.
  2008. * @param {function} [fn] function to apply
  2009. * @param {Array} [args=[]] arguments for function
  2010. */
  2011. function maybeApply(fn, args) {
  2012. if (fn) {
  2013. fn.apply(null, args || []);
  2014. }
  2015. }
  2016. var getUserMediaStatus = {
  2017. initialized: false,
  2018. callbacks: []
  2019. };
  2020. /**
  2021. * Wrap `getUserMedia` to allow others to know if it was executed at least
  2022. * once or not. Wrapper function uses `getUserMediaStatus` object.
  2023. * @param {Function} getUserMedia native function
  2024. * @returns {Function} wrapped function
  2025. */
  2026. function wrapGetUserMedia(getUserMedia) {
  2027. return function (constraints, successCallback, errorCallback) {
  2028. getUserMedia(constraints, function (stream) {
  2029. maybeApply(successCallback, [stream]);
  2030. if (!getUserMediaStatus.initialized) {
  2031. getUserMediaStatus.initialized = true;
  2032. getUserMediaStatus.callbacks.forEach(function (callback) {
  2033. callback();
  2034. });
  2035. getUserMediaStatus.callbacks.length = 0;
  2036. }
  2037. }, function (error) {
  2038. maybeApply(errorCallback, [error]);
  2039. });
  2040. };
  2041. }
  2042. /**
  2043. * Create stub device which equals to auto selected device.
  2044. * @param {string} kind if that should be `audio` or `video` device
  2045. * @returns {Object} stub device description in `enumerateDevices` format
  2046. */
  2047. function createAutoDeviceInfo(kind) {
  2048. return {
  2049. facing: null,
  2050. label: 'Auto',
  2051. kind: kind,
  2052. deviceId: '',
  2053. groupId: null
  2054. };
  2055. }
  2056. /**
  2057. * Execute function after getUserMedia was executed at least once.
  2058. * @param {Function} callback function to execute after getUserMedia
  2059. */
  2060. function afterUserMediaInitialized(callback) {
  2061. if (getUserMediaStatus.initialized) {
  2062. callback();
  2063. } else {
  2064. getUserMediaStatus.callbacks.push(callback);
  2065. }
  2066. }
  2067. /**
  2068. * Wrapper function which makes enumerateDevices to wait
  2069. * until someone executes getUserMedia first time.
  2070. * @param {Function} enumerateDevices native function
  2071. * @returns {Funtion} wrapped function
  2072. */
  2073. function wrapEnumerateDevices(enumerateDevices) {
  2074. return function (callback) {
  2075. // enumerate devices only after initial getUserMedia
  2076. afterUserMediaInitialized(function () {
  2077. enumerateDevices().then(function (devices) {
  2078. //add auto devices
  2079. devices.unshift(
  2080. createAutoDeviceInfo('audioinput'),
  2081. createAutoDeviceInfo('videoinput')
  2082. );
  2083. callback(devices);
  2084. }, function (err) {
  2085. console.error('cannot enumerate devices: ', err);
  2086. // return only auto devices
  2087. callback([createAutoDeviceInfo('audioInput'),
  2088. createAutoDeviceInfo('videoinput')]);
  2089. });
  2090. });
  2091. };
  2092. }
  2093. /**
  2094. * Use old MediaStreamTrack to get devices list and
  2095. * convert it to enumerateDevices format.
  2096. * @param {Function} callback function to call when received devices list.
  2097. */
  2098. function enumerateDevicesThroughMediaStreamTrack (callback) {
  2099. MediaStreamTrack.getSources(function (sources) {
  2100. var devices = sources.map(function (source) {
  2101. var kind = (source.kind || '').toLowerCase();
  2102. return {
  2103. facing: source.facing || null,
  2104. label: source.label,
  2105. kind: kind ? kind + 'input': null,
  2106. deviceId: source.id,
  2107. groupId: source.groupId || null
  2108. };
  2109. });
  2110. //add auto devices
  2111. devices.unshift(
  2112. createAutoDeviceInfo('audioinput'),
  2113. createAutoDeviceInfo('videoinput')
  2114. );
  2115. callback(devices);
  2116. });
  2117. }
  2118. function obtainDevices(options) {
  2119. if(!options.devices || options.devices.length === 0) {
  2120. return options.successCallback(streams);
  2121. }
  2122. var device = options.devices.splice(0, 1);
  2123. options.deviceGUM[device](function (stream) {
  2124. options.streams[device] = stream;
  2125. obtainDevices(options);
  2126. },
  2127. function (error) {
  2128. logger.error(
  2129. "failed to obtain " + device + " stream - stop", error);
  2130. options.errorCallback(JitsiTrackErrors.parseError(error));
  2131. });
  2132. }
  2133. /**
  2134. * Handles the newly created Media Streams.
  2135. * @param streams the new Media Streams
  2136. * @param resolution the resolution of the video streams
  2137. * @returns {*[]} object that describes the new streams
  2138. */
  2139. function handleLocalStream(streams, resolution) {
  2140. var audioStream, videoStream, desktopStream, res = [];
  2141. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  2142. // an object with two properties: audioStream, videoStream.
  2143. if (window.webkitMediaStream) {
  2144. var audioVideo = streams.audioVideo;
  2145. if (audioVideo) {
  2146. var audioTracks = audioVideo.getAudioTracks();
  2147. if(audioTracks.length) {
  2148. audioStream = new webkitMediaStream();
  2149. for (var i = 0; i < audioTracks.length; i++) {
  2150. audioStream.addTrack(audioTracks[i]);
  2151. }
  2152. }
  2153. var videoTracks = audioVideo.getVideoTracks();
  2154. if(videoTracks.length) {
  2155. videoStream = new webkitMediaStream();
  2156. for (i = 0; i < videoTracks.length; i++) {
  2157. videoStream.addTrack(videoTracks[i]);
  2158. }
  2159. }
  2160. }
  2161. }
  2162. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  2163. if (streams && streams.audioStream)
  2164. audioStream = streams.audioStream;
  2165. if (streams && streams.videoStream)
  2166. videoStream = streams.videoStream;
  2167. }
  2168. if (streams && streams.desktopStream)
  2169. res.push({stream: streams.desktopStream,
  2170. type: "video", videoType: "desktop"});
  2171. if(audioStream)
  2172. res.push({stream: audioStream, type: "audio", videoType: null});
  2173. if(videoStream)
  2174. res.push({stream: videoStream, type: "video", videoType: "camera",
  2175. resolution: resolution});
  2176. return res;
  2177. }
  2178. //Options parameter is to pass config options. Currently uses only "useIPv6".
  2179. var RTCUtils = {
  2180. init: function (options) {
  2181. return new Promise(function(resolve, reject) {
  2182. if (RTCBrowserType.isFirefox()) {
  2183. var FFversion = RTCBrowserType.getFirefoxVersion();
  2184. if (FFversion < 40) {
  2185. logger.error(
  2186. "Firefox version too old: " + FFversion +
  2187. ". Required >= 40.");
  2188. reject(new Error("Firefox version too old: " + FFversion +
  2189. ". Required >= 40."));
  2190. return;
  2191. }
  2192. this.peerconnection = mozRTCPeerConnection;
  2193. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  2194. this.enumerateDevices = wrapEnumerateDevices(
  2195. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2196. );
  2197. this.pc_constraints = {};
  2198. this.attachMediaStream = function (element, stream) {
  2199. // srcObject is being standardized and FF will eventually
  2200. // support that unprefixed. FF also supports the
  2201. // "element.src = URL.createObjectURL(...)" combo, but that
  2202. // will be deprecated in favour of srcObject.
  2203. //
  2204. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  2205. // https://github.com/webrtc/samples/issues/302
  2206. if (!element[0])
  2207. return;
  2208. element[0].mozSrcObject = stream;
  2209. element[0].play();
  2210. };
  2211. this.getStreamID = function (stream) {
  2212. var id = stream.id;
  2213. if (!id) {
  2214. var tracks = stream.getVideoTracks();
  2215. if (!tracks || tracks.length === 0) {
  2216. tracks = stream.getAudioTracks();
  2217. }
  2218. id = tracks[0].id;
  2219. }
  2220. return SDPUtil.filter_special_chars(id);
  2221. };
  2222. this.getVideoSrc = function (element) {
  2223. if (!element)
  2224. return null;
  2225. return element.mozSrcObject;
  2226. };
  2227. this.setVideoSrc = function (element, src) {
  2228. if (element)
  2229. element.mozSrcObject = src;
  2230. };
  2231. RTCSessionDescription = mozRTCSessionDescription;
  2232. RTCIceCandidate = mozRTCIceCandidate;
  2233. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  2234. this.peerconnection = webkitRTCPeerConnection;
  2235. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2236. if (navigator.mediaDevices) {
  2237. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  2238. this.enumerateDevices = wrapEnumerateDevices(
  2239. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2240. );
  2241. } else {
  2242. this.getUserMedia = getUserMedia;
  2243. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2244. }
  2245. this.attachMediaStream = function (element, stream) {
  2246. element.attr('src', webkitURL.createObjectURL(stream));
  2247. };
  2248. this.getStreamID = function (stream) {
  2249. // streams from FF endpoints have the characters '{' and '}'
  2250. // that make jQuery choke.
  2251. return SDPUtil.filter_special_chars(stream.id);
  2252. };
  2253. this.getVideoSrc = function (element) {
  2254. if (!element)
  2255. return null;
  2256. return element.getAttribute("src");
  2257. };
  2258. this.setVideoSrc = function (element, src) {
  2259. if (element)
  2260. element.setAttribute("src", src);
  2261. };
  2262. // DTLS should now be enabled by default but..
  2263. this.pc_constraints = {'optional': [
  2264. {'DtlsSrtpKeyAgreement': 'true'}
  2265. ]};
  2266. if (options.useIPv6) {
  2267. // https://code.google.com/p/webrtc/issues/detail?id=2828
  2268. this.pc_constraints.optional.push({googIPv6: true});
  2269. }
  2270. if (RTCBrowserType.isAndroid()) {
  2271. this.pc_constraints = {}; // disable DTLS on Android
  2272. }
  2273. if (!webkitMediaStream.prototype.getVideoTracks) {
  2274. webkitMediaStream.prototype.getVideoTracks = function () {
  2275. return this.videoTracks;
  2276. };
  2277. }
  2278. if (!webkitMediaStream.prototype.getAudioTracks) {
  2279. webkitMediaStream.prototype.getAudioTracks = function () {
  2280. return this.audioTracks;
  2281. };
  2282. }
  2283. }
  2284. // Detect IE/Safari
  2285. else if (RTCBrowserType.isTemasysPluginUsed()) {
  2286. //AdapterJS.WebRTCPlugin.setLogLevel(
  2287. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  2288. AdapterJS.webRTCReady(function (isPlugin) {
  2289. self.peerconnection = RTCPeerConnection;
  2290. self.getUserMedia = window.getUserMedia;
  2291. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2292. self.attachMediaStream = function (elSel, stream) {
  2293. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  2294. return;
  2295. }
  2296. attachMediaStream(elSel[0], stream);
  2297. };
  2298. self.getStreamID = function (stream) {
  2299. var id = SDPUtil.filter_special_chars(stream.label);
  2300. return id;
  2301. };
  2302. self.getVideoSrc = function (element) {
  2303. if (!element) {
  2304. logger.warn("Attempt to get video SRC of null element");
  2305. return null;
  2306. }
  2307. var children = element.children;
  2308. for (var i = 0; i !== children.length; ++i) {
  2309. if (children[i].name === 'streamId') {
  2310. return children[i].value;
  2311. }
  2312. }
  2313. //logger.info(element.id + " SRC: " + src);
  2314. return null;
  2315. };
  2316. self.setVideoSrc = function (element, src) {
  2317. //logger.info("Set video src: ", element, src);
  2318. if (!src) {
  2319. logger.warn("Not attaching video stream, 'src' is null");
  2320. return;
  2321. }
  2322. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2323. var stream = AdapterJS.WebRTCPlugin.plugin
  2324. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  2325. attachMediaStream(element, stream);
  2326. };
  2327. onReady(options, self.getUserMediaWithConstraints);
  2328. resolve();
  2329. });
  2330. } else {
  2331. try {
  2332. logger.error('Browser does not appear to be WebRTC-capable');
  2333. } catch (e) {
  2334. }
  2335. reject('Browser does not appear to be WebRTC-capable');
  2336. return;
  2337. }
  2338. // Call onReady() if Temasys plugin is not used
  2339. if (!RTCBrowserType.isTemasysPluginUsed()) {
  2340. onReady(options, self.getUserMediaWithConstraints);
  2341. resolve();
  2342. }
  2343. }.bind(this));
  2344. },
  2345. /**
  2346. * @param {string[]} um required user media types
  2347. * @param {function} success_callback
  2348. * @param {Function} failure_callback
  2349. * @param {Object} [options] optional parameters
  2350. * @param {string} options.resolution
  2351. * @param {number} options.bandwidth
  2352. * @param {number} options.fps
  2353. * @param {string} options.desktopStream
  2354. * @param {string} options.cameraDeviceId
  2355. * @param {string} options.micDeviceId
  2356. **/
  2357. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  2358. options = options || {};
  2359. resolution = options.resolution;
  2360. var constraints = getConstraints(
  2361. um, options);
  2362. logger.info("Get media constraints", constraints);
  2363. try {
  2364. this.getUserMedia(constraints,
  2365. function (stream) {
  2366. logger.log('onUserMediaSuccess');
  2367. setAvailableDevices(um, true);
  2368. success_callback(stream);
  2369. },
  2370. function (error) {
  2371. setAvailableDevices(um, false);
  2372. logger.warn('Failed to get access to local media. Error ',
  2373. error, constraints);
  2374. if (failure_callback) {
  2375. failure_callback(error, resolution);
  2376. }
  2377. });
  2378. } catch (e) {
  2379. logger.error('GUM failed: ', e);
  2380. if (failure_callback) {
  2381. failure_callback(e);
  2382. }
  2383. }
  2384. },
  2385. /**
  2386. * Creates the local MediaStreams.
  2387. * @param {Object} [options] optional parameters
  2388. * @param {Array} options.devices the devices that will be requested
  2389. * @param {string} options.resolution resolution constraints
  2390. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2391. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2392. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2393. * @param {string} options.cameraDeviceId
  2394. * @param {string} options.micDeviceId
  2395. * @returns {*} Promise object that will receive the new JitsiTracks
  2396. */
  2397. obtainAudioAndVideoPermissions: function (options) {
  2398. var self = this;
  2399. options = options || {};
  2400. return new Promise(function (resolve, reject) {
  2401. var successCallback = function (stream) {
  2402. resolve(handleLocalStream(stream, options.resolution));
  2403. };
  2404. options.devices = options.devices || ['audio', 'video'];
  2405. if(!screenObtainer.isSupported()
  2406. && options.devices.indexOf("desktop") !== -1){
  2407. reject(new Error("Desktop sharing is not supported!"));
  2408. }
  2409. if (RTCBrowserType.isFirefox() ||
  2410. RTCBrowserType.isTemasysPluginUsed()) {
  2411. var GUM = function (device, s, e) {
  2412. this.getUserMediaWithConstraints(device, s, e, options);
  2413. }
  2414. var deviceGUM = {
  2415. "audio": GUM.bind(self, ["audio"]),
  2416. "video": GUM.bind(self, ["video"]),
  2417. "desktop": screenObtainer.obtainStream
  2418. }
  2419. // With FF/IE we can't split the stream into audio and video because FF
  2420. // doesn't support media stream constructors. So, we need to get the
  2421. // audio stream separately from the video stream using two distinct GUM
  2422. // calls. Not very user friendly :-( but we don't have many other
  2423. // options neither.
  2424. //
  2425. // Note that we pack those 2 streams in a single object and pass it to
  2426. // the successCallback method.
  2427. obtainDevices({
  2428. devices: options.devices,
  2429. successCallback: successCallback,
  2430. errorCallback: reject,
  2431. deviceGUM: deviceGUM
  2432. });
  2433. } else {
  2434. var hasDesktop = false;
  2435. if(hasDesktop = options.devices.indexOf("desktop") !== -1) {
  2436. options.devices.splice(options.devices.indexOf("desktop"), 1);
  2437. }
  2438. options.resolution = options.resolution || '360';
  2439. if(options.devices.length) {
  2440. this.getUserMediaWithConstraints(
  2441. options.devices,
  2442. function (stream) {
  2443. if(hasDesktop) {
  2444. screenObtainer.obtainStream(
  2445. function (desktopStream) {
  2446. successCallback({audioVideo: stream,
  2447. desktopStream: desktopStream});
  2448. }, function (error) {
  2449. reject(
  2450. JitsiTrackErrors.parseError(error));
  2451. });
  2452. } else {
  2453. successCallback({audioVideo: stream});
  2454. }
  2455. },
  2456. function (error) {
  2457. reject(JitsiTrackErrors.parseError(error));
  2458. },
  2459. options);
  2460. } else if (hasDesktop) {
  2461. screenObtainer.obtainStream(
  2462. function (stream) {
  2463. successCallback({desktopStream: stream});
  2464. }, function (error) {
  2465. reject(
  2466. JitsiTrackErrors.parseError(error));
  2467. });
  2468. }
  2469. }
  2470. }.bind(this));
  2471. },
  2472. addListener: function (eventType, listener) {
  2473. eventEmitter.on(eventType, listener);
  2474. },
  2475. removeListener: function (eventType, listener) {
  2476. eventEmitter.removeListener(eventType, listener);
  2477. },
  2478. getDeviceAvailability: function () {
  2479. return devices;
  2480. },
  2481. isRTCReady: function () {
  2482. return rtcReady;
  2483. },
  2484. /**
  2485. * Checks if its possible to enumerate available cameras/micropones.
  2486. * @returns {boolean} true if available, false otherwise.
  2487. */
  2488. isDeviceListAvailable: function () {
  2489. var isEnumerateDevicesAvailable = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  2490. if (isEnumerateDevicesAvailable) {
  2491. return true;
  2492. }
  2493. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  2494. },
  2495. /**
  2496. * A method to handle stopping of the stream.
  2497. * One point to handle the differences in various implementations.
  2498. * @param mediaStream MediaStream object to stop.
  2499. */
  2500. stopMediaStream: function (mediaStream) {
  2501. mediaStream.getTracks().forEach(function (track) {
  2502. // stop() not supported with IE
  2503. if (track.stop) {
  2504. track.stop();
  2505. }
  2506. });
  2507. // leave stop for implementation still using it
  2508. if (mediaStream.stop) {
  2509. mediaStream.stop();
  2510. }
  2511. }
  2512. };
  2513. module.exports = RTCUtils;
  2514. }).call(this,"/modules/RTC/RTCUtils.js")
  2515. },{"../../JitsiTrackErrors":9,"../../service/RTC/RTCEvents":79,"../../service/RTC/Resolutions":80,"../xmpp/SDPUtil":32,"./RTCBrowserType":17,"./ScreenObtainer":19,"./adapter.screenshare":20,"events":43,"jitsi-meet-logger":47}],19:[function(require,module,exports){
  2516. (function (__filename){
  2517. /* global chrome, $, alert */
  2518. /* jshint -W003 */
  2519. var logger = require("jitsi-meet-logger").getLogger(__filename);
  2520. var RTCBrowserType = require("./RTCBrowserType");
  2521. var AdapterJS = require("./adapter.screenshare");
  2522. var DesktopSharingEventTypes
  2523. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2524. /**
  2525. * Indicates whether the Chrome desktop sharing extension is installed.
  2526. * @type {boolean}
  2527. */
  2528. var chromeExtInstalled = false;
  2529. /**
  2530. * Indicates whether an update of the Chrome desktop sharing extension is
  2531. * required.
  2532. * @type {boolean}
  2533. */
  2534. var chromeExtUpdateRequired = false;
  2535. /**
  2536. * Whether the jidesha extension for firefox is installed for the domain on
  2537. * which we are running. Null designates an unknown value.
  2538. * @type {null}
  2539. */
  2540. var firefoxExtInstalled = null;
  2541. /**
  2542. * If set to true, detection of an installed firefox extension will be started
  2543. * again the next time obtainScreenOnFirefox is called (e.g. next time the
  2544. * user tries to enable screen sharing).
  2545. */
  2546. var reDetectFirefoxExtension = false;
  2547. var GUM = null;
  2548. /**
  2549. * Handles obtaining a stream from a screen capture on different browsers.
  2550. */
  2551. var ScreenObtainer = {
  2552. /**
  2553. * The EventEmitter to use to emit events.
  2554. * @type {null}
  2555. */
  2556. eventEmitter: null,
  2557. obtainStream: null,
  2558. /**
  2559. * Initializes the function used to obtain a screen capture
  2560. * (this.obtainStream).
  2561. *
  2562. * If the browser is Chrome, it uses the value of
  2563. * 'options.desktopSharingChromeMethod' (or 'options.desktopSharing') to
  2564. * decide whether to use the a Chrome extension (if the value is 'ext'),
  2565. * use the "screen" media source (if the value is 'webrtc'),
  2566. * or disable screen capture (if the value is other).
  2567. * Note that for the "screen" media source to work the
  2568. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be set.
  2569. */
  2570. init: function(eventEmitter, options, gum) {
  2571. this.eventEmitter = eventEmitter;
  2572. var obtainDesktopStream = null;
  2573. this.options = options = options || {};
  2574. GUM = gum;
  2575. if (RTCBrowserType.isFirefox())
  2576. initFirefoxExtensionDetection(options);
  2577. // TODO remove this, options.desktopSharing is deprecated.
  2578. var chromeMethod =
  2579. (options.desktopSharingChromeMethod || options.desktopSharing);
  2580. if (RTCBrowserType.isTemasysPluginUsed()) {
  2581. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  2582. logger.info("Screensharing not supported by this plugin " +
  2583. "version");
  2584. } else if(!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2585. logger.info(
  2586. "Screensharing not available with Temasys plugin on" +
  2587. " this site");
  2588. } else {
  2589. obtainDesktopStream = obtainWebRTCScreen;
  2590. logger.info("Using Temasys plugin for desktop sharing");
  2591. }
  2592. } else if (RTCBrowserType.isChrome()) {
  2593. if (chromeMethod == "ext") {
  2594. if (RTCBrowserType.getChromeVersion() >= 34) {
  2595. obtainDesktopStream =
  2596. this.obtainScreenFromExtension;
  2597. logger.info("Using Chrome extension for desktop sharing");
  2598. initChromeExtension(options);
  2599. } else {
  2600. logger.info("Chrome extension not supported until ver 34");
  2601. }
  2602. } else if (chromeMethod == "webrtc") {
  2603. obtainDesktopStream = obtainWebRTCScreen;
  2604. logger.info("Using Chrome WebRTC for desktop sharing");
  2605. }
  2606. } else if (RTCBrowserType.isFirefox()) {
  2607. if (options.desktopSharingFirefoxDisabled) {
  2608. obtainDesktopStream = null;
  2609. } else if (window.location.protocol === "http:"){
  2610. logger.log("Screen sharing is not supported over HTTP. " +
  2611. "Use of HTTPS is required.");
  2612. obtainDesktopStream = null;
  2613. } else {
  2614. obtainDesktopStream = this.obtainScreenOnFirefox;
  2615. }
  2616. }
  2617. if (!obtainDesktopStream) {
  2618. logger.info("Desktop sharing disabled");
  2619. }
  2620. this.obtainStream = obtainDesktopStream;
  2621. },
  2622. /**
  2623. * Checks whether obtaining a screen capture is supported in the current
  2624. * environment.
  2625. * @returns {boolean}
  2626. */
  2627. isSupported: function() {
  2628. return !!this.obtainStream;
  2629. },
  2630. /**
  2631. * Obtains a screen capture stream on Firefox.
  2632. * @param callback
  2633. * @param errorCallback
  2634. */
  2635. obtainScreenOnFirefox:
  2636. function (callback, errorCallback) {
  2637. var self = this;
  2638. var extensionRequired = false;
  2639. if (this.options.desktopSharingFirefoxMaxVersionExtRequired === -1 ||
  2640. (this.options.desktopSharingFirefoxMaxVersionExtRequired >= 0 &&
  2641. RTCBrowserType.getFirefoxVersion() <=
  2642. this.options.desktopSharingFirefoxMaxVersionExtRequired)) {
  2643. extensionRequired = true;
  2644. logger.log("Jidesha extension required on firefox version " +
  2645. RTCBrowserType.getFirefoxVersion());
  2646. }
  2647. if (!extensionRequired || firefoxExtInstalled === true) {
  2648. obtainWebRTCScreen(callback, errorCallback);
  2649. return;
  2650. }
  2651. if (reDetectFirefoxExtension) {
  2652. reDetectFirefoxExtension = false;
  2653. initFirefoxExtensionDetection(this.options);
  2654. }
  2655. // Give it some (more) time to initialize, and assume lack of
  2656. // extension if it hasn't.
  2657. if (firefoxExtInstalled === null) {
  2658. window.setTimeout(
  2659. function() {
  2660. if (firefoxExtInstalled === null)
  2661. firefoxExtInstalled = false;
  2662. self.obtainScreenOnFirefox(callback, errorCallback);
  2663. },
  2664. 300
  2665. );
  2666. logger.log("Waiting for detection of jidesha on firefox to " +
  2667. "finish.");
  2668. return;
  2669. }
  2670. // We need an extension and it isn't installed.
  2671. // Make sure we check for the extension when the user clicks again.
  2672. firefoxExtInstalled = null;
  2673. reDetectFirefoxExtension = true;
  2674. // Prompt the user to install the extension
  2675. this.eventEmitter.emit(
  2676. DesktopSharingEventTypes.FIREFOX_EXTENSION_NEEDED,
  2677. this.options.desktopSharingFirefoxExtensionURL);
  2678. // Make sure desktopsharing knows that we failed, so that it doesn't get
  2679. // stuck in 'switching' mode.
  2680. errorCallback('Firefox extension required.');
  2681. },
  2682. /**
  2683. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  2684. * 'desktop' stream for returned stream token.
  2685. */
  2686. obtainScreenFromExtension: function (streamCallback, failCallback) {
  2687. if (chromeExtInstalled) {
  2688. doGetStreamFromExtension(this.options, streamCallback,
  2689. failCallback);
  2690. } else {
  2691. if (chromeExtUpdateRequired) {
  2692. alert(
  2693. 'Jitsi Desktop Streamer requires update. ' +
  2694. 'Changes will take effect after next Chrome restart.');
  2695. }
  2696. chrome.webstore.install(
  2697. getWebStoreInstallUrl(this.options),
  2698. function (arg) {
  2699. logger.log("Extension installed successfully", arg);
  2700. chromeExtInstalled = true;
  2701. // We need to give a moment for the endpoint to become
  2702. // available
  2703. window.setTimeout(function () {
  2704. doGetStreamFromExtension(this.options, streamCallback,
  2705. failCallback);
  2706. }, 500);
  2707. },
  2708. function (arg) {
  2709. logger.log("Failed to install the extension", arg);
  2710. failCallback(arg);
  2711. }
  2712. );
  2713. }
  2714. }
  2715. };
  2716. /**
  2717. * Obtains a desktop stream using getUserMedia.
  2718. * For this to work on Chrome, the
  2719. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  2720. *
  2721. * On firefox, the document's domain must be white-listed in the
  2722. * 'media.getusermedia.screensharing.allowed_domains' preference in
  2723. * 'about:config'.
  2724. */
  2725. function obtainWebRTCScreen(streamCallback, failCallback) {
  2726. GUM(
  2727. ['screen'],
  2728. streamCallback,
  2729. failCallback
  2730. );
  2731. }
  2732. /**
  2733. * Constructs inline install URL for Chrome desktop streaming extension.
  2734. * The 'chromeExtensionId' must be defined in options parameter.
  2735. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  2736. * @returns {string}
  2737. */
  2738. function getWebStoreInstallUrl(options)
  2739. {
  2740. //TODO remove chromeExtensionId (deprecated)
  2741. return "https://chrome.google.com/webstore/detail/" +
  2742. (options.desktopSharingChromeExtId || options.chromeExtensionId);
  2743. }
  2744. /**
  2745. * Checks whether an update of the Chrome extension is required.
  2746. * @param minVersion minimal required version
  2747. * @param extVersion current extension version
  2748. * @returns {boolean}
  2749. */
  2750. function isUpdateRequired(minVersion, extVersion) {
  2751. try {
  2752. var s1 = minVersion.split('.');
  2753. var s2 = extVersion.split('.');
  2754. var len = Math.max(s1.length, s2.length);
  2755. for (var i = 0; i < len; i++) {
  2756. var n1 = 0,
  2757. n2 = 0;
  2758. if (i < s1.length)
  2759. n1 = parseInt(s1[i]);
  2760. if (i < s2.length)
  2761. n2 = parseInt(s2[i]);
  2762. if (isNaN(n1) || isNaN(n2)) {
  2763. return true;
  2764. } else if (n1 !== n2) {
  2765. return n1 > n2;
  2766. }
  2767. }
  2768. // will happen if both versions have identical numbers in
  2769. // their components (even if one of them is longer, has more components)
  2770. return false;
  2771. }
  2772. catch (e) {
  2773. logger.error("Failed to parse extension version", e);
  2774. return true;
  2775. }
  2776. }
  2777. function checkChromeExtInstalled(callback, options) {
  2778. if (!chrome || !chrome.runtime) {
  2779. // No API, so no extension for sure
  2780. callback(false, false);
  2781. return;
  2782. }
  2783. chrome.runtime.sendMessage(
  2784. //TODO: remove chromeExtensionId (deprecated)
  2785. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  2786. { getVersion: true },
  2787. function (response) {
  2788. if (!response || !response.version) {
  2789. // Communication failure - assume that no endpoint exists
  2790. logger.warn(
  2791. "Extension not installed?: ", chrome.runtime.lastError);
  2792. callback(false, false);
  2793. return;
  2794. }
  2795. // Check installed extension version
  2796. var extVersion = response.version;
  2797. logger.log('Extension version is: ' + extVersion);
  2798. //TODO: remove minChromeExtVersion (deprecated)
  2799. var updateRequired
  2800. = isUpdateRequired(
  2801. (options.desktopSharingChromeMinExtVersion ||
  2802. options.minChromeExtVersion),
  2803. extVersion);
  2804. callback(!updateRequired, updateRequired);
  2805. }
  2806. );
  2807. }
  2808. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  2809. // Sends 'getStream' msg to the extension.
  2810. // Extension id must be defined in the config.
  2811. chrome.runtime.sendMessage(
  2812. //TODO: remove chromeExtensionId (deprecated)
  2813. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  2814. {
  2815. getStream: true,
  2816. //TODO: remove desktopSharingSources (deprecated).
  2817. sources: (options.desktopSharingChromeSources ||
  2818. options.desktopSharingSources)
  2819. },
  2820. function (response) {
  2821. if (!response) {
  2822. failCallback(chrome.runtime.lastError);
  2823. return;
  2824. }
  2825. logger.log("Response from extension: " + response);
  2826. if (response.streamId) {
  2827. GUM(
  2828. ['desktop'],
  2829. function (stream) {
  2830. streamCallback(stream);
  2831. },
  2832. failCallback,
  2833. {desktopStream: response.streamId});
  2834. } else {
  2835. failCallback("Extension failed to get the stream");
  2836. }
  2837. }
  2838. );
  2839. }
  2840. /**
  2841. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  2842. * config.js to support inline installs. Host site must be selected as main
  2843. * website of published extension.
  2844. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  2845. */
  2846. function initInlineInstalls(options)
  2847. {
  2848. $("link[rel=chrome-webstore-item]").attr("href",
  2849. getWebStoreInstallUrl(options));
  2850. }
  2851. function initChromeExtension(options) {
  2852. // Initialize Chrome extension inline installs
  2853. initInlineInstalls(options);
  2854. // Check if extension is installed
  2855. checkChromeExtInstalled(function (installed, updateRequired) {
  2856. chromeExtInstalled = installed;
  2857. chromeExtUpdateRequired = updateRequired;
  2858. logger.info(
  2859. "Chrome extension installed: " + chromeExtInstalled +
  2860. " updateRequired: " + chromeExtUpdateRequired);
  2861. }, options);
  2862. }
  2863. /**
  2864. * Starts the detection of an installed jidesha extension for firefox.
  2865. * @param options supports "desktopSharingFirefoxDisabled",
  2866. * "desktopSharingFirefoxExtId" and "chromeExtensionId"
  2867. */
  2868. function initFirefoxExtensionDetection(options) {
  2869. if (options.desktopSharingFirefoxDisabled) {
  2870. return;
  2871. }
  2872. if (firefoxExtInstalled === false || firefoxExtInstalled === true)
  2873. return;
  2874. if (!options.desktopSharingFirefoxExtId) {
  2875. firefoxExtInstalled = false;
  2876. return;
  2877. }
  2878. var img = document.createElement('img');
  2879. img.onload = function(){
  2880. logger.log("Detected firefox screen sharing extension.");
  2881. firefoxExtInstalled = true;
  2882. };
  2883. img.onerror = function(){
  2884. logger.log("Detected lack of firefox screen sharing extension.");
  2885. firefoxExtInstalled = false;
  2886. };
  2887. // The jidesha extension exposes an empty image file under the url:
  2888. // "chrome://EXT_ID/content/DOMAIN.png"
  2889. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  2890. // DOMAIN is a domain whitelisted by the extension.
  2891. var src = "chrome://" +
  2892. (options.desktopSharingFirefoxExtId.replace('@', '.')) +
  2893. "/content/" + document.location.hostname + ".png";
  2894. img.setAttribute('src', src);
  2895. }
  2896. module.exports = ScreenObtainer;
  2897. }).call(this,"/modules/RTC/ScreenObtainer.js")
  2898. },{"../../service/desktopsharing/DesktopSharingEventTypes":83,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":47}],20:[function(require,module,exports){
  2899. (function (__filename){
  2900. /*! adapterjs - v0.12.0 - 2015-09-04 */
  2901. var console = require("jitsi-meet-logger").getLogger(__filename);
  2902. // Adapter's interface.
  2903. var AdapterJS = AdapterJS || {};
  2904. // Browserify compatibility
  2905. if(typeof exports !== 'undefined') {
  2906. module.exports = AdapterJS;
  2907. }
  2908. AdapterJS.options = AdapterJS.options || {};
  2909. // uncomment to get virtual webcams
  2910. // AdapterJS.options.getAllCams = true;
  2911. // uncomment to prevent the install prompt when the plugin in not yet installed
  2912. // AdapterJS.options.hidePluginInstallPrompt = true;
  2913. // AdapterJS version
  2914. AdapterJS.VERSION = '0.12.0';
  2915. // This function will be called when the WebRTC API is ready to be used
  2916. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  2917. // the plugin
  2918. // You may Override this function to synchronise the start of your application
  2919. // with the WebRTC API being ready.
  2920. // If you decide not to override use this synchronisation, it may result in
  2921. // an extensive CPU usage on the plugin start (once per tab loaded)
  2922. // Params:
  2923. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  2924. //
  2925. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  2926. // The WebRTC API is ready.
  2927. // Override me and do whatever you want here
  2928. };
  2929. // Sets a callback function to be called when the WebRTC interface is ready.
  2930. // The first argument is the function to callback.\
  2931. // Throws an error if the first argument is not a function
  2932. AdapterJS.webRTCReady = function (callback) {
  2933. if (typeof callback !== 'function') {
  2934. throw new Error('Callback provided is not a function');
  2935. }
  2936. if (true === AdapterJS.onwebrtcreadyDone) {
  2937. // All WebRTC interfaces are ready, just call the callback
  2938. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  2939. } else {
  2940. // will be triggered automatically when your browser/plugin is ready.
  2941. AdapterJS.onwebrtcready = callback;
  2942. }
  2943. };
  2944. // Plugin namespace
  2945. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  2946. // The object to store plugin information
  2947. AdapterJS.WebRTCPlugin.pluginInfo = {
  2948. prefix : 'Tem',
  2949. plugName : 'TemWebRTCPlugin',
  2950. pluginId : 'plugin0',
  2951. type : 'application/x-temwebrtcplugin',
  2952. onload : '__TemWebRTCReady0',
  2953. portalLink : 'http://skylink.io/plugin/',
  2954. downloadLink : null, //set below
  2955. companyName: 'Temasys'
  2956. };
  2957. if(!!navigator.platform.match(/^Mac/i)) {
  2958. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  2959. }
  2960. else if(!!navigator.platform.match(/^Win/i)) {
  2961. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  2962. }
  2963. AdapterJS.WebRTCPlugin.TAGS = {
  2964. NONE : 'none',
  2965. AUDIO : 'audio',
  2966. VIDEO : 'video'
  2967. };
  2968. // Unique identifier of each opened page
  2969. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  2970. // Use this whenever you want to call the plugin.
  2971. AdapterJS.WebRTCPlugin.plugin = null;
  2972. // Set log level for the plugin once it is ready.
  2973. // The different values are
  2974. // This is an asynchronous function that will run when the plugin is ready
  2975. AdapterJS.WebRTCPlugin.setLogLevel = null;
  2976. // Defines webrtc's JS interface according to the plugin's implementation.
  2977. // Define plugin Browsers as WebRTC Interface.
  2978. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  2979. // This function detects whether or not a plugin is installed.
  2980. // Checks if Not IE (firefox, for example), else if it's IE,
  2981. // we're running IE and do something. If not it is not supported.
  2982. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  2983. // Lets adapter.js wait until the the document is ready before injecting the plugin
  2984. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  2985. // Inject the HTML DOM object element into the page.
  2986. AdapterJS.WebRTCPlugin.injectPlugin = null;
  2987. // States of readiness that the plugin goes through when
  2988. // being injected and stated
  2989. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  2990. NONE : 0, // no plugin use
  2991. INITIALIZING : 1, // Detected need for plugin
  2992. INJECTING : 2, // Injecting plugin
  2993. INJECTED: 3, // Plugin element injected but not usable yet
  2994. READY: 4 // Plugin ready to be used
  2995. };
  2996. // Current state of the plugin. You cannot use the plugin before this is
  2997. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  2998. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  2999. // True is AdapterJS.onwebrtcready was already called, false otherwise
  3000. // Used to make sure AdapterJS.onwebrtcready is only called once
  3001. AdapterJS.onwebrtcreadyDone = false;
  3002. // Log levels for the plugin.
  3003. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  3004. /*
  3005. Log outputs are prefixed in some cases.
  3006. INFO: Information reported by the plugin.
  3007. ERROR: Errors originating from within the plugin.
  3008. WEBRTC: Error originating from within the libWebRTC library
  3009. */
  3010. // From the least verbose to the most verbose
  3011. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  3012. NONE : 'NONE',
  3013. ERROR : 'ERROR',
  3014. WARNING : 'WARNING',
  3015. INFO: 'INFO',
  3016. VERBOSE: 'VERBOSE',
  3017. SENSITIVE: 'SENSITIVE'
  3018. };
  3019. // Does a waiting check before proceeding to load the plugin.
  3020. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  3021. // This methid will use an interval to wait for the plugin to be ready.
  3022. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  3023. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  3024. // This function will be called when plugin is ready. It sends necessary
  3025. // details to the plugin.
  3026. // The function will wait for the document to be ready and the set the
  3027. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  3028. // indicating that it can start being requested.
  3029. // This function is not in the IE/Safari condition brackets so that
  3030. // TemPluginLoaded function might be called on Chrome/Firefox.
  3031. // This function is the only private function that is not encapsulated to
  3032. // allow the plugin method to be called.
  3033. __TemWebRTCReady0 = function () {
  3034. if (document.readyState === 'complete') {
  3035. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3036. AdapterJS.maybeThroughWebRTCReady();
  3037. } else {
  3038. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  3039. if (document.readyState === 'complete') {
  3040. // TODO: update comments, we wait for the document to be ready
  3041. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  3042. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3043. AdapterJS.maybeThroughWebRTCReady();
  3044. }
  3045. }, 100);
  3046. }
  3047. };
  3048. AdapterJS.maybeThroughWebRTCReady = function() {
  3049. if (!AdapterJS.onwebrtcreadyDone) {
  3050. AdapterJS.onwebrtcreadyDone = true;
  3051. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  3052. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  3053. }
  3054. }
  3055. };
  3056. // Text namespace
  3057. AdapterJS.TEXT = {
  3058. PLUGIN: {
  3059. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  3060. 'to work on this browser.',
  3061. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  3062. BUTTON: 'Install Now'
  3063. },
  3064. REFRESH: {
  3065. REQUIRE_REFRESH: 'Please refresh page',
  3066. BUTTON: 'Refresh Page'
  3067. }
  3068. };
  3069. // The result of ice connection states.
  3070. // - starting: Ice connection is starting.
  3071. // - checking: Ice connection is checking.
  3072. // - connected Ice connection is connected.
  3073. // - completed Ice connection is connected.
  3074. // - done Ice connection has been completed.
  3075. // - disconnected Ice connection has been disconnected.
  3076. // - failed Ice connection has failed.
  3077. // - closed Ice connection is closed.
  3078. AdapterJS._iceConnectionStates = {
  3079. starting : 'starting',
  3080. checking : 'checking',
  3081. connected : 'connected',
  3082. completed : 'connected',
  3083. done : 'completed',
  3084. disconnected : 'disconnected',
  3085. failed : 'failed',
  3086. closed : 'closed'
  3087. };
  3088. //The IceConnection states that has been fired for each peer.
  3089. AdapterJS._iceConnectionFiredStates = [];
  3090. // Check if WebRTC Interface is defined.
  3091. AdapterJS.isDefined = null;
  3092. // This function helps to retrieve the webrtc detected browser information.
  3093. // This sets:
  3094. // - webrtcDetectedBrowser: The browser agent name.
  3095. // - webrtcDetectedVersion: The browser version.
  3096. // - webrtcDetectedType: The types of webRTC support.
  3097. // - 'moz': Mozilla implementation of webRTC.
  3098. // - 'webkit': WebKit implementation of webRTC.
  3099. // - 'plugin': Using the plugin implementation.
  3100. AdapterJS.parseWebrtcDetectedBrowser = function () {
  3101. var hasMatch, checkMatch = navigator.userAgent.match(
  3102. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  3103. if (/trident/i.test(checkMatch[1])) {
  3104. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  3105. webrtcDetectedBrowser = 'IE';
  3106. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  3107. } else if (checkMatch[1] === 'Chrome') {
  3108. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3109. if (hasMatch !== null) {
  3110. webrtcDetectedBrowser = 'opera';
  3111. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  3112. }
  3113. }
  3114. if (navigator.userAgent.indexOf('Safari')) {
  3115. if (typeof InstallTrigger !== 'undefined') {
  3116. webrtcDetectedBrowser = 'firefox';
  3117. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  3118. webrtcDetectedBrowser = 'IE';
  3119. } else if (
  3120. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  3121. webrtcDetectedBrowser = 'safari';
  3122. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  3123. webrtcDetectedBrowser = 'opera';
  3124. } else if (!!window.chrome) {
  3125. webrtcDetectedBrowser = 'chrome';
  3126. }
  3127. }
  3128. if (!webrtcDetectedBrowser) {
  3129. webrtcDetectedVersion = checkMatch[1];
  3130. }
  3131. if (!webrtcDetectedVersion) {
  3132. try {
  3133. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  3134. [navigator.appName, navigator.appVersion, '-?'];
  3135. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  3136. checkMatch.splice(1, 1, hasMatch[1]);
  3137. }
  3138. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  3139. } catch (error) { }
  3140. }
  3141. };
  3142. // To fix configuration as some browsers does not support
  3143. // the 'urls' attribute.
  3144. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  3145. if (pcConfig === null) {
  3146. return;
  3147. }
  3148. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  3149. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  3150. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  3151. delete pcConfig.iceServers[i].urls;
  3152. }
  3153. }
  3154. };
  3155. AdapterJS.addEvent = function(elem, evnt, func) {
  3156. if (elem.addEventListener) { // W3C DOM
  3157. elem.addEventListener(evnt, func, false);
  3158. } else if (elem.attachEvent) {// OLD IE DOM
  3159. elem.attachEvent('on'+evnt, func);
  3160. } else { // No much to do
  3161. elem[evnt] = func;
  3162. }
  3163. };
  3164. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  3165. // only inject once the page is ready
  3166. if (document.readyState !== 'complete') {
  3167. return;
  3168. }
  3169. var w = window;
  3170. var i = document.createElement('iframe');
  3171. i.style.position = 'fixed';
  3172. i.style.top = '-41px';
  3173. i.style.left = 0;
  3174. i.style.right = 0;
  3175. i.style.width = '100%';
  3176. i.style.height = '40px';
  3177. i.style.backgroundColor = '#ffffe1';
  3178. i.style.border = 'none';
  3179. i.style.borderBottom = '1px solid #888888';
  3180. i.style.zIndex = '9999999';
  3181. if(typeof i.style.webkitTransition === 'string') {
  3182. i.style.webkitTransition = 'all .5s ease-out';
  3183. } else if(typeof i.style.transition === 'string') {
  3184. i.style.transition = 'all .5s ease-out';
  3185. }
  3186. document.body.appendChild(i);
  3187. c = (i.contentWindow) ? i.contentWindow :
  3188. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  3189. c.document.open();
  3190. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  3191. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  3192. 'middle; cursor: default;">' + text + '</span>');
  3193. if(buttonText && buttonLink) {
  3194. c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
  3195. c.document.close();
  3196. // On click on okay
  3197. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  3198. if (!!displayRefreshBar) {
  3199. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  3200. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  3201. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  3202. }
  3203. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  3204. e.preventDefault();
  3205. try {
  3206. event.cancelBubble = true;
  3207. } catch(error) { }
  3208. var pluginInstallInterval = setInterval(function(){
  3209. if(! isIE) {
  3210. navigator.plugins.refresh(false);
  3211. }
  3212. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3213. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3214. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3215. function() { // plugin now installed
  3216. clearInterval(pluginInstallInterval);
  3217. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  3218. },
  3219. function() {
  3220. // still no plugin detected, nothing to do
  3221. });
  3222. } , 500);
  3223. });
  3224. // On click on Cancel
  3225. AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
  3226. w.document.body.removeChild(i);
  3227. });
  3228. } else {
  3229. c.document.close();
  3230. }
  3231. setTimeout(function() {
  3232. if(typeof i.style.webkitTransform === 'string') {
  3233. i.style.webkitTransform = 'translateY(40px)';
  3234. } else if(typeof i.style.transform === 'string') {
  3235. i.style.transform = 'translateY(40px)';
  3236. } else {
  3237. i.style.top = '0px';
  3238. }
  3239. }, 300);
  3240. };
  3241. // -----------------------------------------------------------
  3242. // Detected webrtc implementation. Types are:
  3243. // - 'moz': Mozilla implementation of webRTC.
  3244. // - 'webkit': WebKit implementation of webRTC.
  3245. // - 'plugin': Using the plugin implementation.
  3246. webrtcDetectedType = null;
  3247. // Detected webrtc datachannel support. Types are:
  3248. // - 'SCTP': SCTP datachannel support.
  3249. // - 'RTP': RTP datachannel support.
  3250. webrtcDetectedDCSupport = null;
  3251. // Set the settings for creating DataChannels, MediaStream for
  3252. // Cross-browser compability.
  3253. // - This is only for SCTP based support browsers.
  3254. // the 'urls' attribute.
  3255. checkMediaDataChannelSettings =
  3256. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  3257. if (typeof callback !== 'function') {
  3258. return;
  3259. }
  3260. var beOfferer = true;
  3261. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  3262. // Nightly version does not require MozDontOfferDataChannel for interop
  3263. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  3264. var isPeerFirefox = peerBrowserAgent === 'firefox';
  3265. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  3266. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  3267. // Resends an updated version of constraints for MozDataChannel to work
  3268. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  3269. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  3270. try {
  3271. delete constraints.mandatory.MozDontOfferDataChannel;
  3272. } catch (error) {
  3273. console.error('Failed deleting MozDontOfferDataChannel');
  3274. console.error(error);
  3275. }
  3276. } else if ((isLocalFirefox && !isPeerFirefox)) {
  3277. constraints.mandatory.MozDontOfferDataChannel = true;
  3278. }
  3279. if (!isLocalFirefox) {
  3280. // temporary measure to remove Moz* constraints in non Firefox browsers
  3281. for (var prop in constraints.mandatory) {
  3282. if (constraints.mandatory.hasOwnProperty(prop)) {
  3283. if (prop.indexOf('Moz') !== -1) {
  3284. delete constraints.mandatory[prop];
  3285. }
  3286. }
  3287. }
  3288. }
  3289. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  3290. // interopability of the media stream
  3291. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  3292. beOfferer = false;
  3293. }
  3294. callback(beOfferer, constraints);
  3295. };
  3296. // Handles the differences for all browsers ice connection state output.
  3297. // - Tested outcomes are:
  3298. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  3299. // - Chrome (answerer) : 'checking' > 'connected'
  3300. // - Firefox (offerer) : 'checking' > 'connected'
  3301. // - Firefox (answerer): 'checking' > 'connected'
  3302. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  3303. if (typeof callback !== 'function') {
  3304. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  3305. return;
  3306. }
  3307. peerId = (peerId) ? peerId : 'peer';
  3308. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  3309. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  3310. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  3311. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  3312. AdapterJS._iceConnectionFiredStates[peerId] = [];
  3313. }
  3314. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  3315. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  3316. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  3317. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  3318. setTimeout(function () {
  3319. AdapterJS._iceConnectionFiredStates[peerId]
  3320. .push(AdapterJS._iceConnectionStates.done);
  3321. callback(AdapterJS._iceConnectionStates.done);
  3322. }, 1000);
  3323. }
  3324. callback(iceConnectionState);
  3325. }
  3326. return;
  3327. };
  3328. // Firefox:
  3329. // - Creates iceServer from the url for Firefox.
  3330. // - Create iceServer with stun url.
  3331. // - Create iceServer with turn url.
  3332. // - Ignore the transport parameter from TURN url for FF version <=27.
  3333. // - Return null for createIceServer if transport=tcp.
  3334. // - FF 27 and above supports transport parameters in TURN url,
  3335. // - So passing in the full url to create iceServer.
  3336. // Chrome:
  3337. // - Creates iceServer from the url for Chrome M33 and earlier.
  3338. // - Create iceServer with stun url.
  3339. // - Chrome M28 & above uses below TURN format.
  3340. // Plugin:
  3341. // - Creates Ice Server for Plugin Browsers
  3342. // - If Stun - Create iceServer with stun url.
  3343. // - Else - Create iceServer with turn url
  3344. // - This is a WebRTC Function
  3345. createIceServer = null;
  3346. // Firefox:
  3347. // - Creates IceServers for Firefox
  3348. // - Use .url for FireFox.
  3349. // - Multiple Urls support
  3350. // Chrome:
  3351. // - Creates iceServers from the urls for Chrome M34 and above.
  3352. // - .urls is supported since Chrome M34.
  3353. // - Multiple Urls support
  3354. // Plugin:
  3355. // - Creates Ice Servers for Plugin Browsers
  3356. // - Multiple Urls support
  3357. // - This is a WebRTC Function
  3358. createIceServers = null;
  3359. //------------------------------------------------------------
  3360. //The RTCPeerConnection object.
  3361. RTCPeerConnection = null;
  3362. // Creates RTCSessionDescription object for Plugin Browsers
  3363. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  3364. RTCSessionDescription : null;
  3365. // Creates RTCIceCandidate object for Plugin Browsers
  3366. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  3367. RTCIceCandidate : null;
  3368. // Get UserMedia (only difference is the prefix).
  3369. // Code from Adam Barth.
  3370. getUserMedia = null;
  3371. // Attach a media stream to an element.
  3372. attachMediaStream = null;
  3373. // Re-attach a media stream to an element.
  3374. reattachMediaStream = null;
  3375. // Detected browser agent name. Types are:
  3376. // - 'firefox': Firefox browser.
  3377. // - 'chrome': Chrome browser.
  3378. // - 'opera': Opera browser.
  3379. // - 'safari': Safari browser.
  3380. // - 'IE' - Internet Explorer browser.
  3381. webrtcDetectedBrowser = null;
  3382. // Detected browser version.
  3383. webrtcDetectedVersion = null;
  3384. // Check for browser types and react accordingly
  3385. if (navigator.mozGetUserMedia) {
  3386. webrtcDetectedBrowser = 'firefox';
  3387. webrtcDetectedVersion = parseInt(navigator
  3388. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  3389. webrtcDetectedType = 'moz';
  3390. webrtcDetectedDCSupport = 'SCTP';
  3391. RTCPeerConnection = function (pcConfig, pcConstraints) {
  3392. AdapterJS.maybeFixConfiguration(pcConfig);
  3393. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  3394. };
  3395. // The RTCSessionDescription object.
  3396. RTCSessionDescription = mozRTCSessionDescription;
  3397. window.RTCSessionDescription = RTCSessionDescription;
  3398. // The RTCIceCandidate object.
  3399. RTCIceCandidate = mozRTCIceCandidate;
  3400. window.RTCIceCandidate = RTCIceCandidate;
  3401. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  3402. navigator.getUserMedia = window.getUserMedia;
  3403. // Shim for MediaStreamTrack.getSources.
  3404. MediaStreamTrack.getSources = function(successCb) {
  3405. setTimeout(function() {
  3406. var infos = [
  3407. { kind: 'audio', id: 'default', label:'', facing:'' },
  3408. { kind: 'video', id: 'default', label:'', facing:'' }
  3409. ];
  3410. successCb(infos);
  3411. }, 0);
  3412. };
  3413. createIceServer = function (url, username, password) {
  3414. var iceServer = null;
  3415. var url_parts = url.split(':');
  3416. if (url_parts[0].indexOf('stun') === 0) {
  3417. iceServer = { url : url };
  3418. } else if (url_parts[0].indexOf('turn') === 0) {
  3419. if (webrtcDetectedVersion < 27) {
  3420. var turn_url_parts = url.split('?');
  3421. if (turn_url_parts.length === 1 ||
  3422. turn_url_parts[1].indexOf('transport=udp') === 0) {
  3423. iceServer = {
  3424. url : turn_url_parts[0],
  3425. credential : password,
  3426. username : username
  3427. };
  3428. }
  3429. } else {
  3430. iceServer = {
  3431. url : url,
  3432. credential : password,
  3433. username : username
  3434. };
  3435. }
  3436. }
  3437. return iceServer;
  3438. };
  3439. createIceServers = function (urls, username, password) {
  3440. var iceServers = [];
  3441. for (i = 0; i < urls.length; i++) {
  3442. var iceServer = createIceServer(urls[i], username, password);
  3443. if (iceServer !== null) {
  3444. iceServers.push(iceServer);
  3445. }
  3446. }
  3447. return iceServers;
  3448. };
  3449. attachMediaStream = function (element, stream) {
  3450. element.mozSrcObject = stream;
  3451. if (stream !== null)
  3452. element.play();
  3453. return element;
  3454. };
  3455. reattachMediaStream = function (to, from) {
  3456. to.mozSrcObject = from.mozSrcObject;
  3457. to.play();
  3458. return to;
  3459. };
  3460. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  3461. if (!callback) {
  3462. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  3463. ': 1 argument required, but only 0 present.');
  3464. }
  3465. return callback([]);
  3466. };
  3467. // Fake get{Video,Audio}Tracks
  3468. if (!MediaStream.prototype.getVideoTracks) {
  3469. MediaStream.prototype.getVideoTracks = function () {
  3470. return [];
  3471. };
  3472. }
  3473. if (!MediaStream.prototype.getAudioTracks) {
  3474. MediaStream.prototype.getAudioTracks = function () {
  3475. return [];
  3476. };
  3477. }
  3478. AdapterJS.maybeThroughWebRTCReady();
  3479. } else if (navigator.webkitGetUserMedia) {
  3480. webrtcDetectedBrowser = 'chrome';
  3481. webrtcDetectedType = 'webkit';
  3482. webrtcDetectedVersion = parseInt(navigator
  3483. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  3484. // check if browser is opera 20+
  3485. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3486. if (checkIfOpera !== null) {
  3487. webrtcDetectedBrowser = 'opera';
  3488. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  3489. }
  3490. // check browser datachannel support
  3491. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  3492. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  3493. webrtcDetectedDCSupport = 'SCTP';
  3494. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  3495. webrtcDetectedVersion > 24) {
  3496. webrtcDetectedDCSupport = 'RTP';
  3497. } else {
  3498. webrtcDetectedDCSupport = '';
  3499. }
  3500. createIceServer = function (url, username, password) {
  3501. var iceServer = null;
  3502. var url_parts = url.split(':');
  3503. if (url_parts[0].indexOf('stun') === 0) {
  3504. iceServer = { 'url' : url };
  3505. } else if (url_parts[0].indexOf('turn') === 0) {
  3506. iceServer = {
  3507. 'url' : url,
  3508. 'credential' : password,
  3509. 'username' : username
  3510. };
  3511. }
  3512. return iceServer;
  3513. };
  3514. createIceServers = function (urls, username, password) {
  3515. var iceServers = [];
  3516. if (webrtcDetectedVersion >= 34) {
  3517. iceServers = {
  3518. 'urls' : urls,
  3519. 'credential' : password,
  3520. 'username' : username
  3521. };
  3522. } else {
  3523. for (i = 0; i < urls.length; i++) {
  3524. var iceServer = createIceServer(urls[i], username, password);
  3525. if (iceServer !== null) {
  3526. iceServers.push(iceServer);
  3527. }
  3528. }
  3529. }
  3530. return iceServers;
  3531. };
  3532. RTCPeerConnection = function (pcConfig, pcConstraints) {
  3533. if (webrtcDetectedVersion < 34) {
  3534. AdapterJS.maybeFixConfiguration(pcConfig);
  3535. }
  3536. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  3537. };
  3538. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  3539. navigator.getUserMedia = window.getUserMedia;
  3540. attachMediaStream = function (element, stream) {
  3541. if (typeof element.srcObject !== 'undefined') {
  3542. element.srcObject = stream;
  3543. } else if (typeof element.mozSrcObject !== 'undefined') {
  3544. element.mozSrcObject = stream;
  3545. } else if (typeof element.src !== 'undefined') {
  3546. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  3547. } else {
  3548. console.log('Error attaching stream to element.');
  3549. }
  3550. return element;
  3551. };
  3552. reattachMediaStream = function (to, from) {
  3553. to.src = from.src;
  3554. return to;
  3555. };
  3556. AdapterJS.maybeThroughWebRTCReady();
  3557. } else if (navigator.mediaDevices && navigator.userAgent.match(
  3558. /Edge\/(\d+).(\d+)$/)) {
  3559. webrtcDetectedBrowser = 'edge';
  3560. webrtcDetectedVersion =
  3561. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  3562. // the minimum version still supported by adapter.
  3563. webrtcMinimumVersion = 12;
  3564. window.getUserMedia = navigator.getUserMedia.bind(navigator);
  3565. attachMediaStream = function(element, stream) {
  3566. element.srcObject = stream;
  3567. return element;
  3568. };
  3569. reattachMediaStream = function(to, from) {
  3570. to.srcObject = from.srcObject;
  3571. return to;
  3572. };
  3573. AdapterJS.maybeThroughWebRTCReady();
  3574. } else { // TRY TO USE PLUGIN
  3575. // IE 9 is not offering an implementation of console.log until you open a console
  3576. if (typeof console !== 'object' || typeof console.log !== 'function') {
  3577. /* jshint -W020 */
  3578. console = {} || console;
  3579. // Implemented based on console specs from MDN
  3580. // You may override these functions
  3581. console.log = function (arg) {};
  3582. console.info = function (arg) {};
  3583. console.error = function (arg) {};
  3584. console.dir = function (arg) {};
  3585. console.exception = function (arg) {};
  3586. console.trace = function (arg) {};
  3587. console.warn = function (arg) {};
  3588. console.count = function (arg) {};
  3589. console.debug = function (arg) {};
  3590. console.count = function (arg) {};
  3591. console.time = function (arg) {};
  3592. console.timeEnd = function (arg) {};
  3593. console.group = function (arg) {};
  3594. console.groupCollapsed = function (arg) {};
  3595. console.groupEnd = function (arg) {};
  3596. /* jshint +W020 */
  3597. }
  3598. webrtcDetectedType = 'plugin';
  3599. webrtcDetectedDCSupport = 'plugin';
  3600. AdapterJS.parseWebrtcDetectedBrowser();
  3601. isIE = webrtcDetectedBrowser === 'IE';
  3602. /* jshint -W035 */
  3603. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  3604. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3605. /* empty because it needs to prevent the function from running. */
  3606. }
  3607. };
  3608. /* jshint +W035 */
  3609. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  3610. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3611. // Call immediately if possible
  3612. // Once the plugin is set, the code will always take this path
  3613. callback();
  3614. } else {
  3615. // otherwise start a 100ms interval
  3616. var checkPluginReadyState = setInterval(function () {
  3617. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3618. clearInterval(checkPluginReadyState);
  3619. callback();
  3620. }
  3621. }, 100);
  3622. }
  3623. };
  3624. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  3625. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3626. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  3627. });
  3628. };
  3629. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  3630. // only inject once the page is ready
  3631. if (document.readyState !== 'complete') {
  3632. return;
  3633. }
  3634. // Prevent multiple injections
  3635. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  3636. return;
  3637. }
  3638. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  3639. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  3640. var frag = document.createDocumentFragment();
  3641. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  3642. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  3643. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  3644. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  3645. '<param name="pluginId" value="' +
  3646. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  3647. '<param name="windowless" value="false" /> ' +
  3648. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  3649. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  3650. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  3651. // uncomment to be able to use virtual cams
  3652. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  3653. '</object>';
  3654. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  3655. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  3656. }
  3657. document.body.appendChild(frag);
  3658. // Need to re-fetch the plugin
  3659. AdapterJS.WebRTCPlugin.plugin =
  3660. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  3661. } else {
  3662. // Load Plugin
  3663. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  3664. AdapterJS.WebRTCPlugin.plugin.id =
  3665. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  3666. // IE will only start the plugin if it's ACTUALLY visible
  3667. if (isIE) {
  3668. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  3669. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  3670. } else { // The size of the plugin on Safari should be 0x0px
  3671. // so that the autorisation prompt is at the top
  3672. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  3673. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  3674. }
  3675. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  3676. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  3677. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  3678. '<param name="pluginId" value="' +
  3679. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  3680. '<param name="windowless" value="false" /> ' +
  3681. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  3682. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  3683. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  3684. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  3685. }
  3686. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  3687. };
  3688. AdapterJS.WebRTCPlugin.isPluginInstalled =
  3689. function (comName, plugName, installedCb, notInstalledCb) {
  3690. if (!isIE) {
  3691. var pluginArray = navigator.plugins;
  3692. for (var i = 0; i < pluginArray.length; i++) {
  3693. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  3694. installedCb();
  3695. return;
  3696. }
  3697. }
  3698. notInstalledCb();
  3699. } else {
  3700. try {
  3701. var axo = new ActiveXObject(comName + '.' + plugName);
  3702. } catch (e) {
  3703. notInstalledCb();
  3704. return;
  3705. }
  3706. installedCb();
  3707. }
  3708. };
  3709. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  3710. if (AdapterJS.WebRTCPlugin.pluginState ===
  3711. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3712. console.error("AdapterJS - WebRTC interface has already been defined");
  3713. return;
  3714. }
  3715. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  3716. AdapterJS.isDefined = function (variable) {
  3717. return variable !== null && variable !== undefined;
  3718. };
  3719. createIceServer = function (url, username, password) {
  3720. var iceServer = null;
  3721. var url_parts = url.split(':');
  3722. if (url_parts[0].indexOf('stun') === 0) {
  3723. iceServer = {
  3724. 'url' : url,
  3725. 'hasCredentials' : false
  3726. };
  3727. } else if (url_parts[0].indexOf('turn') === 0) {
  3728. iceServer = {
  3729. 'url' : url,
  3730. 'hasCredentials' : true,
  3731. 'credential' : password,
  3732. 'username' : username
  3733. };
  3734. }
  3735. return iceServer;
  3736. };
  3737. createIceServers = function (urls, username, password) {
  3738. var iceServers = [];
  3739. for (var i = 0; i < urls.length; ++i) {
  3740. iceServers.push(createIceServer(urls[i], username, password));
  3741. }
  3742. return iceServers;
  3743. };
  3744. RTCSessionDescription = function (info) {
  3745. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3746. return AdapterJS.WebRTCPlugin.plugin.
  3747. ConstructSessionDescription(info.type, info.sdp);
  3748. };
  3749. RTCPeerConnection = function (servers, constraints) {
  3750. var iceServers = null;
  3751. if (servers) {
  3752. iceServers = servers.iceServers;
  3753. for (var i = 0; i < iceServers.length; i++) {
  3754. if (iceServers[i].urls && !iceServers[i].url) {
  3755. iceServers[i].url = iceServers[i].urls;
  3756. }
  3757. iceServers[i].hasCredentials = AdapterJS.
  3758. isDefined(iceServers[i].username) &&
  3759. AdapterJS.isDefined(iceServers[i].credential);
  3760. }
  3761. }
  3762. var mandatory = (constraints && constraints.mandatory) ?
  3763. constraints.mandatory : null;
  3764. var optional = (constraints && constraints.optional) ?
  3765. constraints.optional : null;
  3766. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3767. return AdapterJS.WebRTCPlugin.plugin.
  3768. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  3769. iceServers, mandatory, optional);
  3770. };
  3771. MediaStreamTrack = {};
  3772. MediaStreamTrack.getSources = function (callback) {
  3773. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3774. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  3775. });
  3776. };
  3777. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  3778. constraints.audio = constraints.audio || false;
  3779. constraints.video = constraints.video || false;
  3780. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3781. AdapterJS.WebRTCPlugin.plugin.
  3782. getUserMedia(constraints, successCallback, failureCallback);
  3783. });
  3784. };
  3785. window.navigator.getUserMedia = window.getUserMedia;
  3786. attachMediaStream = function (element, stream) {
  3787. if (!element || !element.parentNode) {
  3788. return;
  3789. }
  3790. var streamId
  3791. if (stream === null) {
  3792. streamId = '';
  3793. }
  3794. else {
  3795. stream.enableSoundTracks(true); // TODO: remove on 0.12.0
  3796. streamId = stream.id;
  3797. }
  3798. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  3799. var nodeName = element.nodeName.toLowerCase();
  3800. if (nodeName !== 'object') { // not a plugin <object> tag yet
  3801. var tag;
  3802. switch(nodeName) {
  3803. case 'audio':
  3804. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  3805. break;
  3806. case 'video':
  3807. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  3808. break;
  3809. default:
  3810. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  3811. }
  3812. var frag = document.createDocumentFragment();
  3813. var temp = document.createElement('div');
  3814. var classHTML = '';
  3815. if (element.className) {
  3816. classHTML = 'class="' + element.className + '" ';
  3817. } else if (element.attributes && element.attributes['class']) {
  3818. classHTML = 'class="' + element.attributes['class'].value + '" ';
  3819. }
  3820. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  3821. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  3822. '<param name="pluginId" value="' + elementId + '" /> ' +
  3823. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  3824. '<param name="windowless" value="true" /> ' +
  3825. '<param name="streamId" value="' + streamId + '" /> ' +
  3826. '<param name="tag" value="' + tag + '" /> ' +
  3827. '</object>';
  3828. while (temp.firstChild) {
  3829. frag.appendChild(temp.firstChild);
  3830. }
  3831. var height = '';
  3832. var width = '';
  3833. if (element.getBoundingClientRect) {
  3834. var rectObject = element.getBoundingClientRect();
  3835. width = rectObject.width + 'px';
  3836. height = rectObject.height + 'px';
  3837. }
  3838. else if (element.width) {
  3839. width = element.width;
  3840. height = element.height;
  3841. } else {
  3842. // TODO: What scenario could bring us here?
  3843. }
  3844. element.parentNode.insertBefore(frag, element);
  3845. frag = document.getElementById(elementId);
  3846. frag.width = width;
  3847. frag.height = height;
  3848. element.parentNode.removeChild(element);
  3849. } else { // already an <object> tag, just change the stream id
  3850. var children = element.children;
  3851. for (var i = 0; i !== children.length; ++i) {
  3852. if (children[i].name === 'streamId') {
  3853. children[i].value = streamId;
  3854. break;
  3855. }
  3856. }
  3857. element.setStreamId(streamId);
  3858. }
  3859. var newElement = document.getElementById(elementId);
  3860. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  3861. newElement.onplay = (element.onplay) ? element.onplay : function (arg) {};
  3862. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  3863. if (isIE) { // on IE the event needs to be plugged manually
  3864. newElement.attachEvent('onplaying', newElement.onplaying);
  3865. newElement.attachEvent('onplay', newElement.onplay);
  3866. newElement._TemOnClick = function (id) {
  3867. var arg = {
  3868. srcElement : document.getElementById(id)
  3869. };
  3870. newElement.onclick(arg);
  3871. };
  3872. }
  3873. return newElement;
  3874. };
  3875. reattachMediaStream = function (to, from) {
  3876. var stream = null;
  3877. var children = from.children;
  3878. for (var i = 0; i !== children.length; ++i) {
  3879. if (children[i].name === 'streamId') {
  3880. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3881. stream = AdapterJS.WebRTCPlugin.plugin
  3882. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  3883. break;
  3884. }
  3885. }
  3886. if (stream !== null) {
  3887. return attachMediaStream(to, stream);
  3888. } else {
  3889. console.log('Could not find the stream associated with this element');
  3890. }
  3891. };
  3892. RTCIceCandidate = function (candidate) {
  3893. if (!candidate.sdpMid) {
  3894. candidate.sdpMid = '';
  3895. }
  3896. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3897. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  3898. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  3899. );
  3900. };
  3901. // inject plugin
  3902. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  3903. AdapterJS.WebRTCPlugin.injectPlugin();
  3904. };
  3905. // This function will be called if the plugin is needed (browser different
  3906. // from Chrome or Firefox), but the plugin is not installed.
  3907. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  3908. function() {
  3909. AdapterJS.addEvent(document,
  3910. 'readystatechange',
  3911. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  3912. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  3913. };
  3914. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  3915. if (AdapterJS.options.hidePluginInstallPrompt) {
  3916. return;
  3917. }
  3918. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  3919. if(downloadLink) { // if download link
  3920. var popupString;
  3921. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  3922. popupString = 'This website requires you to install the ' +
  3923. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  3924. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  3925. ' WebRTC Plugin</a>' +
  3926. ' to work on this browser.';
  3927. } else { // no portal link, just print a generic explanation
  3928. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  3929. }
  3930. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  3931. } else { // no download link, just print a generic explanation
  3932. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  3933. }
  3934. };
  3935. // Try to detect the plugin and act accordingly
  3936. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3937. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3938. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3939. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  3940. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  3941. }
  3942. }).call(this,"/modules/RTC/adapter.screenshare.js")
  3943. },{"jitsi-meet-logger":47}],21:[function(require,module,exports){
  3944. (function (__filename){
  3945. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3946. function supportsLocalStorage() {
  3947. try {
  3948. return 'localStorage' in window && window.localStorage !== null;
  3949. } catch (e) {
  3950. logger.log("localstorage is not supported");
  3951. return false;
  3952. }
  3953. }
  3954. function generateUniqueId() {
  3955. function _p8() {
  3956. return (Math.random().toString(16) + "000000000").substr(2, 8);
  3957. }
  3958. return _p8() + _p8() + _p8() + _p8();
  3959. }
  3960. function Settings(conferenceID) {
  3961. this.email = '';
  3962. this.displayName = '';
  3963. this.userId;
  3964. this.language = null;
  3965. this.confSettings = null;
  3966. this.conferenceID = conferenceID;
  3967. if (supportsLocalStorage()) {
  3968. if(!window.localStorage.getItem(conferenceID))
  3969. this.confSettings = {};
  3970. else
  3971. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  3972. if(!this.confSettings.jitsiMeetId) {
  3973. this.confSettings.jitsiMeetId = generateUniqueId();
  3974. logger.log("generated id",
  3975. this.confSettings.jitsiMeetId);
  3976. this.save();
  3977. }
  3978. this.userId = this.confSettings.jitsiMeetId || '';
  3979. this.email = this.confSettings.email || '';
  3980. this.displayName = this.confSettings.displayname || '';
  3981. this.language = this.confSettings.language;
  3982. } else {
  3983. logger.log("local storage is not supported");
  3984. this.userId = generateUniqueId();
  3985. }
  3986. }
  3987. Settings.prototype.save = function () {
  3988. if(!supportsLocalStorage())
  3989. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  3990. }
  3991. Settings.prototype.setDisplayName = function (newDisplayName) {
  3992. this.displayName = newDisplayName;
  3993. if(this.confSettings != null)
  3994. this.confSettings.displayname = displayName;
  3995. this.save();
  3996. return this.displayName;
  3997. },
  3998. Settings.prototype.setEmail = function (newEmail) {
  3999. this.email = newEmail;
  4000. if(this.confSettings != null)
  4001. this.confSettings.email = newEmail;
  4002. this.save();
  4003. return this.email;
  4004. },
  4005. Settings.prototype.getSettings = function () {
  4006. return {
  4007. email: this.email,
  4008. displayName: this.displayName,
  4009. uid: this.userId,
  4010. language: this.language
  4011. };
  4012. },
  4013. Settings.prototype.setLanguage = function (lang) {
  4014. this.language = lang;
  4015. if(this.confSettings != null)
  4016. this.confSettings.language = lang;
  4017. this.save();
  4018. }
  4019. module.exports = Settings;
  4020. }).call(this,"/modules/settings/Settings.js")
  4021. },{"jitsi-meet-logger":47}],22:[function(require,module,exports){
  4022. /* global config */
  4023. /**
  4024. * Provides statistics for the local stream.
  4025. */
  4026. var RTCBrowserType = require('../RTC/RTCBrowserType');
  4027. var StatisticsEvents = require('../../service/statistics/Events');
  4028. var LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  4029. /**
  4030. * Size of the webaudio analyzer buffer.
  4031. * @type {number}
  4032. */
  4033. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  4034. /**
  4035. * Value of the webaudio analyzer smoothing time parameter.
  4036. * @type {number}
  4037. */
  4038. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  4039. /**
  4040. * Converts time domain data array to audio level.
  4041. * @param samples the time domain data array.
  4042. * @returns {number} the audio level
  4043. */
  4044. function timeDomainDataToAudioLevel(samples) {
  4045. var maxVolume = 0;
  4046. var length = samples.length;
  4047. for (var i = 0; i < length; i++) {
  4048. if (maxVolume < samples[i])
  4049. maxVolume = samples[i];
  4050. }
  4051. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  4052. }
  4053. /**
  4054. * Animates audio level change
  4055. * @param newLevel the new audio level
  4056. * @param lastLevel the last audio level
  4057. * @returns {Number} the audio level to be set
  4058. */
  4059. function animateLevel(newLevel, lastLevel) {
  4060. var value = 0;
  4061. var diff = lastLevel - newLevel;
  4062. if(diff > 0.2) {
  4063. value = lastLevel - 0.2;
  4064. }
  4065. else if(diff < -0.4) {
  4066. value = lastLevel + 0.4;
  4067. }
  4068. else {
  4069. value = newLevel;
  4070. }
  4071. return parseFloat(value.toFixed(3));
  4072. }
  4073. /**
  4074. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  4075. *
  4076. * @param stream the local stream
  4077. * @param interval stats refresh interval given in ms.
  4078. * @constructor
  4079. */
  4080. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  4081. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  4082. this.stream = stream;
  4083. this.intervalId = null;
  4084. this.intervalMilis = interval;
  4085. this.eventEmitter = eventEmitter;
  4086. this.audioLevel = 0;
  4087. this.statisticsService = statisticsService;
  4088. }
  4089. /**
  4090. * Starts the collecting the statistics.
  4091. */
  4092. LocalStatsCollector.prototype.start = function () {
  4093. if (!window.AudioContext ||
  4094. RTCBrowserType.isTemasysPluginUsed())
  4095. return;
  4096. var context = new AudioContext();
  4097. var analyser = context.createAnalyser();
  4098. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  4099. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  4100. var source = context.createMediaStreamSource(this.stream);
  4101. source.connect(analyser);
  4102. var self = this;
  4103. this.intervalId = setInterval(
  4104. function () {
  4105. var array = new Uint8Array(analyser.frequencyBinCount);
  4106. analyser.getByteTimeDomainData(array);
  4107. var audioLevel = timeDomainDataToAudioLevel(array);
  4108. if (audioLevel != self.audioLevel) {
  4109. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  4110. self.eventEmitter.emit(
  4111. StatisticsEvents.AUDIO_LEVEL,
  4112. self.statisticsService.LOCAL_JID,
  4113. self.audioLevel);
  4114. }
  4115. },
  4116. this.intervalMilis
  4117. );
  4118. };
  4119. /**
  4120. * Stops collecting the statistics.
  4121. */
  4122. LocalStatsCollector.prototype.stop = function () {
  4123. if (this.intervalId) {
  4124. clearInterval(this.intervalId);
  4125. this.intervalId = null;
  4126. }
  4127. };
  4128. module.exports = LocalStatsCollector;
  4129. },{"../../service/statistics/Events":84,"../../service/statistics/constants":85,"../RTC/RTCBrowserType":17}],23:[function(require,module,exports){
  4130. (function (__filename){
  4131. /* global require, ssrc2jid */
  4132. /* jshint -W117 */
  4133. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4134. var RTCBrowserType = require("../RTC/RTCBrowserType");
  4135. var StatisticsEvents = require("../../service/statistics/Events");
  4136. /* Whether we support the browser we are running into for logging statistics */
  4137. var browserSupported = RTCBrowserType.isChrome() ||
  4138. RTCBrowserType.isOpera();
  4139. var keyMap = {};
  4140. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  4141. "ssrc": "ssrc",
  4142. "packetsReceived": "packetsReceived",
  4143. "packetsLost": "packetsLost",
  4144. "packetsSent": "packetsSent",
  4145. "bytesReceived": "bytesReceived",
  4146. "bytesSent": "bytesSent"
  4147. };
  4148. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  4149. "receiveBandwidth": "googAvailableReceiveBandwidth",
  4150. "sendBandwidth": "googAvailableSendBandwidth",
  4151. "remoteAddress": "googRemoteAddress",
  4152. "transportType": "googTransportType",
  4153. "localAddress": "googLocalAddress",
  4154. "activeConnection": "googActiveConnection",
  4155. "ssrc": "ssrc",
  4156. "packetsReceived": "packetsReceived",
  4157. "packetsSent": "packetsSent",
  4158. "packetsLost": "packetsLost",
  4159. "bytesReceived": "bytesReceived",
  4160. "bytesSent": "bytesSent",
  4161. "googFrameHeightReceived": "googFrameHeightReceived",
  4162. "googFrameWidthReceived": "googFrameWidthReceived",
  4163. "googFrameHeightSent": "googFrameHeightSent",
  4164. "googFrameWidthSent": "googFrameWidthSent",
  4165. "audioInputLevel": "audioInputLevel",
  4166. "audioOutputLevel": "audioOutputLevel"
  4167. };
  4168. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  4169. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  4170. /**
  4171. * Calculates packet lost percent using the number of lost packets and the
  4172. * number of all packet.
  4173. * @param lostPackets the number of lost packets
  4174. * @param totalPackets the number of all packets.
  4175. * @returns {number} packet loss percent
  4176. */
  4177. function calculatePacketLoss(lostPackets, totalPackets) {
  4178. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  4179. return 0;
  4180. return Math.round((lostPackets/totalPackets)*100);
  4181. }
  4182. function getStatValue(item, name) {
  4183. var browserType = RTCBrowserType.getBrowserType();
  4184. if (!keyMap[browserType][name])
  4185. throw "The property isn't supported!";
  4186. var key = keyMap[browserType][name];
  4187. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  4188. item.stat(key) : item[key];
  4189. }
  4190. function formatAudioLevel(audioLevel) {
  4191. return Math.min(Math.max(audioLevel, 0), 1);
  4192. }
  4193. /**
  4194. * Checks whether a certain record should be included in the logged statistics.
  4195. */
  4196. function acceptStat(reportId, reportType, statName) {
  4197. if (reportType == "googCandidatePair" && statName == "googChannelId")
  4198. return false;
  4199. if (reportType == "ssrc") {
  4200. if (statName == "googTrackId" ||
  4201. statName == "transportId" ||
  4202. statName == "ssrc")
  4203. return false;
  4204. }
  4205. return true;
  4206. }
  4207. /**
  4208. * Checks whether a certain record should be included in the logged statistics.
  4209. */
  4210. function acceptReport(id, type) {
  4211. if (id.substring(0, 15) == "googCertificate" ||
  4212. id.substring(0, 9) == "googTrack" ||
  4213. id.substring(0, 20) == "googLibjingleSession")
  4214. return false;
  4215. if (type == "googComponent")
  4216. return false;
  4217. return true;
  4218. }
  4219. /**
  4220. * Peer statistics data holder.
  4221. * @constructor
  4222. */
  4223. function PeerStats()
  4224. {
  4225. this.ssrc2Loss = {};
  4226. this.ssrc2AudioLevel = {};
  4227. this.ssrc2bitrate = {};
  4228. this.ssrc2resolution = {};
  4229. }
  4230. /**
  4231. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  4232. * represented by this instance.
  4233. * @param lossRate new packet loss rate value to be set.
  4234. */
  4235. PeerStats.prototype.setSsrcLoss = function (lossRate)
  4236. {
  4237. this.ssrc2Loss = lossRate;
  4238. };
  4239. /**
  4240. * Sets resolution that belong to the ssrc
  4241. * represented by this instance.
  4242. * @param resolution new resolution value to be set.
  4243. */
  4244. PeerStats.prototype.setSsrcResolution = function (resolution)
  4245. {
  4246. if(resolution === null && this.ssrc2resolution[ssrc])
  4247. {
  4248. delete this.ssrc2resolution[ssrc];
  4249. }
  4250. else if(resolution !== null)
  4251. this.ssrc2resolution[ssrc] = resolution;
  4252. };
  4253. /**
  4254. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  4255. * represented by this instance.
  4256. * @param ssrc audio or video RTP stream SSRC.
  4257. * @param bitrate new bitrate value to be set.
  4258. */
  4259. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  4260. {
  4261. if(this.ssrc2bitrate[ssrc])
  4262. {
  4263. this.ssrc2bitrate[ssrc].download += bitrate.download;
  4264. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  4265. }
  4266. else {
  4267. this.ssrc2bitrate[ssrc] = bitrate;
  4268. }
  4269. };
  4270. /**
  4271. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  4272. * the stream which belongs to the peer represented by this instance.
  4273. * @param ssrc RTP stream SSRC for which current audio level value will be
  4274. * updated.
  4275. * @param audioLevel the new audio level value to be set. Value is truncated to
  4276. * fit the range from 0 to 1.
  4277. */
  4278. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  4279. {
  4280. // Range limit 0 - 1
  4281. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  4282. };
  4283. function ConferenceStats() {
  4284. /**
  4285. * The bandwidth
  4286. * @type {{}}
  4287. */
  4288. this.bandwidth = {};
  4289. /**
  4290. * The bit rate
  4291. * @type {{}}
  4292. */
  4293. this.bitrate = {};
  4294. /**
  4295. * The packet loss rate
  4296. * @type {{}}
  4297. */
  4298. this.packetLoss = null;
  4299. /**
  4300. * Array with the transport information.
  4301. * @type {Array}
  4302. */
  4303. this.transport = [];
  4304. }
  4305. /**
  4306. * <tt>StatsCollector</tt> registers for stats updates of given
  4307. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  4308. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  4309. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  4310. * instance as an event source.
  4311. *
  4312. * @param peerconnection webRTC peer connection object.
  4313. * @param interval stats refresh interval given in ms.
  4314. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  4315. * called on stats update.
  4316. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  4317. * @constructor
  4318. */
  4319. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  4320. {
  4321. this.peerconnection = peerconnection;
  4322. this.baselineAudioLevelsReport = null;
  4323. this.currentAudioLevelsReport = null;
  4324. this.currentStatsReport = null;
  4325. this.baselineStatsReport = null;
  4326. this.audioLevelsIntervalId = null;
  4327. this.eventEmitter = eventEmitter;
  4328. this.config = config || {};
  4329. this.conferenceStats = new ConferenceStats();
  4330. /**
  4331. * Gather PeerConnection stats once every this many milliseconds.
  4332. */
  4333. this.GATHER_INTERVAL = 15000;
  4334. /**
  4335. * Log stats via the focus once every this many milliseconds.
  4336. */
  4337. this.LOG_INTERVAL = 60000;
  4338. /**
  4339. * Gather stats and store them in this.statsToBeLogged.
  4340. */
  4341. this.gatherStatsIntervalId = null;
  4342. /**
  4343. * Send the stats already saved in this.statsToBeLogged to be logged via
  4344. * the focus.
  4345. */
  4346. this.logStatsIntervalId = null;
  4347. /**
  4348. * Stores the statistics which will be send to the focus to be logged.
  4349. */
  4350. this.statsToBeLogged =
  4351. {
  4352. timestamps: [],
  4353. stats: {}
  4354. };
  4355. // Updates stats interval
  4356. this.audioLevelsIntervalMilis = audioLevelsInterval;
  4357. this.statsIntervalId = null;
  4358. this.statsIntervalMilis = statsInterval;
  4359. // Map of ssrcs to PeerStats
  4360. this.ssrc2stats = {};
  4361. }
  4362. module.exports = StatsCollector;
  4363. /**
  4364. * Stops stats updates.
  4365. */
  4366. StatsCollector.prototype.stop = function () {
  4367. if (this.audioLevelsIntervalId) {
  4368. clearInterval(this.audioLevelsIntervalId);
  4369. this.audioLevelsIntervalId = null;
  4370. }
  4371. if (this.statsIntervalId)
  4372. {
  4373. clearInterval(this.statsIntervalId);
  4374. this.statsIntervalId = null;
  4375. }
  4376. if(this.logStatsIntervalId)
  4377. {
  4378. clearInterval(this.logStatsIntervalId);
  4379. this.logStatsIntervalId = null;
  4380. }
  4381. if(this.gatherStatsIntervalId)
  4382. {
  4383. clearInterval(this.gatherStatsIntervalId);
  4384. this.gatherStatsIntervalId = null;
  4385. }
  4386. };
  4387. /**
  4388. * Callback passed to <tt>getStats</tt> method.
  4389. * @param error an error that occurred on <tt>getStats</tt> call.
  4390. */
  4391. StatsCollector.prototype.errorCallback = function (error)
  4392. {
  4393. logger.error("Get stats error", error);
  4394. this.stop();
  4395. };
  4396. /**
  4397. * Starts stats updates.
  4398. */
  4399. StatsCollector.prototype.start = function ()
  4400. {
  4401. var self = this;
  4402. this.audioLevelsIntervalId = setInterval(
  4403. function () {
  4404. // Interval updates
  4405. self.peerconnection.getStats(
  4406. function (report) {
  4407. var results = null;
  4408. if (!report || !report.result ||
  4409. typeof report.result != 'function') {
  4410. results = report;
  4411. }
  4412. else {
  4413. results = report.result();
  4414. }
  4415. //logger.error("Got interval report", results);
  4416. self.currentAudioLevelsReport = results;
  4417. self.processAudioLevelReport();
  4418. self.baselineAudioLevelsReport =
  4419. self.currentAudioLevelsReport;
  4420. },
  4421. self.errorCallback
  4422. );
  4423. },
  4424. self.audioLevelsIntervalMilis
  4425. );
  4426. // if (!this.config.disableStats && browserSupported) {
  4427. // this.statsIntervalId = setInterval(
  4428. // function () {
  4429. // // Interval updates
  4430. // self.peerconnection.getStats(
  4431. // function (report) {
  4432. // var results = null;
  4433. // if (!report || !report.result ||
  4434. // typeof report.result != 'function') {
  4435. // //firefox
  4436. // results = report;
  4437. // }
  4438. // else {
  4439. // //chrome
  4440. // results = report.result();
  4441. // }
  4442. // //logger.error("Got interval report", results);
  4443. // self.currentStatsReport = results;
  4444. // try {
  4445. // self.processStatsReport();
  4446. // }
  4447. // catch (e) {
  4448. // logger.error("Unsupported key:" + e, e);
  4449. // }
  4450. //
  4451. // self.baselineStatsReport = self.currentStatsReport;
  4452. // },
  4453. // self.errorCallback
  4454. // );
  4455. // },
  4456. // self.statsIntervalMilis
  4457. // );
  4458. // }
  4459. //
  4460. // if (this.config.logStats && browserSupported) {
  4461. // this.gatherStatsIntervalId = setInterval(
  4462. // function () {
  4463. // self.peerconnection.getStats(
  4464. // function (report) {
  4465. // self.addStatsToBeLogged(report.result());
  4466. // },
  4467. // function () {
  4468. // }
  4469. // );
  4470. // },
  4471. // this.GATHER_INTERVAL
  4472. // );
  4473. //
  4474. // this.logStatsIntervalId = setInterval(
  4475. // function() { self.logStats(); },
  4476. // this.LOG_INTERVAL);
  4477. // }
  4478. };
  4479. /**
  4480. * Converts the stats to the format used for logging, and saves the data in
  4481. * this.statsToBeLogged.
  4482. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  4483. */
  4484. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  4485. var self = this;
  4486. var num_records = this.statsToBeLogged.timestamps.length;
  4487. this.statsToBeLogged.timestamps.push(new Date().getTime());
  4488. reports.map(function (report) {
  4489. if (!acceptReport(report.id, report.type))
  4490. return;
  4491. var stat = self.statsToBeLogged.stats[report.id];
  4492. if (!stat) {
  4493. stat = self.statsToBeLogged.stats[report.id] = {};
  4494. }
  4495. stat.type = report.type;
  4496. report.names().map(function (name) {
  4497. if (!acceptStat(report.id, report.type, name))
  4498. return;
  4499. var values = stat[name];
  4500. if (!values) {
  4501. values = stat[name] = [];
  4502. }
  4503. while (values.length < num_records) {
  4504. values.push(null);
  4505. }
  4506. values.push(report.stat(name));
  4507. });
  4508. });
  4509. };
  4510. //FIXME:
  4511. //StatsCollector.prototype.logStats = function () {
  4512. //
  4513. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  4514. // return;
  4515. // // Reset the stats
  4516. // this.statsToBeLogged.stats = {};
  4517. // this.statsToBeLogged.timestamps = [];
  4518. //};
  4519. /**
  4520. * Stats processing logic.
  4521. */
  4522. StatsCollector.prototype.processStatsReport = function () {
  4523. if (!this.baselineStatsReport) {
  4524. return;
  4525. }
  4526. for (var idx in this.currentStatsReport) {
  4527. var now = this.currentStatsReport[idx];
  4528. try {
  4529. if (getStatValue(now, 'receiveBandwidth') ||
  4530. getStatValue(now, 'sendBandwidth')) {
  4531. this.conferenceStats.bandwidth = {
  4532. "download": Math.round(
  4533. (getStatValue(now, 'receiveBandwidth')) / 1000),
  4534. "upload": Math.round(
  4535. (getStatValue(now, 'sendBandwidth')) / 1000)
  4536. };
  4537. }
  4538. }
  4539. catch(e){/*not supported*/}
  4540. if(now.type == 'googCandidatePair')
  4541. {
  4542. var ip, type, localIP, active;
  4543. try {
  4544. ip = getStatValue(now, 'remoteAddress');
  4545. type = getStatValue(now, "transportType");
  4546. localIP = getStatValue(now, "localAddress");
  4547. active = getStatValue(now, "activeConnection");
  4548. }
  4549. catch(e){/*not supported*/}
  4550. if(!ip || !type || !localIP || active != "true")
  4551. continue;
  4552. var addressSaved = false;
  4553. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  4554. {
  4555. if(this.conferenceStats.transport[i].ip == ip &&
  4556. this.conferenceStats.transport[i].type == type &&
  4557. this.conferenceStats.transport[i].localip == localIP)
  4558. {
  4559. addressSaved = true;
  4560. }
  4561. }
  4562. if(addressSaved)
  4563. continue;
  4564. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  4565. continue;
  4566. }
  4567. if(now.type == "candidatepair")
  4568. {
  4569. if(now.state == "succeeded")
  4570. continue;
  4571. var local = this.currentStatsReport[now.localCandidateId];
  4572. var remote = this.currentStatsReport[now.remoteCandidateId];
  4573. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  4574. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  4575. }
  4576. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  4577. now.type != "inboundrtp") {
  4578. continue;
  4579. }
  4580. var before = this.baselineStatsReport[idx];
  4581. if (!before) {
  4582. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  4583. continue;
  4584. }
  4585. var ssrc = getStatValue(now, 'ssrc');
  4586. if(!ssrc)
  4587. continue;
  4588. var ssrcStats = this.ssrc2stats[ssrc];
  4589. if (!ssrcStats) {
  4590. ssrcStats = new PeerStats();
  4591. this.ssrc2stats[ssrc] = ssrcStats;
  4592. }
  4593. var isDownloadStream = true;
  4594. var key = 'packetsReceived';
  4595. var packetsNow = getStatValue(now, key);
  4596. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  4597. isDownloadStream = false;
  4598. key = 'packetsSent';
  4599. packetsNow = getStatValue(now, key);
  4600. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  4601. console.warn("No packetsReceived nor packetsSent stat found");
  4602. continue;
  4603. }
  4604. }
  4605. if (!packetsNow || packetsNow < 0)
  4606. packetsNow = 0;
  4607. var packetsBefore = getStatValue(before, key);
  4608. if (!packetsBefore || packetsBefore < 0)
  4609. packetsBefore = 0;
  4610. var packetRate = packetsNow - packetsBefore;
  4611. if (!packetRate || packetRate < 0)
  4612. packetRate = 0;
  4613. var currentLoss = getStatValue(now, 'packetsLost');
  4614. if (!currentLoss || currentLoss < 0)
  4615. currentLoss = 0;
  4616. var previousLoss = getStatValue(before, 'packetsLost');
  4617. if (!previousLoss || previousLoss < 0)
  4618. previousLoss = 0;
  4619. var lossRate = currentLoss - previousLoss;
  4620. if (!lossRate || lossRate < 0)
  4621. lossRate = 0;
  4622. var packetsTotal = (packetRate + lossRate);
  4623. ssrcStats.setSsrcLoss(ssrc,
  4624. {"packetsTotal": packetsTotal,
  4625. "packetsLost": lossRate,
  4626. "isDownloadStream": isDownloadStream});
  4627. var bytesReceived = 0, bytesSent = 0;
  4628. if(getStatValue(now, "bytesReceived")) {
  4629. bytesReceived = getStatValue(now, "bytesReceived") -
  4630. getStatValue(before, "bytesReceived");
  4631. }
  4632. if (getStatValue(now, "bytesSent")) {
  4633. bytesSent = getStatValue(now, "bytesSent") -
  4634. getStatValue(before, "bytesSent");
  4635. }
  4636. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  4637. if (bytesReceived <= 0 || time <= 0) {
  4638. bytesReceived = 0;
  4639. } else {
  4640. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  4641. }
  4642. if (bytesSent <= 0 || time <= 0) {
  4643. bytesSent = 0;
  4644. } else {
  4645. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  4646. }
  4647. ssrcStats.setSsrcBitrate(ssrc, {
  4648. "download": bytesReceived,
  4649. "upload": bytesSent});
  4650. var resolution = {height: null, width: null};
  4651. try {
  4652. if (getStatValue(now, "googFrameHeightReceived") &&
  4653. getStatValue(now, "googFrameWidthReceived")) {
  4654. resolution.height =
  4655. getStatValue(now, "googFrameHeightReceived");
  4656. resolution.width = getStatValue(now, "googFrameWidthReceived");
  4657. }
  4658. else if (getStatValue(now, "googFrameHeightSent") &&
  4659. getStatValue(now, "googFrameWidthSent")) {
  4660. resolution.height = getStatValue(now, "googFrameHeightSent");
  4661. resolution.width = getStatValue(now, "googFrameWidthSent");
  4662. }
  4663. }
  4664. catch(e){/*not supported*/}
  4665. if (resolution.height && resolution.width) {
  4666. ssrcStats.setSsrcResolution(ssrc, resolution);
  4667. } else {
  4668. ssrcStats.setSsrcResolution(ssrc, null);
  4669. }
  4670. }
  4671. var self = this;
  4672. // Jid stats
  4673. var totalPackets = {download: 0, upload: 0};
  4674. var lostPackets = {download: 0, upload: 0};
  4675. var bitrateDownload = 0;
  4676. var bitrateUpload = 0;
  4677. var resolutions = {};
  4678. Object.keys(this.ssrc2stats).forEach(
  4679. function (jid) {
  4680. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  4681. function (ssrc) {
  4682. var type = "upload";
  4683. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  4684. type = "download";
  4685. totalPackets[type] +=
  4686. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  4687. lostPackets[type] +=
  4688. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  4689. }
  4690. );
  4691. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  4692. function (ssrc) {
  4693. bitrateDownload +=
  4694. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  4695. bitrateUpload +=
  4696. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  4697. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  4698. }
  4699. );
  4700. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  4701. }
  4702. );
  4703. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  4704. this.conferenceStats.packetLoss = {
  4705. total:
  4706. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  4707. totalPackets.download + totalPackets.upload),
  4708. download:
  4709. calculatePacketLoss(lostPackets.download, totalPackets.download),
  4710. upload:
  4711. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  4712. };
  4713. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS,
  4714. {
  4715. "bitrate": this.conferenceStats.bitrate,
  4716. "packetLoss": this.conferenceStats.packetLoss,
  4717. "bandwidth": this.conferenceStats.bandwidth,
  4718. "resolution": resolutions,
  4719. "transport": this.conferenceStats.transport
  4720. });
  4721. this.conferenceStats.transport = [];
  4722. };
  4723. /**
  4724. * Stats processing logic.
  4725. */
  4726. StatsCollector.prototype.processAudioLevelReport = function () {
  4727. if (!this.baselineAudioLevelsReport) {
  4728. return;
  4729. }
  4730. for (var idx in this.currentAudioLevelsReport) {
  4731. var now = this.currentAudioLevelsReport[idx];
  4732. //if we don't have "packetsReceived" this is local stream
  4733. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  4734. continue;
  4735. }
  4736. var before = this.baselineAudioLevelsReport[idx];
  4737. if (!before) {
  4738. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  4739. continue;
  4740. }
  4741. var ssrc = getStatValue(now, 'ssrc');
  4742. if (!ssrc) {
  4743. if((Date.now() - now.timestamp) < 3000)
  4744. logger.warn("No ssrc: ");
  4745. continue;
  4746. }
  4747. var ssrcStats = this.ssrc2stats[ssrc];
  4748. if (!ssrcStats) {
  4749. ssrcStats = new PeerStats();
  4750. this.ssrc2stats[ssrc] = ssrcStats;
  4751. }
  4752. // Audio level
  4753. var audioLevel = null;
  4754. try {
  4755. audioLevel = getStatValue(now, 'audioInputLevel');
  4756. if (!audioLevel)
  4757. audioLevel = getStatValue(now, 'audioOutputLevel');
  4758. }
  4759. catch(e) {/*not supported*/
  4760. logger.warn("Audio Levels are not available in the statistics.");
  4761. clearInterval(this.audioLevelsIntervalId);
  4762. return;
  4763. }
  4764. if (audioLevel) {
  4765. // TODO: can't find specs about what this value really is,
  4766. // but it seems to vary between 0 and around 32k.
  4767. audioLevel = audioLevel / 32767;
  4768. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  4769. this.eventEmitter.emit(
  4770. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel);
  4771. }
  4772. }
  4773. };
  4774. }).call(this,"/modules/statistics/RTPStatsCollector.js")
  4775. },{"../../service/statistics/Events":84,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":47}],24:[function(require,module,exports){
  4776. /* global require, APP */
  4777. var LocalStats = require("./LocalStatsCollector.js");
  4778. var RTPStats = require("./RTPStatsCollector.js");
  4779. var EventEmitter = require("events");
  4780. var StatisticsEvents = require("../../service/statistics/Events");
  4781. //var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  4782. //var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  4783. //var CallStats = require("./CallStats");
  4784. //var RTCEvents = require("../../service/RTC/RTCEvents");
  4785. //
  4786. //function onDisposeConference(onUnload) {
  4787. // CallStats.sendTerminateEvent();
  4788. // stopRemote();
  4789. // if(onUnload) {
  4790. // stopLocal();
  4791. // eventEmitter.removeAllListeners();
  4792. // }
  4793. //}
  4794. function Statistics() {
  4795. this.localStats = null;
  4796. this.rtpStats = null;
  4797. this.eventEmitter = new EventEmitter();
  4798. }
  4799. Statistics.prototype.startRemoteStats = function (peerconnection) {
  4800. if (this.rtpStats) {
  4801. this.rtpStats.stop();
  4802. }
  4803. this.rtpStats = new RTPStats(peerconnection, 200, 2000, this.eventEmitter);
  4804. this.rtpStats.start();
  4805. }
  4806. Statistics.prototype.startLocalStats = function (stream) {
  4807. if(stream.getType() !== "audio")
  4808. return;
  4809. this.localStats = new LocalStats(stream.getOriginalStream(), 200, this,
  4810. this.eventEmitter);
  4811. this.localStats.start();
  4812. }
  4813. Statistics.prototype.addAudioLevelListener = function(listener)
  4814. {
  4815. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  4816. }
  4817. Statistics.prototype.removeAudioLevelListener = function(listener)
  4818. {
  4819. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  4820. }
  4821. Statistics.prototype.dispose = function () {
  4822. this.stopLocal();
  4823. this.stopRemote();
  4824. if(this.eventEmitter)
  4825. {
  4826. this.eventEmitter.removeAllListeners();
  4827. }
  4828. }
  4829. Statistics.prototype.stopLocal = function () {
  4830. if (this.localStats) {
  4831. this.localStats.stop();
  4832. this.localStats = null;
  4833. }
  4834. }
  4835. Statistics.prototype.stopRemote = function () {
  4836. if (this.rtpStats) {
  4837. this.rtpStats.stop();
  4838. this.eventEmitter.emit(StatisticsEvents.STOP);
  4839. this.rtpStats = null;
  4840. }
  4841. }
  4842. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  4843. //
  4844. //var statistics = {
  4845. // /**
  4846. // * Indicates that this audio level is for local jid.
  4847. // * @type {string}
  4848. // */
  4849. // LOCAL_JID: 'local',
  4850. //
  4851. // addConnectionStatsListener: function(listener)
  4852. // {
  4853. // eventEmitter.on("statistics.connectionstats", listener);
  4854. // },
  4855. //
  4856. // removeConnectionStatsListener: function(listener)
  4857. // {
  4858. // eventEmitter.removeListener("statistics.connectionstats", listener);
  4859. // },
  4860. //
  4861. //
  4862. // addRemoteStatsStopListener: function(listener)
  4863. // {
  4864. // eventEmitter.on("statistics.stop", listener);
  4865. // },
  4866. //
  4867. // removeRemoteStatsStopListener: function(listener)
  4868. // {
  4869. // eventEmitter.removeListener("statistics.stop", listener);
  4870. // },
  4871. //
  4872. //
  4873. // stopRemoteStatistics: function()
  4874. // {
  4875. // stopRemote();
  4876. // },
  4877. //
  4878. //// Already implemented with the constructor
  4879. // start: function () {
  4880. // APP.RTC.addStreamListener(onStreamCreated,
  4881. // StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  4882. // APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  4883. // //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  4884. // APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  4885. // startRemoteStats(event.peerconnection);
  4886. //// CallStats.init(event);
  4887. // });
  4888. //// APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  4889. //// CallStats.init(session);
  4890. //// });
  4891. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  4892. //// APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  4893. //// CallStats.sendMuteEvent(mute, "audio");
  4894. //// });
  4895. //// APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  4896. //// CallStats.sendSetupFailedEvent();
  4897. //// });
  4898. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  4899. //// APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  4900. //// CallStats.sendMuteEvent(mute, "video");
  4901. //// });
  4902. // }
  4903. //};
  4904. module.exports = Statistics;
  4905. },{"../../service/statistics/Events":84,"../../service/statistics/constants":85,"./LocalStatsCollector.js":22,"./RTPStatsCollector.js":23,"events":43}],25:[function(require,module,exports){
  4906. /**
  4907. /**
  4908. * @const
  4909. */
  4910. var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  4911. /**
  4912. * Hexadecimal digits.
  4913. * @const
  4914. */
  4915. var HEX_DIGITS = '0123456789abcdef';
  4916. /**
  4917. * Generates random int within the range [min, max]
  4918. * @param min the minimum value for the generated number
  4919. * @param max the maximum value for the generated number
  4920. * @returns random int number
  4921. */
  4922. function randomInt(min, max) {
  4923. return Math.floor(Math.random() * (max - min + 1)) + min;
  4924. }
  4925. /**
  4926. * Get random element from array or string.
  4927. * @param {Array|string} arr source
  4928. * @returns array element or string character
  4929. */
  4930. function randomElement(arr) {
  4931. return arr[randomInt(0, arr.length - 1)];
  4932. }
  4933. /**
  4934. * Generate random alphanumeric string.
  4935. * @param {number} length expected string length
  4936. * @returns {string} random string of specified length
  4937. */
  4938. function randomAlphanumStr(length) {
  4939. var result = '';
  4940. for (var i = 0; i < length; i += 1) {
  4941. result += randomElement(ALPHANUM);
  4942. }
  4943. return result;
  4944. }
  4945. /**
  4946. * Exported interface.
  4947. */
  4948. var RandomUtil = {
  4949. /**
  4950. * Returns a random hex digit.
  4951. * @returns {*}
  4952. */
  4953. randomHexDigit: function() {
  4954. return randomElement(HEX_DIGITS);
  4955. },
  4956. /**
  4957. * Returns a random string of hex digits with length 'len'.
  4958. * @param len the length.
  4959. */
  4960. randomHexString: function (len) {
  4961. var ret = '';
  4962. while (len--) {
  4963. ret += this.randomHexDigit();
  4964. }
  4965. return ret;
  4966. },
  4967. randomElement: randomElement,
  4968. randomAlphanumStr: randomAlphanumStr
  4969. };
  4970. module.exports = RandomUtil;
  4971. },{}],26:[function(require,module,exports){
  4972. (function (__filename){
  4973. /* global Strophe, $, $pres, $iq, $msg */
  4974. /* jshint -W101,-W069 */
  4975. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4976. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  4977. var Moderator = require("./moderator");
  4978. var EventEmitter = require("events");
  4979. var parser = {
  4980. packet2JSON: function (packet, nodes) {
  4981. var self = this;
  4982. $(packet).children().each(function (index) {
  4983. var tagName = $(this).prop("tagName");
  4984. var node = {
  4985. tagName: tagName
  4986. };
  4987. node.attributes = {};
  4988. $($(this)[0].attributes).each(function( index, attr ) {
  4989. node.attributes[ attr.name ] = attr.value;
  4990. });
  4991. var text = Strophe.getText($(this)[0]);
  4992. if (text) {
  4993. node.value = text;
  4994. }
  4995. node.children = [];
  4996. nodes.push(node);
  4997. self.packet2JSON($(this), node.children);
  4998. });
  4999. },
  5000. JSON2packet: function (nodes, packet) {
  5001. for(var i = 0; i < nodes.length; i++) {
  5002. var node = nodes[i];
  5003. if(!node || node === null){
  5004. continue;
  5005. }
  5006. packet.c(node.tagName, node.attributes);
  5007. if(node.value)
  5008. packet.t(node.value);
  5009. if(node.children)
  5010. this.JSON2packet(node.children, packet);
  5011. packet.up();
  5012. }
  5013. // packet.up();
  5014. }
  5015. };
  5016. /**
  5017. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  5018. * @param pres the presence JSON
  5019. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  5020. */
  5021. function filterNodeFromPresenceJSON(pres, nodeName){
  5022. var res = [];
  5023. for(var i = 0; i < pres.length; i++)
  5024. if(pres[i].tagName === nodeName)
  5025. res.push(pres[i]);
  5026. return res;
  5027. }
  5028. function ChatRoom(connection, jid, password, XMPP, options) {
  5029. this.eventEmitter = new EventEmitter();
  5030. this.xmpp = XMPP;
  5031. this.connection = connection;
  5032. this.roomjid = Strophe.getBareJidFromJid(jid);
  5033. this.myroomjid = jid;
  5034. this.password = password;
  5035. logger.info("Joined MUC as " + this.myroomjid);
  5036. this.members = {};
  5037. this.presMap = {};
  5038. this.presHandlers = {};
  5039. this.joined = false;
  5040. this.role = 'none';
  5041. this.focusMucJid = null;
  5042. this.bridgeIsDown = false;
  5043. this.options = options || {};
  5044. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter);
  5045. this.initPresenceMap();
  5046. this.session = null;
  5047. var self = this;
  5048. this.lastPresences = {};
  5049. }
  5050. ChatRoom.prototype.initPresenceMap = function () {
  5051. this.presMap['to'] = this.myroomjid;
  5052. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  5053. this.presMap["nodes"] = [];
  5054. this.presMap["nodes"].push( {
  5055. "tagName": "user-agent",
  5056. "value": navigator.userAgent,
  5057. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  5058. });
  5059. };
  5060. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  5061. this.presMap["nodes"].push( {
  5062. "tagName": "devices",
  5063. "children": [
  5064. {
  5065. "tagName": "audio",
  5066. "value": devices.audio,
  5067. },
  5068. {
  5069. "tagName": "video",
  5070. "value": devices.video,
  5071. }
  5072. ]
  5073. });
  5074. };
  5075. ChatRoom.prototype.join = function (password, tokenPassword) {
  5076. if(password)
  5077. this.password = password;
  5078. var self = this;
  5079. this.moderator.allocateConferenceFocus(function()
  5080. {
  5081. self.sendPresence(tokenPassword);
  5082. }.bind(this));
  5083. };
  5084. ChatRoom.prototype.sendPresence = function (tokenPassword) {
  5085. if (!this.presMap['to']) {
  5086. // Too early to send presence - not initialized
  5087. return;
  5088. }
  5089. var pres = $pres({to: this.presMap['to'] });
  5090. pres.c('x', {xmlns: this.presMap['xns']});
  5091. if (this.password) {
  5092. pres.c('password').t(this.password).up();
  5093. }
  5094. pres.up();
  5095. // Send XEP-0115 'c' stanza that contains our capabilities info
  5096. if (this.connection.caps) {
  5097. this.connection.caps.node = this.xmpp.options.clientNode;
  5098. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  5099. }
  5100. if (tokenPassword) {
  5101. pres.c('token', { xmlns: 'http://jitsi.org/jitmeet/auth-token'})
  5102. .t(tokenPassword).up();
  5103. }
  5104. parser.JSON2packet(this.presMap.nodes, pres);
  5105. this.connection.send(pres);
  5106. };
  5107. ChatRoom.prototype.doLeave = function () {
  5108. logger.log("do leave", this.myroomjid);
  5109. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  5110. this.presMap.length = 0;
  5111. this.connection.send(pres);
  5112. };
  5113. ChatRoom.prototype.createNonAnonymousRoom = function () {
  5114. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  5115. var getForm = $iq({type: 'get', to: this.roomjid})
  5116. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  5117. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5118. var self = this;
  5119. this.connection.sendIQ(getForm, function (form) {
  5120. if (!$(form).find(
  5121. '>query>x[xmlns="jabber:x:data"]' +
  5122. '>field[var="muc#roomconfig_whois"]').length) {
  5123. logger.error('non-anonymous rooms not supported');
  5124. return;
  5125. }
  5126. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  5127. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5128. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5129. formSubmit.c('field', {'var': 'FORM_TYPE'})
  5130. .c('value')
  5131. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5132. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  5133. .c('value').t('anyone').up().up();
  5134. self.connection.sendIQ(formSubmit);
  5135. }, function (error) {
  5136. logger.error("Error getting room configuration form");
  5137. });
  5138. };
  5139. ChatRoom.prototype.onPresence = function (pres) {
  5140. var from = pres.getAttribute('from');
  5141. // Parse roles.
  5142. var member = {};
  5143. member.show = $(pres).find('>show').text();
  5144. member.status = $(pres).find('>status').text();
  5145. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  5146. member.affiliation = tmp.attr('affiliation');
  5147. member.role = tmp.attr('role');
  5148. // Focus recognition
  5149. member.jid = tmp.attr('jid');
  5150. member.isFocus = false;
  5151. if (member.jid
  5152. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") === 0) {
  5153. member.isFocus = true;
  5154. }
  5155. $(pres).find(">x").remove();
  5156. var nodes = [];
  5157. parser.packet2JSON(pres, nodes);
  5158. this.lastPresences[from] = nodes;
  5159. for(var i = 0; i < nodes.length; i++)
  5160. {
  5161. var node = nodes[i];
  5162. switch(node.tagName)
  5163. {
  5164. case "nick":
  5165. member.nick = node.value;
  5166. if(!member.isFocus) {
  5167. var displayName = !this.xmpp.options.displayJids
  5168. ? member.nick : Strophe.getResourceFromJid(from);
  5169. if (displayName && displayName.length > 0) {
  5170. this.eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  5171. }
  5172. logger.info("Display name: " + displayName, pres);
  5173. }
  5174. break;
  5175. case "userId":
  5176. member.id = node.value;
  5177. break;
  5178. case "email":
  5179. member.email = node.value;
  5180. break;
  5181. case "bridgeIsDown":
  5182. if(!this.bridgeIsDown) {
  5183. this.bridgeIsDown = true;
  5184. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  5185. }
  5186. break;
  5187. default :
  5188. this.processNode(node, from);
  5189. }
  5190. }
  5191. if (from == this.myroomjid) {
  5192. if (member.affiliation == 'owner')
  5193. if (this.role !== member.role) {
  5194. this.role = member.role;
  5195. this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED, this.role);
  5196. }
  5197. if (!this.joined) {
  5198. this.joined = true;
  5199. console.log("(TIME) MUC joined:\t", window.performance.now());
  5200. this.eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  5201. }
  5202. } else if (this.members[from] === undefined) {
  5203. // new participant
  5204. this.members[from] = member;
  5205. logger.log('entered', from, member);
  5206. if (member.isFocus) {
  5207. this.focusMucJid = from;
  5208. logger.info("Ignore focus: " + from + ", real JID: " + member.jid);
  5209. }
  5210. else {
  5211. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, member.id || member.email, member.nick);
  5212. }
  5213. } else {
  5214. // Presence update for existing participant
  5215. // Watch role change:
  5216. if (this.members[from].role != member.role) {
  5217. this.members[from].role = member.role;
  5218. this.eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  5219. }
  5220. // store the new display name
  5221. if(member.displayName)
  5222. this.members[from].displayName = member.displayName;
  5223. }
  5224. if(!member.isFocus)
  5225. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id || member.email);
  5226. // Trigger status message update
  5227. if (member.status) {
  5228. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  5229. }
  5230. };
  5231. ChatRoom.prototype.processNode = function (node, from) {
  5232. if(this.presHandlers[node.tagName])
  5233. this.presHandlers[node.tagName](node, from);
  5234. };
  5235. ChatRoom.prototype.sendMessage = function (body, nickname) {
  5236. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5237. msg.c('body', body).up();
  5238. if (nickname) {
  5239. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  5240. }
  5241. this.connection.send(msg);
  5242. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  5243. };
  5244. ChatRoom.prototype.setSubject = function (subject) {
  5245. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5246. msg.c('subject', subject);
  5247. this.connection.send(msg);
  5248. logger.log("topic changed to " + subject);
  5249. };
  5250. ChatRoom.prototype.onParticipantLeft = function (jid) {
  5251. delete this.lastPresences[jid];
  5252. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  5253. this.moderator.onMucMemberLeft(jid);
  5254. };
  5255. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  5256. // room destroyed ?
  5257. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5258. '>destroy').length) {
  5259. var reason;
  5260. var reasonSelect = $(pres).find(
  5261. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5262. '>destroy>reason');
  5263. if (reasonSelect.length) {
  5264. reason = reasonSelect.text();
  5265. }
  5266. this.xmpp.disposeConference(false);
  5267. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  5268. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(from)];
  5269. return true;
  5270. }
  5271. // Status code 110 indicates that this notification is "self-presence".
  5272. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  5273. delete this.members[from];
  5274. this.onParticipantLeft(from);
  5275. }
  5276. // If the status code is 110 this means we're leaving and we would like
  5277. // to remove everyone else from our view, so we trigger the event.
  5278. else if (Object.keys(this.members).length > 1) {
  5279. for (var i in this.members) {
  5280. var member = this.members[i];
  5281. delete this.members[i];
  5282. this.onParticipantLeft(member);
  5283. }
  5284. }
  5285. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  5286. if (this.myroomjid === from) {
  5287. this.xmpp.disposeConference(false);
  5288. this.eventEmitter.emit(XMPPEvents.KICKED);
  5289. }
  5290. }
  5291. };
  5292. ChatRoom.prototype.onMessage = function (msg, from) {
  5293. var nick =
  5294. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  5295. .text() ||
  5296. Strophe.getResourceFromJid(from);
  5297. var txt = $(msg).find('>body').text();
  5298. var type = msg.getAttribute("type");
  5299. if (type == "error") {
  5300. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  5301. $(msg).find('>text').text(), txt);
  5302. return true;
  5303. }
  5304. var subject = $(msg).find('>subject');
  5305. if (subject.length) {
  5306. var subjectText = subject.text();
  5307. if (subjectText || subjectText === "") {
  5308. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  5309. logger.log("Subject is changed to " + subjectText);
  5310. }
  5311. }
  5312. // xep-0203 delay
  5313. var stamp = $(msg).find('>delay').attr('stamp');
  5314. if (!stamp) {
  5315. // or xep-0091 delay, UTC timestamp
  5316. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  5317. if (stamp) {
  5318. // the format is CCYYMMDDThh:mm:ss
  5319. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  5320. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  5321. }
  5322. }
  5323. if (txt) {
  5324. logger.log('chat', nick, txt);
  5325. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  5326. from, nick, txt, this.myroomjid, stamp);
  5327. }
  5328. };
  5329. ChatRoom.prototype.onPresenceError = function (pres, from) {
  5330. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5331. logger.log('on password required', from);
  5332. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  5333. } else if ($(pres).find(
  5334. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5335. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  5336. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  5337. // enter the room by replying with 'not-authorized'. This would
  5338. // result in reconnection from authorized domain.
  5339. // We're either missing Jicofo/Prosody config for anonymous
  5340. // domains or something is wrong.
  5341. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  5342. } else {
  5343. logger.warn('onPresError ', pres);
  5344. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5345. }
  5346. } else {
  5347. logger.warn('onPresError ', pres);
  5348. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5349. }
  5350. };
  5351. ChatRoom.prototype.kick = function (jid) {
  5352. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  5353. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  5354. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  5355. .c('reason').t('You have been kicked.').up().up().up();
  5356. this.connection.sendIQ(
  5357. kickIQ,
  5358. function (result) {
  5359. logger.log('Kick participant with jid: ', jid, result);
  5360. },
  5361. function (error) {
  5362. logger.log('Kick participant error: ', error);
  5363. });
  5364. };
  5365. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  5366. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  5367. var ob = this;
  5368. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  5369. function (res) {
  5370. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  5371. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5372. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5373. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5374. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  5375. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  5376. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  5377. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  5378. ob.connection.sendIQ(formsubmit,
  5379. onSuccess,
  5380. onError);
  5381. } else {
  5382. onNotSupported();
  5383. }
  5384. }, onError);
  5385. };
  5386. ChatRoom.prototype.addToPresence = function (key, values) {
  5387. values.tagName = key;
  5388. this.presMap["nodes"].push(values);
  5389. };
  5390. ChatRoom.prototype.removeFromPresence = function (key) {
  5391. for(var i = 0; i < this.presMap.nodes.length; i++)
  5392. {
  5393. if(key === this.presMap.nodes[i].tagName)
  5394. this.presMap.nodes.splice(i, 1);
  5395. }
  5396. };
  5397. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  5398. this.presHandlers[name] = handler;
  5399. };
  5400. ChatRoom.prototype.removePresenceListener = function (name) {
  5401. delete this.presHandlers[name];
  5402. };
  5403. ChatRoom.prototype.isModerator = function () {
  5404. return this.role === 'moderator';
  5405. };
  5406. ChatRoom.prototype.getMemberRole = function (peerJid) {
  5407. if (this.members[peerJid]) {
  5408. return this.members[peerJid].role;
  5409. }
  5410. return null;
  5411. };
  5412. ChatRoom.prototype.setJingleSession = function(session){
  5413. this.session = session;
  5414. this.session.room = this;
  5415. };
  5416. ChatRoom.prototype.removeStream = function (stream) {
  5417. if(!this.session)
  5418. return;
  5419. this.session.peerconnection.removeStream(stream);
  5420. };
  5421. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  5422. if(this.session) {
  5423. // FIXME: will block switchInProgress on true value in case of exception
  5424. this.session.switchStreams(stream, oldStream, callback, isAudio);
  5425. } else {
  5426. // We are done immediately
  5427. logger.warn("No conference handler or conference not started yet");
  5428. callback();
  5429. }
  5430. };
  5431. ChatRoom.prototype.addStream = function (stream, callback) {
  5432. if(this.session) {
  5433. // FIXME: will block switchInProgress on true value in case of exception
  5434. this.session.addStream(stream, callback);
  5435. } else {
  5436. // We are done immediately
  5437. logger.warn("No conference handler or conference not started yet");
  5438. callback();
  5439. }
  5440. };
  5441. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  5442. var self = this;
  5443. var localCallback = function (mute) {
  5444. self.sendVideoInfoPresence(mute);
  5445. if(callback)
  5446. callback(mute);
  5447. };
  5448. if(this.session)
  5449. {
  5450. this.session.setVideoMute(
  5451. mute, localCallback, options);
  5452. }
  5453. else {
  5454. localCallback(mute);
  5455. }
  5456. };
  5457. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  5458. //This will be for remote streams only
  5459. // if (this.forceMuted && !mute) {
  5460. // logger.info("Asking focus for unmute");
  5461. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  5462. // // FIXME: wait for result before resetting muted status
  5463. // this.forceMuted = false;
  5464. // }
  5465. return this.sendAudioInfoPresence(mute, callback);
  5466. };
  5467. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  5468. this.removeFromPresence("audiomuted");
  5469. this.addToPresence("audiomuted",
  5470. {attributes:
  5471. {"audions": "http://jitsi.org/jitmeet/audio"},
  5472. value: mute.toString()});
  5473. };
  5474. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  5475. this.addAudioInfoToPresence(mute);
  5476. if(this.connection) {
  5477. this.sendPresence();
  5478. }
  5479. if(callback)
  5480. callback();
  5481. };
  5482. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  5483. this.removeFromPresence("videomuted");
  5484. this.addToPresence("videomuted",
  5485. {attributes:
  5486. {"videons": "http://jitsi.org/jitmeet/video"},
  5487. value: mute.toString()});
  5488. };
  5489. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  5490. this.addVideoInfoToPresence(mute);
  5491. if(!this.connection)
  5492. return;
  5493. this.sendPresence();
  5494. };
  5495. ChatRoom.prototype.addListener = function(type, listener) {
  5496. this.eventEmitter.on(type, listener);
  5497. };
  5498. ChatRoom.prototype.removeListener = function (type, listener) {
  5499. this.eventEmitter.removeListener(type, listener);
  5500. };
  5501. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  5502. if(this.lastPresences[data.peerjid])
  5503. {
  5504. var pres = this.lastPresences[data.peerjid];
  5505. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  5506. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  5507. data.videomuted = ((videomuted.length > 0
  5508. && videomuted[0]
  5509. && videomuted[0]["value"] === "true")? true : false);
  5510. data.audiomuted = ((audiomuted.length > 0
  5511. && audiomuted[0]
  5512. && audiomuted[0]["value"] === "true")? true : false);
  5513. }
  5514. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  5515. };
  5516. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  5517. if (!this.session)
  5518. return null;
  5519. return this.session.getSsrcOwner(ssrc);
  5520. };
  5521. module.exports = ChatRoom;
  5522. }).call(this,"/modules/xmpp/ChatRoom.js")
  5523. },{"../../service/xmpp/XMPPEvents":86,"./moderator":34,"events":43,"jitsi-meet-logger":47}],27:[function(require,module,exports){
  5524. (function (__filename){
  5525. /*
  5526. * JingleSession provides an API to manage a single Jingle session. We will
  5527. * have different implementations depending on the underlying interface used
  5528. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  5529. */
  5530. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5531. function JingleSession(me, sid, connection, service, eventEmitter) {
  5532. /**
  5533. * Our JID.
  5534. */
  5535. this.me = me;
  5536. /**
  5537. * The Jingle session identifier.
  5538. */
  5539. this.sid = sid;
  5540. /**
  5541. * The XMPP connection.
  5542. */
  5543. this.connection = connection;
  5544. /**
  5545. * The XMPP service.
  5546. */
  5547. this.service = service;
  5548. /**
  5549. * The event emitter.
  5550. */
  5551. this.eventEmitter = eventEmitter;
  5552. /**
  5553. * Whether to use dripping or not. Dripping is sending trickle candidates
  5554. * not one-by-one.
  5555. * Note: currently we do not support 'false'.
  5556. */
  5557. this.usedrip = true;
  5558. /**
  5559. * When dripping is used, stores ICE candidates which are to be sent.
  5560. */
  5561. this.drip_container = [];
  5562. // Media constraints. Is this WebRTC only?
  5563. this.media_constraints = null;
  5564. // ICE servers config (RTCConfiguration?).
  5565. this.ice_config = {};
  5566. // The chat room instance associated with the session.
  5567. this.room = null;
  5568. }
  5569. /**
  5570. * Prepares this object to initiate a session.
  5571. * @param peerjid the JID of the remote peer.
  5572. * @param isInitiator whether we will be the Jingle initiator.
  5573. * @param media_constraints
  5574. * @param ice_config
  5575. */
  5576. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  5577. media_constraints, ice_config) {
  5578. this.media_constraints = media_constraints;
  5579. this.ice_config = ice_config;
  5580. if (this.state !== null) {
  5581. logger.error('attempt to initiate on session ' + this.sid +
  5582. 'in state ' + this.state);
  5583. return;
  5584. }
  5585. this.state = 'pending';
  5586. this.initiator = isInitiator ? this.me : peerjid;
  5587. this.responder = !isInitiator ? this.me : peerjid;
  5588. this.peerjid = peerjid;
  5589. this.doInitialize();
  5590. };
  5591. /**
  5592. * Finishes initialization.
  5593. */
  5594. JingleSession.prototype.doInitialize = function() {};
  5595. /**
  5596. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  5597. * Note: currently only used on transport-info
  5598. */
  5599. JingleSession.prototype.addIceCandidates = function(contents) {};
  5600. /**
  5601. * Handles an 'add-source' event.
  5602. *
  5603. * @param contents an array of Jingle 'content' elements.
  5604. */
  5605. JingleSession.prototype.addSources = function(contents) {};
  5606. /**
  5607. * Handles a 'remove-source' event.
  5608. *
  5609. * @param contents an array of Jingle 'content' elements.
  5610. */
  5611. JingleSession.prototype.removeSources = function(contents) {};
  5612. /**
  5613. * Terminates this Jingle session (stops sending media and closes the streams?)
  5614. */
  5615. JingleSession.prototype.terminate = function() {};
  5616. /**
  5617. * Sends a Jingle session-terminate message to the peer and terminates the
  5618. * session.
  5619. * @param reason
  5620. * @param text
  5621. */
  5622. JingleSession.prototype.sendTerminate = function(reason, text) {};
  5623. /**
  5624. * Handles an offer from the remote peer (prepares to accept a session).
  5625. * @param jingle the 'jingle' XML element.
  5626. */
  5627. JingleSession.prototype.setOffer = function(jingle) {};
  5628. /**
  5629. * Handles an answer from the remote peer (prepares to accept a session).
  5630. * @param jingle the 'jingle' XML element.
  5631. */
  5632. JingleSession.prototype.setAnswer = function(jingle) {};
  5633. module.exports = JingleSession;
  5634. }).call(this,"/modules/xmpp/JingleSession.js")
  5635. },{"jitsi-meet-logger":47}],28:[function(require,module,exports){
  5636. (function (__filename){
  5637. /* jshint -W117 */
  5638. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5639. var JingleSession = require("./JingleSession");
  5640. var TraceablePeerConnection = require("./TraceablePeerConnection");
  5641. var SDPDiffer = require("./SDPDiffer");
  5642. var SDPUtil = require("./SDPUtil");
  5643. var SDP = require("./SDP");
  5644. var async = require("async");
  5645. var transform = require("sdp-transform");
  5646. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5647. var RTCBrowserType = require("../RTC/RTCBrowserType");
  5648. var SSRCReplacement = require("./LocalSSRCReplacement");
  5649. var RTC = require("../RTC/RTC");
  5650. // Jingle stuff
  5651. function JingleSessionPC(me, sid, connection, service) {
  5652. JingleSession.call(this, me, sid, connection, service);
  5653. this.initiator = null;
  5654. this.responder = null;
  5655. this.peerjid = null;
  5656. this.state = null;
  5657. this.localSDP = null;
  5658. this.remoteSDP = null;
  5659. this.relayedStreams = [];
  5660. this.usetrickle = true;
  5661. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  5662. this.hadstuncandidate = false;
  5663. this.hadturncandidate = false;
  5664. this.lasticecandidate = false;
  5665. this.statsinterval = null;
  5666. this.reason = null;
  5667. this.addssrc = [];
  5668. this.removessrc = [];
  5669. this.pendingop = null;
  5670. this.switchstreams = false;
  5671. this.addingStreams = false;
  5672. this.wait = true;
  5673. this.localStreamsSSRC = null;
  5674. this.ssrcOwners = {};
  5675. this.ssrcVideoTypes = {};
  5676. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  5677. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  5678. /**
  5679. * The indicator which determines whether the (local) video has been muted
  5680. * in response to a user command in contrast to an automatic decision made
  5681. * by the application logic.
  5682. */
  5683. this.videoMuteByUser = false;
  5684. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  5685. // We start with the queue paused. We resume it when the signaling state is
  5686. // stable and the ice connection state is connected.
  5687. this.modifySourcesQueue.pause();
  5688. }
  5689. //XXX this is badly broken...
  5690. JingleSessionPC.prototype = JingleSession.prototype;
  5691. JingleSessionPC.prototype.constructor = JingleSessionPC;
  5692. JingleSessionPC.prototype.setOffer = function(offer) {
  5693. this.setRemoteDescription(offer, 'offer');
  5694. };
  5695. JingleSessionPC.prototype.setAnswer = function(answer) {
  5696. this.setRemoteDescription(answer, 'answer');
  5697. };
  5698. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  5699. var signalingState = this.peerconnection.signalingState;
  5700. var iceConnectionState = this.peerconnection.iceConnectionState;
  5701. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  5702. this.modifySourcesQueue.resume();
  5703. } else {
  5704. this.modifySourcesQueue.pause();
  5705. }
  5706. };
  5707. JingleSessionPC.prototype.doInitialize = function () {
  5708. var self = this;
  5709. this.hadstuncandidate = false;
  5710. this.hadturncandidate = false;
  5711. this.lasticecandidate = false;
  5712. // True if reconnect is in progress
  5713. this.isreconnect = false;
  5714. // Set to true if the connection was ever stable
  5715. this.wasstable = false;
  5716. this.peerconnection = new TraceablePeerConnection(
  5717. this.connection.jingle.ice_config,
  5718. RTC.getPCConstraints(),
  5719. this);
  5720. this.peerconnection.onicecandidate = function (event) {
  5721. var protocol;
  5722. if (event && event.candidate) {
  5723. protocol = (typeof event.candidate.protocol === 'string')
  5724. ? event.candidate.protocol.toLowerCase() : '';
  5725. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  5726. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  5727. return;
  5728. }
  5729. }
  5730. self.sendIceCandidate(event.candidate);
  5731. };
  5732. this.peerconnection.onaddstream = function (event) {
  5733. if (event.stream.id !== 'default') {
  5734. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  5735. self.remoteStreamAdded(event);
  5736. } else {
  5737. // This is a recvonly stream. Clients that implement Unified Plan,
  5738. // such as Firefox use recvonly "streams/channels/tracks" for
  5739. // receiving remote stream/tracks, as opposed to Plan B where there
  5740. // are only 3 channels: audio, video and data.
  5741. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  5742. }
  5743. };
  5744. this.peerconnection.onremovestream = function (event) {
  5745. // Remove the stream from remoteStreams
  5746. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  5747. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  5748. };
  5749. this.peerconnection.onsignalingstatechange = function (event) {
  5750. if (!(self && self.peerconnection)) return;
  5751. if (self.peerconnection.signalingState === 'stable') {
  5752. self.wasstable = true;
  5753. }
  5754. self.updateModifySourcesQueue();
  5755. };
  5756. /**
  5757. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  5758. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  5759. * RTCPeerConnection.iceConnectionState changes.
  5760. *
  5761. * @param event the event containing information about the change
  5762. */
  5763. this.peerconnection.oniceconnectionstatechange = function (event) {
  5764. if (!(self && self.peerconnection)) return;
  5765. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  5766. ":\t", window.performance.now());
  5767. self.updateModifySourcesQueue();
  5768. switch (self.peerconnection.iceConnectionState) {
  5769. case 'connected':
  5770. // Informs interested parties that the connection has been restored.
  5771. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  5772. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  5773. self.isreconnect = false;
  5774. break;
  5775. case 'disconnected':
  5776. self.isreconnect = true;
  5777. // Informs interested parties that the connection has been interrupted.
  5778. if (self.wasstable)
  5779. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  5780. break;
  5781. case 'failed':
  5782. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5783. break;
  5784. }
  5785. onIceConnectionStateChange(self.sid, self);
  5786. };
  5787. this.peerconnection.onnegotiationneeded = function (event) {
  5788. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  5789. };
  5790. this.relayedStreams.forEach(function(stream) {
  5791. self.peerconnection.addStream(stream);
  5792. });
  5793. };
  5794. function onIceConnectionStateChange(sid, session) {
  5795. switch (session.peerconnection.iceConnectionState) {
  5796. case 'checking':
  5797. session.timeChecking = (new Date()).getTime();
  5798. session.firstconnect = true;
  5799. break;
  5800. case 'completed': // on caller side
  5801. case 'connected':
  5802. if (session.firstconnect) {
  5803. session.firstconnect = false;
  5804. var metadata = {};
  5805. metadata.setupTime
  5806. = (new Date()).getTime() - session.timeChecking;
  5807. session.peerconnection.getStats(function (res) {
  5808. if(res && res.result) {
  5809. res.result().forEach(function (report) {
  5810. if (report.type == 'googCandidatePair' &&
  5811. report.stat('googActiveConnection') == 'true') {
  5812. metadata.localCandidateType
  5813. = report.stat('googLocalCandidateType');
  5814. metadata.remoteCandidateType
  5815. = report.stat('googRemoteCandidateType');
  5816. // log pair as well so we can get nice pie
  5817. // charts
  5818. metadata.candidatePair
  5819. = report.stat('googLocalCandidateType') +
  5820. ';' +
  5821. report.stat('googRemoteCandidateType');
  5822. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  5823. {
  5824. metadata.ipv6 = true;
  5825. }
  5826. }
  5827. });
  5828. }
  5829. });
  5830. }
  5831. break;
  5832. }
  5833. }
  5834. JingleSessionPC.prototype.accept = function () {
  5835. this.state = 'active';
  5836. var pranswer = this.peerconnection.localDescription;
  5837. if (!pranswer || pranswer.type != 'pranswer') {
  5838. return;
  5839. }
  5840. logger.log('going from pranswer to answer');
  5841. if (this.usetrickle) {
  5842. // remove candidates already sent from session-accept
  5843. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  5844. for (var i = 0; i < lines.length; i++) {
  5845. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  5846. }
  5847. }
  5848. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  5849. // FIXME: change any inactive to sendrecv or whatever they were originally
  5850. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  5851. }
  5852. var prsdp = new SDP(pranswer.sdp);
  5853. if (self.webrtcIceTcpDisable) {
  5854. prsdp.removeTcpCandidates = true;
  5855. }
  5856. if (self.webrtcIceUdpDisable) {
  5857. prsdp.removeUdpCandidates = true;
  5858. }
  5859. var accept = $iq({to: this.peerjid,
  5860. type: 'set'})
  5861. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5862. action: 'session-accept',
  5863. initiator: this.initiator,
  5864. responder: this.responder,
  5865. sid: this.sid });
  5866. // FIXME why do we generate session-accept in 3 different places ?
  5867. prsdp.toJingle(
  5868. accept,
  5869. this.initiator == this.me ? 'initiator' : 'responder',
  5870. this.localStreamsSSRC);
  5871. var sdp = this.peerconnection.localDescription.sdp;
  5872. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  5873. // FIXME: change any inactive to sendrecv or whatever they were originally
  5874. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  5875. }
  5876. var self = this;
  5877. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  5878. function () {
  5879. //logger.log('setLocalDescription success');
  5880. self.setLocalDescription();
  5881. SSRCReplacement.processSessionInit(accept);
  5882. self.connection.sendIQ(accept,
  5883. function () {
  5884. var ack = {};
  5885. ack.source = 'answer';
  5886. $(document).trigger('ack.jingle', [self.sid, ack]);
  5887. },
  5888. function (stanza) {
  5889. var error = ($(stanza).find('error').length) ? {
  5890. code: $(stanza).find('error').attr('code'),
  5891. reason: $(stanza).find('error :first')[0].tagName
  5892. }:{};
  5893. error.source = 'answer';
  5894. JingleSessionPC.onJingleError(self.sid, error);
  5895. },
  5896. 10000);
  5897. },
  5898. function (e) {
  5899. logger.error('setLocalDescription failed', e);
  5900. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5901. }
  5902. );
  5903. };
  5904. JingleSessionPC.prototype.terminate = function (reason) {
  5905. this.state = 'ended';
  5906. this.reason = reason;
  5907. this.peerconnection.close();
  5908. if (this.statsinterval !== null) {
  5909. window.clearInterval(this.statsinterval);
  5910. this.statsinterval = null;
  5911. }
  5912. };
  5913. JingleSessionPC.prototype.active = function () {
  5914. return this.state == 'active';
  5915. };
  5916. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  5917. var self = this;
  5918. if (candidate && !this.lasticecandidate) {
  5919. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  5920. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  5921. if (!(ice && jcand)) {
  5922. logger.error('failed to get ice && jcand');
  5923. return;
  5924. }
  5925. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  5926. if (jcand.type === 'srflx') {
  5927. this.hadstuncandidate = true;
  5928. } else if (jcand.type === 'relay') {
  5929. this.hadturncandidate = true;
  5930. }
  5931. if (this.usetrickle) {
  5932. if (this.usedrip) {
  5933. if (this.drip_container.length === 0) {
  5934. // start 20ms callout
  5935. window.setTimeout(function () {
  5936. if (self.drip_container.length === 0) return;
  5937. self.sendIceCandidates(self.drip_container);
  5938. self.drip_container = [];
  5939. }, 20);
  5940. }
  5941. this.drip_container.push(candidate);
  5942. return;
  5943. } else {
  5944. self.sendIceCandidate([candidate]);
  5945. }
  5946. }
  5947. } else {
  5948. //logger.log('sendIceCandidate: last candidate.');
  5949. if (!this.usetrickle) {
  5950. //logger.log('should send full offer now...');
  5951. //FIXME why do we generate session-accept in 3 different places ?
  5952. var init = $iq({to: this.peerjid,
  5953. type: 'set'})
  5954. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5955. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  5956. initiator: this.initiator,
  5957. sid: this.sid});
  5958. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  5959. if (self.webrtcIceTcpDisable) {
  5960. this.localSDP.removeTcpCandidates = true;
  5961. }
  5962. if (self.webrtcIceUdpDisable) {
  5963. this.localSDP.removeUdpCandidates = true;
  5964. }
  5965. var sendJingle = function (ssrc) {
  5966. if(!ssrc)
  5967. ssrc = {};
  5968. self.localSDP.toJingle(
  5969. init,
  5970. self.initiator == self.me ? 'initiator' : 'responder',
  5971. ssrc);
  5972. SSRCReplacement.processSessionInit(init);
  5973. self.connection.sendIQ(init,
  5974. function () {
  5975. //logger.log('session initiate ack');
  5976. var ack = {};
  5977. ack.source = 'offer';
  5978. $(document).trigger('ack.jingle', [self.sid, ack]);
  5979. },
  5980. function (stanza) {
  5981. self.state = 'error';
  5982. self.peerconnection.close();
  5983. var error = ($(stanza).find('error').length) ? {
  5984. code: $(stanza).find('error').attr('code'),
  5985. reason: $(stanza).find('error :first')[0].tagName,
  5986. }:{};
  5987. error.source = 'offer';
  5988. JingleSessionPC.onJingleError(self.sid, error);
  5989. },
  5990. 10000);
  5991. };
  5992. sendJingle();
  5993. }
  5994. this.lasticecandidate = true;
  5995. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  5996. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  5997. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  5998. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  5999. }
  6000. }
  6001. };
  6002. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  6003. logger.log('sendIceCandidates', candidates);
  6004. var cand = $iq({to: this.peerjid, type: 'set'})
  6005. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6006. action: 'transport-info',
  6007. initiator: this.initiator,
  6008. sid: this.sid});
  6009. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  6010. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  6011. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  6012. if (cands.length > 0) {
  6013. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  6014. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6015. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  6016. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  6017. }).c('transport', ice);
  6018. for (var i = 0; i < cands.length; i++) {
  6019. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  6020. }
  6021. // add fingerprint
  6022. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  6023. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  6024. tmp.required = true;
  6025. cand.c(
  6026. 'fingerprint',
  6027. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  6028. .t(tmp.fingerprint);
  6029. delete tmp.fingerprint;
  6030. cand.attrs(tmp);
  6031. cand.up();
  6032. }
  6033. cand.up(); // transport
  6034. cand.up(); // content
  6035. }
  6036. }
  6037. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  6038. //logger.log('was this the last candidate', this.lasticecandidate);
  6039. this.connection.sendIQ(cand,
  6040. function () {
  6041. var ack = {};
  6042. ack.source = 'transportinfo';
  6043. $(document).trigger('ack.jingle', [this.sid, ack]);
  6044. },
  6045. function (stanza) {
  6046. var error = ($(stanza).find('error').length) ? {
  6047. code: $(stanza).find('error').attr('code'),
  6048. reason: $(stanza).find('error :first')[0].tagName,
  6049. }:{};
  6050. error.source = 'transportinfo';
  6051. JingleSessionPC.onJingleError(this.sid, error);
  6052. },
  6053. 10000);
  6054. };
  6055. JingleSessionPC.prototype.sendOffer = function () {
  6056. //logger.log('sendOffer...');
  6057. var self = this;
  6058. this.peerconnection.createOffer(function (sdp) {
  6059. self.createdOffer(sdp);
  6060. },
  6061. function (e) {
  6062. logger.error('createOffer failed', e);
  6063. },
  6064. this.media_constraints
  6065. );
  6066. };
  6067. // FIXME createdOffer is never used in jitsi-meet
  6068. JingleSessionPC.prototype.createdOffer = function (sdp) {
  6069. //logger.log('createdOffer', sdp);
  6070. var self = this;
  6071. this.localSDP = new SDP(sdp.sdp);
  6072. //this.localSDP.mangle();
  6073. var sendJingle = function () {
  6074. var init = $iq({to: this.peerjid,
  6075. type: 'set'})
  6076. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6077. action: 'session-initiate',
  6078. initiator: this.initiator,
  6079. sid: this.sid});
  6080. self.localSDP.toJingle(
  6081. init,
  6082. this.initiator == this.me ? 'initiator' : 'responder',
  6083. this.localStreamsSSRC);
  6084. SSRCReplacement.processSessionInit(init);
  6085. self.connection.sendIQ(init,
  6086. function () {
  6087. var ack = {};
  6088. ack.source = 'offer';
  6089. $(document).trigger('ack.jingle', [self.sid, ack]);
  6090. },
  6091. function (stanza) {
  6092. self.state = 'error';
  6093. self.peerconnection.close();
  6094. var error = ($(stanza).find('error').length) ? {
  6095. code: $(stanza).find('error').attr('code'),
  6096. reason: $(stanza).find('error :first')[0].tagName,
  6097. }:{};
  6098. error.source = 'offer';
  6099. JingleSessionPC.onJingleError(self.sid, error);
  6100. },
  6101. 10000);
  6102. }
  6103. sdp.sdp = this.localSDP.raw;
  6104. this.peerconnection.setLocalDescription(sdp,
  6105. function () {
  6106. if(self.usetrickle)
  6107. {
  6108. sendJingle();
  6109. }
  6110. self.setLocalDescription();
  6111. //logger.log('setLocalDescription success');
  6112. },
  6113. function (e) {
  6114. logger.error('setLocalDescription failed', e);
  6115. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6116. }
  6117. );
  6118. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6119. for (var i = 0; i < cands.length; i++) {
  6120. var cand = SDPUtil.parse_icecandidate(cands[i]);
  6121. if (cand.type == 'srflx') {
  6122. this.hadstuncandidate = true;
  6123. } else if (cand.type == 'relay') {
  6124. this.hadturncandidate = true;
  6125. }
  6126. }
  6127. };
  6128. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  6129. var self = this;
  6130. $(contents).each(function (idx, content) {
  6131. var name = $(content).attr('name');
  6132. var mediaType = this.getAttribute('name');
  6133. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  6134. ssrcs.each(function () {
  6135. var ssrc = this.getAttribute('ssrc');
  6136. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  6137. function () {
  6138. var owner = this.getAttribute('owner');
  6139. self.ssrcOwners[ssrc] = owner;
  6140. }
  6141. );
  6142. });
  6143. });
  6144. };
  6145. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  6146. return this.ssrcOwners[ssrc];
  6147. };
  6148. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  6149. //logger.log('setting remote description... ', desctype);
  6150. this.remoteSDP = new SDP('');
  6151. if (self.webrtcIceTcpDisable) {
  6152. this.remoteSDP.removeTcpCandidates = true;
  6153. }
  6154. if (self.webrtcIceUdpDisable) {
  6155. this.remoteSDP.removeUdpCandidates = true;
  6156. }
  6157. this.remoteSDP.fromJingle(elem);
  6158. this.readSsrcInfo($(elem).find(">content"));
  6159. if (this.peerconnection.remoteDescription) {
  6160. logger.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  6161. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  6162. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  6163. for (var i = 0; i < pranswer.media.length; i++) {
  6164. // make sure we have ice ufrag and pwd
  6165. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  6166. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  6167. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  6168. } else {
  6169. logger.warn('no ice ufrag?');
  6170. }
  6171. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  6172. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  6173. } else {
  6174. logger.warn('no ice pwd?');
  6175. }
  6176. }
  6177. // copy over candidates
  6178. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  6179. for (var j = 0; j < lines.length; j++) {
  6180. this.remoteSDP.media[i] += lines[j] + '\r\n';
  6181. }
  6182. }
  6183. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6184. }
  6185. }
  6186. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  6187. this.peerconnection.setRemoteDescription(remotedesc,
  6188. function () {
  6189. //logger.log('setRemoteDescription success');
  6190. },
  6191. function (e) {
  6192. logger.error('setRemoteDescription error', e);
  6193. JingleSessionPC.onJingleFatalError(self, e);
  6194. }
  6195. );
  6196. };
  6197. /**
  6198. * Adds remote ICE candidates to this Jingle session.
  6199. * @param elem An array of Jingle "content" elements?
  6200. */
  6201. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  6202. var self = this;
  6203. if (this.peerconnection.signalingState == 'closed') {
  6204. return;
  6205. }
  6206. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  6207. logger.log('trickle ice candidate arriving before session accept...');
  6208. // create a PRANSWER for setRemoteDescription
  6209. if (!this.remoteSDP) {
  6210. var cobbled = 'v=0\r\n' +
  6211. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  6212. 's=-\r\n' +
  6213. 't=0 0\r\n';
  6214. // first, take some things from the local description
  6215. for (var i = 0; i < this.localSDP.media.length; i++) {
  6216. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  6217. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  6218. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  6219. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  6220. }
  6221. cobbled += 'a=inactive\r\n';
  6222. }
  6223. this.remoteSDP = new SDP(cobbled);
  6224. }
  6225. // then add things like ice and dtls from remote candidate
  6226. elem.each(function () {
  6227. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  6228. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6229. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6230. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  6231. var tmp = $(this).find('transport');
  6232. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  6233. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  6234. tmp = $(this).find('transport>fingerprint');
  6235. if (tmp.length) {
  6236. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  6237. } else {
  6238. logger.log('no dtls fingerprint (webrtc issue #1718?)');
  6239. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  6240. }
  6241. break;
  6242. }
  6243. }
  6244. }
  6245. });
  6246. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6247. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  6248. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  6249. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  6250. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  6251. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  6252. }).length == this.remoteSDP.media.length;
  6253. if (iscomplete) {
  6254. logger.log('setting pranswer');
  6255. try {
  6256. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  6257. function() {
  6258. },
  6259. function(e) {
  6260. logger.log('setRemoteDescription pranswer failed', e.toString());
  6261. });
  6262. } catch (e) {
  6263. logger.error('setting pranswer failed', e);
  6264. }
  6265. } else {
  6266. //logger.log('not yet setting pranswer');
  6267. }
  6268. }
  6269. // operate on each content element
  6270. elem.each(function () {
  6271. // would love to deactivate this, but firefox still requires it
  6272. var idx = -1;
  6273. var i;
  6274. for (i = 0; i < self.remoteSDP.media.length; i++) {
  6275. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6276. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6277. idx = i;
  6278. break;
  6279. }
  6280. }
  6281. if (idx == -1) { // fall back to localdescription
  6282. for (i = 0; i < self.localSDP.media.length; i++) {
  6283. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6284. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6285. idx = i;
  6286. break;
  6287. }
  6288. }
  6289. }
  6290. var name = $(this).attr('name');
  6291. // TODO: check ice-pwd and ice-ufrag?
  6292. $(this).find('transport>candidate').each(function () {
  6293. var line, candidate;
  6294. var protocol = this.getAttribute('protocol');
  6295. protocol =
  6296. (typeof protocol === 'string') ? protocol.toLowerCase() : '';
  6297. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  6298. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  6299. return;
  6300. }
  6301. line = SDPUtil.candidateFromJingle(this);
  6302. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  6303. sdpMid: name,
  6304. candidate: line});
  6305. try {
  6306. self.peerconnection.addIceCandidate(candidate);
  6307. } catch (e) {
  6308. logger.error('addIceCandidate failed', e.toString(), line);
  6309. }
  6310. });
  6311. });
  6312. };
  6313. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  6314. //logger.log('createAnswer', provisional);
  6315. var self = this;
  6316. this.peerconnection.createAnswer(
  6317. function (sdp) {
  6318. self.createdAnswer(sdp, provisional);
  6319. },
  6320. function (e) {
  6321. logger.error('createAnswer failed', e);
  6322. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6323. },
  6324. this.media_constraints
  6325. );
  6326. };
  6327. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  6328. //logger.log('createAnswer callback');
  6329. var self = this;
  6330. this.localSDP = new SDP(sdp.sdp);
  6331. //this.localSDP.mangle();
  6332. this.usepranswer = provisional === true;
  6333. if (this.usetrickle) {
  6334. if (this.usepranswer) {
  6335. sdp.type = 'pranswer';
  6336. for (var i = 0; i < this.localSDP.media.length; i++) {
  6337. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  6338. }
  6339. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  6340. }
  6341. }
  6342. var self = this;
  6343. var sendJingle = function (ssrcs) {
  6344. // FIXME why do we generate session-accept in 3 different places ?
  6345. var accept = $iq({to: self.peerjid,
  6346. type: 'set'})
  6347. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6348. action: 'session-accept',
  6349. initiator: self.initiator,
  6350. responder: self.responder,
  6351. sid: self.sid });
  6352. if (self.webrtcIceTcpDisable) {
  6353. self.localSDP.removeTcpCandidates = true;
  6354. }
  6355. if (self.webrtcIceUdpDisable) {
  6356. self.localSDP.removeUdpCandidates = true;
  6357. }
  6358. self.localSDP.toJingle(
  6359. accept,
  6360. self.initiator == self.me ? 'initiator' : 'responder',
  6361. ssrcs);
  6362. SSRCReplacement.processSessionInit(accept);
  6363. self.connection.sendIQ(accept,
  6364. function () {
  6365. var ack = {};
  6366. ack.source = 'answer';
  6367. $(document).trigger('ack.jingle', [self.sid, ack]);
  6368. },
  6369. function (stanza) {
  6370. var error = ($(stanza).find('error').length) ? {
  6371. code: $(stanza).find('error').attr('code'),
  6372. reason: $(stanza).find('error :first')[0].tagName,
  6373. }:{};
  6374. error.source = 'answer';
  6375. JingleSessionPC.onJingleError(self.sid, error);
  6376. },
  6377. 10000);
  6378. }
  6379. sdp.sdp = this.localSDP.raw;
  6380. this.peerconnection.setLocalDescription(sdp,
  6381. function () {
  6382. //logger.log('setLocalDescription success');
  6383. if (self.usetrickle && !self.usepranswer) {
  6384. sendJingle();
  6385. }
  6386. self.setLocalDescription();
  6387. },
  6388. function (e) {
  6389. logger.error('setLocalDescription failed', e);
  6390. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6391. }
  6392. );
  6393. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6394. for (var j = 0; j < cands.length; j++) {
  6395. var cand = SDPUtil.parse_icecandidate(cands[j]);
  6396. if (cand.type == 'srflx') {
  6397. this.hadstuncandidate = true;
  6398. } else if (cand.type == 'relay') {
  6399. this.hadturncandidate = true;
  6400. }
  6401. }
  6402. };
  6403. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  6404. var self = this,
  6405. term = $iq({to: this.peerjid,
  6406. type: 'set'})
  6407. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6408. action: 'session-terminate',
  6409. initiator: this.initiator,
  6410. sid: this.sid})
  6411. .c('reason')
  6412. .c(reason || 'success');
  6413. if (text) {
  6414. term.up().c('text').t(text);
  6415. }
  6416. this.connection.sendIQ(term,
  6417. function () {
  6418. self.peerconnection.close();
  6419. self.peerconnection = null;
  6420. self.terminate();
  6421. var ack = {};
  6422. ack.source = 'terminate';
  6423. $(document).trigger('ack.jingle', [self.sid, ack]);
  6424. },
  6425. function (stanza) {
  6426. var error = ($(stanza).find('error').length) ? {
  6427. code: $(stanza).find('error').attr('code'),
  6428. reason: $(stanza).find('error :first')[0].tagName,
  6429. }:{};
  6430. $(document).trigger('ack.jingle', [self.sid, error]);
  6431. },
  6432. 10000);
  6433. if (this.statsinterval !== null) {
  6434. window.clearInterval(this.statsinterval);
  6435. this.statsinterval = null;
  6436. }
  6437. };
  6438. /**
  6439. * Handles a Jingle source-add message for this Jingle session.
  6440. * @param elem An array of Jingle "content" elements.
  6441. */
  6442. JingleSessionPC.prototype.addSource = function (elem) {
  6443. var self = this;
  6444. // FIXME: dirty waiting
  6445. if (!this.peerconnection.localDescription)
  6446. {
  6447. logger.warn("addSource - localDescription not ready yet")
  6448. setTimeout(function()
  6449. {
  6450. self.addSource(elem);
  6451. },
  6452. 200
  6453. );
  6454. return;
  6455. }
  6456. logger.log('addssrc', new Date().getTime());
  6457. logger.log('ice', this.peerconnection.iceConnectionState);
  6458. this.readSsrcInfo(elem);
  6459. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6460. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  6461. $(elem).each(function (idx, content) {
  6462. var name = $(content).attr('name');
  6463. var lines = '';
  6464. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6465. var semantics = this.getAttribute('semantics');
  6466. var ssrcs = $(this).find('>source').map(function () {
  6467. return this.getAttribute('ssrc');
  6468. }).get();
  6469. if (ssrcs.length) {
  6470. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6471. }
  6472. });
  6473. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  6474. tmp.each(function () {
  6475. var ssrc = $(this).attr('ssrc');
  6476. if(mySdp.containsSSRC(ssrc)){
  6477. /**
  6478. * This happens when multiple participants change their streams at the same time and
  6479. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  6480. * addssrc are scheduled for update IQ. See
  6481. */
  6482. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  6483. return;
  6484. }
  6485. if (sdp.containsSSRC(ssrc)) {
  6486. logger.warn("Source-add request for existing SSRC: " + ssrc);
  6487. return;
  6488. }
  6489. $(this).find('>parameter').each(function () {
  6490. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  6491. if ($(this).attr('value') && $(this).attr('value').length)
  6492. lines += ':' + $(this).attr('value');
  6493. lines += '\r\n';
  6494. });
  6495. });
  6496. sdp.media.forEach(function(media, idx) {
  6497. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  6498. return;
  6499. sdp.media[idx] += lines;
  6500. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  6501. self.addssrc[idx] += lines;
  6502. });
  6503. sdp.raw = sdp.session + sdp.media.join('');
  6504. });
  6505. this.modifySourcesQueue.push(function() {
  6506. // When a source is added and if this is FF, a new channel is allocated
  6507. // for receiving the added source. We need to diffuse the SSRC of this
  6508. // new recvonly channel to the rest of the peers.
  6509. logger.log('modify sources done');
  6510. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6511. logger.log("SDPs", mySdp, newSdp);
  6512. self.notifyMySSRCUpdate(mySdp, newSdp);
  6513. });
  6514. };
  6515. /**
  6516. * Handles a Jingle source-remove message for this Jingle session.
  6517. * @param elem An array of Jingle "content" elements.
  6518. */
  6519. JingleSessionPC.prototype.removeSource = function (elem) {
  6520. var self = this;
  6521. // FIXME: dirty waiting
  6522. if (!this.peerconnection.localDescription) {
  6523. logger.warn("removeSource - localDescription not ready yet");
  6524. setTimeout(function() {
  6525. self.removeSource(elem);
  6526. },
  6527. 200
  6528. );
  6529. return;
  6530. }
  6531. logger.log('removessrc', new Date().getTime());
  6532. logger.log('ice', this.peerconnection.iceConnectionState);
  6533. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6534. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  6535. $(elem).each(function (idx, content) {
  6536. var name = $(content).attr('name');
  6537. var lines = '';
  6538. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6539. var semantics = this.getAttribute('semantics');
  6540. var ssrcs = $(this).find('>source').map(function () {
  6541. return this.getAttribute('ssrc');
  6542. }).get();
  6543. if (ssrcs.length) {
  6544. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6545. }
  6546. });
  6547. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  6548. tmp.each(function () {
  6549. var ssrc = $(this).attr('ssrc');
  6550. // This should never happen, but can be useful for bug detection
  6551. if(mySdp.containsSSRC(ssrc)){
  6552. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  6553. return;
  6554. }
  6555. $(this).find('>parameter').each(function () {
  6556. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  6557. if ($(this).attr('value') && $(this).attr('value').length)
  6558. lines += ':' + $(this).attr('value');
  6559. lines += '\r\n';
  6560. });
  6561. });
  6562. sdp.media.forEach(function(media, idx) {
  6563. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  6564. return;
  6565. sdp.media[idx] += lines;
  6566. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  6567. self.removessrc[idx] += lines;
  6568. });
  6569. sdp.raw = sdp.session + sdp.media.join('');
  6570. });
  6571. this.modifySourcesQueue.push(function() {
  6572. // When a source is removed and if this is FF, the recvonly channel that
  6573. // receives the remote stream is deactivated . We need to diffuse the
  6574. // recvonly SSRC removal to the rest of the peers.
  6575. logger.log('modify sources done');
  6576. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6577. logger.log("SDPs", mySdp, newSdp);
  6578. self.notifyMySSRCUpdate(mySdp, newSdp);
  6579. });
  6580. };
  6581. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  6582. var self = this;
  6583. if (this.peerconnection.signalingState == 'closed') return;
  6584. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  6585. || this.switchstreams || this.addingStreams)){
  6586. // There is nothing to do since scheduled job might have been executed by another succeeding call
  6587. this.setLocalDescription();
  6588. if(successCallback){
  6589. successCallback();
  6590. }
  6591. queueCallback();
  6592. return;
  6593. }
  6594. // Reset switch streams flags
  6595. this.switchstreams = false;
  6596. this.addingStreams = false;
  6597. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6598. // add sources
  6599. this.addssrc.forEach(function(lines, idx) {
  6600. sdp.media[idx] += lines;
  6601. });
  6602. this.addssrc = [];
  6603. // remove sources
  6604. this.removessrc.forEach(function(lines, idx) {
  6605. lines = lines.split('\r\n');
  6606. lines.pop(); // remove empty last element;
  6607. lines.forEach(function(line) {
  6608. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  6609. });
  6610. });
  6611. this.removessrc = [];
  6612. sdp.raw = sdp.session + sdp.media.join('');
  6613. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  6614. function() {
  6615. if(self.signalingState == 'closed') {
  6616. logger.error("createAnswer attempt on closed state");
  6617. queueCallback("createAnswer attempt on closed state");
  6618. return;
  6619. }
  6620. self.peerconnection.createAnswer(
  6621. function(modifiedAnswer) {
  6622. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  6623. if (self.pendingop !== null) {
  6624. var sdp = new SDP(modifiedAnswer.sdp);
  6625. if (sdp.media.length > 1) {
  6626. switch(self.pendingop) {
  6627. case 'mute':
  6628. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  6629. break;
  6630. case 'unmute':
  6631. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  6632. break;
  6633. }
  6634. sdp.raw = sdp.session + sdp.media.join('');
  6635. modifiedAnswer.sdp = sdp.raw;
  6636. }
  6637. self.pendingop = null;
  6638. }
  6639. // FIXME: pushing down an answer while ice connection state
  6640. // is still checking is bad...
  6641. //logger.log(self.peerconnection.iceConnectionState);
  6642. // trying to work around another chrome bug
  6643. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  6644. self.peerconnection.setLocalDescription(modifiedAnswer,
  6645. function() {
  6646. //logger.log('modified setLocalDescription ok');
  6647. self.setLocalDescription();
  6648. if(successCallback){
  6649. successCallback();
  6650. }
  6651. queueCallback();
  6652. },
  6653. function(error) {
  6654. logger.error('modified setLocalDescription failed', error);
  6655. queueCallback(error);
  6656. }
  6657. );
  6658. },
  6659. function(error) {
  6660. logger.error('modified answer failed', error);
  6661. queueCallback(error);
  6662. }
  6663. );
  6664. },
  6665. function(error) {
  6666. logger.error('modify failed', error);
  6667. queueCallback(error);
  6668. }
  6669. );
  6670. };
  6671. /**
  6672. * Switches video streams.
  6673. * @param newStream new stream that will be used as video of this session.
  6674. * @param oldStream old video stream of this session.
  6675. * @param successCallback callback executed after successful stream switch.
  6676. * @param isAudio whether the streams are audio (if true) or video (if false).
  6677. */
  6678. JingleSessionPC.prototype.switchStreams =
  6679. function (newStream, oldStream, successCallback, isAudio) {
  6680. var self = this;
  6681. var sender, newTrack;
  6682. var senderKind = isAudio ? 'audio' : 'video';
  6683. // Remember SDP to figure out added/removed SSRCs
  6684. var oldSdp = null;
  6685. if (self.peerconnection) {
  6686. if (self.peerconnection.localDescription) {
  6687. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  6688. }
  6689. if (RTCBrowserType.getBrowserType() ===
  6690. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  6691. // On Firefox we don't replace MediaStreams as this messes up the
  6692. // m-lines (which can't be removed in Plan Unified) and brings a lot
  6693. // of complications. Instead, we use the RTPSender and replace just
  6694. // the track.
  6695. // Find the right sender (for audio or video)
  6696. self.peerconnection.peerconnection.getSenders().some(function (s) {
  6697. if (s.track && s.track.kind === senderKind) {
  6698. sender = s;
  6699. return true;
  6700. }
  6701. });
  6702. if (sender) {
  6703. // We assume that our streams have a single track, either audio
  6704. // or video.
  6705. newTrack = isAudio ? newStream.getAudioTracks()[0] :
  6706. newStream.getVideoTracks()[0];
  6707. sender.replaceTrack(newTrack)
  6708. .then(function() {
  6709. console.log("Replaced a track, isAudio=" + isAudio);
  6710. })
  6711. .catch(function(err) {
  6712. console.log("Failed to replace a track: " + err);
  6713. });
  6714. } else {
  6715. console.log("Cannot switch tracks: no RTPSender.");
  6716. }
  6717. } else {
  6718. self.peerconnection.removeStream(oldStream, true);
  6719. if (newStream) {
  6720. self.peerconnection.addStream(newStream);
  6721. }
  6722. }
  6723. }
  6724. // Conference is not active
  6725. if (!oldSdp) {
  6726. successCallback();
  6727. return;
  6728. }
  6729. self.switchstreams = true;
  6730. self.modifySourcesQueue.push(function() {
  6731. logger.log('modify sources done');
  6732. successCallback();
  6733. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6734. logger.log("SDPs", oldSdp, newSdp);
  6735. self.notifyMySSRCUpdate(oldSdp, newSdp);
  6736. });
  6737. };
  6738. /**
  6739. * Adds streams.
  6740. * @param stream new stream that will be added.
  6741. * @param success_callback callback executed after successful stream addition.
  6742. */
  6743. JingleSessionPC.prototype.addStream = function (stream, callback) {
  6744. var self = this;
  6745. // Remember SDP to figure out added/removed SSRCs
  6746. var oldSdp = null;
  6747. if(this.peerconnection) {
  6748. if(this.peerconnection.localDescription) {
  6749. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  6750. }
  6751. if(stream)
  6752. this.peerconnection.addStream(stream);
  6753. }
  6754. // Conference is not active
  6755. if(!oldSdp || !this.peerconnection) {
  6756. callback();
  6757. return;
  6758. }
  6759. this.addingStreams = true;
  6760. this.modifySourcesQueue.push(function() {
  6761. logger.log('modify sources done');
  6762. callback();
  6763. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6764. logger.log("SDPs", oldSdp, newSdp);
  6765. self.notifyMySSRCUpdate(oldSdp, newSdp);
  6766. });
  6767. }
  6768. /**
  6769. * Figures out added/removed ssrcs and send update IQs.
  6770. * @param old_sdp SDP object for old description.
  6771. * @param new_sdp SDP object for new description.
  6772. */
  6773. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  6774. if (!(this.peerconnection.signalingState == 'stable' &&
  6775. this.peerconnection.iceConnectionState == 'connected')){
  6776. logger.log("Too early to send updates");
  6777. return;
  6778. }
  6779. // send source-remove IQ.
  6780. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  6781. var remove = $iq({to: this.peerjid, type: 'set'})
  6782. .c('jingle', {
  6783. xmlns: 'urn:xmpp:jingle:1',
  6784. action: 'source-remove',
  6785. initiator: this.initiator,
  6786. sid: this.sid
  6787. }
  6788. );
  6789. var removed = sdpDiffer.toJingle(remove);
  6790. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  6791. // it in the current form
  6792. if (removed)
  6793. remove = SSRCReplacement.processSourceRemove(remove);
  6794. if (removed && remove) {
  6795. logger.info("Sending source-remove", remove);
  6796. this.connection.sendIQ(remove,
  6797. function (res) {
  6798. logger.info('got remove result', res);
  6799. },
  6800. function (err) {
  6801. logger.error('got remove error', err);
  6802. }
  6803. );
  6804. } else {
  6805. logger.log('removal not necessary');
  6806. }
  6807. // send source-add IQ.
  6808. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  6809. var add = $iq({to: this.peerjid, type: 'set'})
  6810. .c('jingle', {
  6811. xmlns: 'urn:xmpp:jingle:1',
  6812. action: 'source-add',
  6813. initiator: this.initiator,
  6814. sid: this.sid
  6815. }
  6816. );
  6817. var added = sdpDiffer.toJingle(add);
  6818. // Let 'source-add' IQ through the hack and see if we're allowed to send
  6819. // it in the current form
  6820. if (added)
  6821. add = SSRCReplacement.processSourceAdd(add);
  6822. if (added && add) {
  6823. logger.info("Sending source-add", add);
  6824. this.connection.sendIQ(add,
  6825. function (res) {
  6826. logger.info('got add result', res);
  6827. },
  6828. function (err) {
  6829. logger.error('got add error', err);
  6830. }
  6831. );
  6832. } else {
  6833. logger.log('addition not necessary');
  6834. }
  6835. };
  6836. /**
  6837. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  6838. *
  6839. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  6840. * tracks; otherwise, <tt>false</tt>
  6841. * @param callback a function to be invoked with <tt>mute</tt> after all video
  6842. * tracks have been enabled/disabled. The function may, optionally, return
  6843. * another function which is to be invoked after the whole mute/unmute operation
  6844. * has completed successfully.
  6845. * @param options an object which specifies optional arguments such as the
  6846. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  6847. * specifies whether the method was initiated in response to a user command (in
  6848. * contrast to an automatic decision made by the application logic)
  6849. */
  6850. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  6851. var byUser;
  6852. if (options) {
  6853. byUser = options.byUser;
  6854. if (typeof byUser === 'undefined') {
  6855. byUser = true;
  6856. }
  6857. } else {
  6858. byUser = true;
  6859. }
  6860. // The user's command to mute the (local) video takes precedence over any
  6861. // automatic decision made by the application logic.
  6862. if (byUser) {
  6863. this.videoMuteByUser = mute;
  6864. } else if (this.videoMuteByUser) {
  6865. return;
  6866. }
  6867. this.hardMuteVideo(mute);
  6868. var self = this;
  6869. var oldSdp = null;
  6870. if(self.peerconnection) {
  6871. if(self.peerconnection.localDescription) {
  6872. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  6873. }
  6874. }
  6875. this.modifySourcesQueue.push(function() {
  6876. logger.log('modify sources done');
  6877. callback(mute);
  6878. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6879. logger.log("SDPs", oldSdp, newSdp);
  6880. self.notifyMySSRCUpdate(oldSdp, newSdp);
  6881. });
  6882. };
  6883. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  6884. this.pendingop = muted ? 'mute' : 'unmute';
  6885. };
  6886. JingleSessionPC.prototype.sendMute = function (muted, content) {
  6887. var info = $iq({to: this.peerjid,
  6888. type: 'set'})
  6889. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6890. action: 'session-info',
  6891. initiator: this.initiator,
  6892. sid: this.sid });
  6893. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  6894. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  6895. if (content) {
  6896. info.attrs({'name': content});
  6897. }
  6898. this.connection.send(info);
  6899. };
  6900. JingleSessionPC.prototype.sendRinging = function () {
  6901. var info = $iq({to: this.peerjid,
  6902. type: 'set'})
  6903. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6904. action: 'session-info',
  6905. initiator: this.initiator,
  6906. sid: this.sid });
  6907. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  6908. this.connection.send(info);
  6909. };
  6910. JingleSessionPC.prototype.getStats = function (interval) {
  6911. var self = this;
  6912. var recv = {audio: 0, video: 0};
  6913. var lost = {audio: 0, video: 0};
  6914. var lastrecv = {audio: 0, video: 0};
  6915. var lastlost = {audio: 0, video: 0};
  6916. var loss = {audio: 0, video: 0};
  6917. var delta = {audio: 0, video: 0};
  6918. this.statsinterval = window.setInterval(function () {
  6919. if (self && self.peerconnection && self.peerconnection.getStats) {
  6920. self.peerconnection.getStats(function (stats) {
  6921. var results = stats.result();
  6922. // TODO: there are so much statistics you can get from this..
  6923. for (var i = 0; i < results.length; ++i) {
  6924. if (results[i].type == 'ssrc') {
  6925. var packetsrecv = results[i].stat('packetsReceived');
  6926. var packetslost = results[i].stat('packetsLost');
  6927. if (packetsrecv && packetslost) {
  6928. packetsrecv = parseInt(packetsrecv, 10);
  6929. packetslost = parseInt(packetslost, 10);
  6930. if (results[i].stat('googFrameRateReceived')) {
  6931. lastlost.video = lost.video;
  6932. lastrecv.video = recv.video;
  6933. recv.video = packetsrecv;
  6934. lost.video = packetslost;
  6935. } else {
  6936. lastlost.audio = lost.audio;
  6937. lastrecv.audio = recv.audio;
  6938. recv.audio = packetsrecv;
  6939. lost.audio = packetslost;
  6940. }
  6941. }
  6942. }
  6943. }
  6944. delta.audio = recv.audio - lastrecv.audio;
  6945. delta.video = recv.video - lastrecv.video;
  6946. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  6947. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  6948. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  6949. });
  6950. }
  6951. }, interval || 3000);
  6952. return this.statsinterval;
  6953. };
  6954. JingleSessionPC.onJingleError = function (session, error)
  6955. {
  6956. logger.error("Jingle error", error);
  6957. }
  6958. JingleSessionPC.onJingleFatalError = function (session, error)
  6959. {
  6960. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6961. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  6962. }
  6963. JingleSessionPC.prototype.setLocalDescription = function () {
  6964. var self = this;
  6965. var newssrcs = [];
  6966. if(!this.peerconnection.localDescription)
  6967. return;
  6968. var session = transform.parse(this.peerconnection.localDescription.sdp);
  6969. var i;
  6970. session.media.forEach(function (media) {
  6971. if (media.ssrcs && media.ssrcs.length > 0) {
  6972. // TODO(gp) maybe exclude FID streams?
  6973. media.ssrcs.forEach(function (ssrc) {
  6974. if (ssrc.attribute !== 'cname') {
  6975. return;
  6976. }
  6977. newssrcs.push({
  6978. 'ssrc': ssrc.id,
  6979. 'type': media.type
  6980. });
  6981. });
  6982. }
  6983. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  6984. {
  6985. newssrcs.push({
  6986. 'ssrc': self.localStreamsSSRC[media.type],
  6987. 'type': media.type
  6988. });
  6989. }
  6990. });
  6991. logger.log('new ssrcs', newssrcs);
  6992. // Bind us as local SSRCs owner
  6993. if (newssrcs.length > 0) {
  6994. for (i = 0; i < newssrcs.length; i++) {
  6995. var ssrc = newssrcs[i].ssrc;
  6996. var myJid = self.connection.emuc.myroomjid;
  6997. self.ssrcOwners[ssrc] = myJid;
  6998. }
  6999. }
  7000. }
  7001. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7002. JingleSessionPC.prototype.sendKeyframe = function () {
  7003. var pc = this.peerconnection;
  7004. logger.log('sendkeyframe', pc.iceConnectionState);
  7005. if (pc.iceConnectionState !== 'connected') return; // safe...
  7006. var self = this;
  7007. pc.setRemoteDescription(
  7008. pc.remoteDescription,
  7009. function () {
  7010. pc.createAnswer(
  7011. function (modifiedAnswer) {
  7012. pc.setLocalDescription(
  7013. modifiedAnswer,
  7014. function () {
  7015. // noop
  7016. },
  7017. function (error) {
  7018. logger.log('triggerKeyframe setLocalDescription failed', error);
  7019. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  7020. }
  7021. );
  7022. },
  7023. function (error) {
  7024. logger.log('triggerKeyframe createAnswer failed', error);
  7025. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  7026. }
  7027. );
  7028. },
  7029. function (error) {
  7030. logger.log('triggerKeyframe setRemoteDescription failed', error);
  7031. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  7032. }
  7033. );
  7034. }
  7035. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  7036. var self = this;
  7037. var thessrc;
  7038. var streamId = RTC.getStreamID(data.stream);
  7039. // look up an associated JID for a stream id
  7040. if (!streamId) {
  7041. logger.error("No stream ID for", data.stream);
  7042. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  7043. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  7044. var ssrclines = this.peerconnection.remoteDescription?
  7045. SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:') : [];
  7046. ssrclines = ssrclines.filter(function (line) {
  7047. // NOTE(gp) previously we filtered on the mslabel, but that property
  7048. // is not always present.
  7049. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  7050. if (RTCBrowserType.isTemasysPluginUsed()) {
  7051. return ((line.indexOf('mslabel:' + streamId) !== -1));
  7052. } else {
  7053. return ((line.indexOf('msid:' + streamId) !== -1));
  7054. }
  7055. });
  7056. if (ssrclines.length) {
  7057. thessrc = ssrclines[0].substring(7).split(' ')[0];
  7058. if (!self.ssrcOwners[thessrc]) {
  7059. logger.error("No SSRC owner known for: " + thessrc);
  7060. return;
  7061. }
  7062. data.peerjid = self.ssrcOwners[thessrc];
  7063. logger.log('associated jid', self.ssrcOwners[thessrc]);
  7064. } else {
  7065. logger.error("No SSRC lines for ", streamId);
  7066. }
  7067. }
  7068. this.room.remoteStreamAdded(data, this.sid, thessrc);
  7069. var isVideo = data.stream.getVideoTracks().length > 0;
  7070. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7071. if (isVideo &&
  7072. data.peerjid && this.peerjid === data.peerjid &&
  7073. data.stream.getVideoTracks().length === 0 &&
  7074. RTC.localVideo.getTracks().length > 0) {
  7075. window.setTimeout(function () {
  7076. self.sendKeyframe();
  7077. }, 3000);
  7078. }
  7079. }
  7080. module.exports = JingleSessionPC;
  7081. }).call(this,"/modules/xmpp/JingleSessionPC.js")
  7082. },{"../../service/xmpp/XMPPEvents":86,"../RTC/RTC":16,"../RTC/RTCBrowserType":17,"./JingleSession":27,"./LocalSSRCReplacement":29,"./SDP":30,"./SDPDiffer":31,"./SDPUtil":32,"./TraceablePeerConnection":33,"async":42,"jitsi-meet-logger":47,"sdp-transform":75}],29:[function(require,module,exports){
  7083. (function (__filename){
  7084. /* global $ */
  7085. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7086. /*
  7087. Here we do modifications of local video SSRCs. There are 2 situations we have
  7088. to handle:
  7089. 1. We generate SSRC for local recvonly video stream. This is the case when we
  7090. have no local camera and it is not generated automatically, but SSRC=1 is
  7091. used implicitly. If that happens RTCP packets will be dropped by the JVB
  7092. and we won't be able to request video key frames correctly.
  7093. 2. A hack to re-use SSRC of the first video stream for any new stream created
  7094. in future. It turned out that Chrome may keep on using the SSRC of removed
  7095. video stream in RTCP even though a new one has been created. So we just
  7096. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  7097. notifications are blocked once first video SSRC is advertised to the focus.
  7098. What this hack does:
  7099. 1. Stores the SSRC of the first video stream created by
  7100. a) scanning Jingle session-accept/session-invite for existing video SSRC
  7101. b) watching for 'source-add' for new video stream if it has not been
  7102. created in step a)
  7103. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  7104. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  7105. returned to the other parts of the application.
  7106. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  7107. blocks those notifications. This makes Jicofo and all participants think
  7108. that it exists all the time even if the video stream has been removed or
  7109. replaced locally. Thanks to that there is no additional signaling activity
  7110. on video mute or when switching to the desktop stream.
  7111. */
  7112. var SDP = require('./SDP');
  7113. var RandomUtil = require('../util/RandomUtil');
  7114. var RTCBrowserType = require('../RTC/RTCBrowserType');
  7115. /**
  7116. * The hack is enabled on all browsers except FF by default
  7117. * FIXME finish the hack once removeStream method is implemented in FF
  7118. * @type {boolean}
  7119. */
  7120. var isEnabled = !RTCBrowserType.isFirefox();
  7121. /**
  7122. * Stored SSRC of local video stream.
  7123. */
  7124. var localVideoSSRC;
  7125. /**
  7126. * SSRC, msid, mslabel, label used for recvonly video stream when we have no local camera.
  7127. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  7128. * instead of 1.
  7129. */
  7130. var localRecvOnlySSRC, localRecvOnlyMSID, localRecvOnlyMSLabel, localRecvOnlyLabel;
  7131. /**
  7132. * cname for <tt>localRecvOnlySSRC</tt>
  7133. */
  7134. var localRecvOnlyCName;
  7135. /**
  7136. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  7137. * from given Jingle IQ.
  7138. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  7139. * @param actionName display name of the action which will be printed in log
  7140. * messages.
  7141. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  7142. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  7143. * other SSRCs left to be signaled after removing it.
  7144. */
  7145. var filterOutSource = function (modifyIq, actionName) {
  7146. var modifyIqTree = $(modifyIq.tree());
  7147. if (!localVideoSSRC)
  7148. return modifyIqTree[0];
  7149. var videoSSRC = modifyIqTree.find(
  7150. '>jingle>content[name="video"]' +
  7151. '>description>source[ssrc="' + localVideoSSRC + '"]');
  7152. if (!videoSSRC.length) {
  7153. return modifyIqTree[0];
  7154. }
  7155. logger.info(
  7156. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  7157. videoSSRC.remove();
  7158. // Check if any sources still left to be added/removed
  7159. if (modifyIqTree.find('>jingle>content>description>source').length) {
  7160. return modifyIqTree[0];
  7161. } else {
  7162. return null;
  7163. }
  7164. };
  7165. /**
  7166. * Scans given Jingle IQ for video SSRC and stores it.
  7167. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  7168. */
  7169. var storeLocalVideoSSRC = function (jingleIq) {
  7170. var videoSSRCs =
  7171. $(jingleIq.tree())
  7172. .find('>jingle>content[name="video"]>description>source');
  7173. videoSSRCs.each(function (idx, ssrcElem) {
  7174. if (localVideoSSRC)
  7175. return;
  7176. // We consider SSRC real only if it has msid attribute
  7177. // recvonly streams in FF do not have it as well as local SSRCs
  7178. // we generate for recvonly streams in Chrome
  7179. var ssrSel = $(ssrcElem);
  7180. var msid = ssrSel.find('>parameter[name="msid"]');
  7181. if (msid.length) {
  7182. var ssrcVal = ssrSel.attr('ssrc');
  7183. if (ssrcVal) {
  7184. localVideoSSRC = ssrcVal;
  7185. logger.info('Stored local video SSRC' +
  7186. ' for future re-use: ' + localVideoSSRC);
  7187. }
  7188. }
  7189. });
  7190. };
  7191. /**
  7192. * Generates new label/mslabel attribute
  7193. * @returns {string} label/mslabel attribute
  7194. */
  7195. function generateLabel() {
  7196. return RandomUtil.randomHexString(8) + "-" + RandomUtil.randomHexString(4) +
  7197. "-" + RandomUtil.randomHexString(4) + "-" +
  7198. RandomUtil.randomHexString(4) + "-" + RandomUtil.randomHexString(12);
  7199. }
  7200. /**
  7201. * Generates new SSRC, CNAME, mslabel, label and msid for local video recvonly stream.
  7202. * FIXME what about eventual SSRC collision ?
  7203. */
  7204. function generateRecvonlySSRC() {
  7205. localRecvOnlySSRC =
  7206. Math.random().toString(10).substring(2, 11);
  7207. localRecvOnlyCName =
  7208. Math.random().toString(36).substring(2);
  7209. localRecvOnlyMSLabel = generateLabel();
  7210. localRecvOnlyLabel = generateLabel();
  7211. localRecvOnlyMSID = localRecvOnlyMSLabel + " " + localRecvOnlyLabel;
  7212. logger.info(
  7213. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  7214. ", cname: " + localRecvOnlyCName);
  7215. }
  7216. var LocalSSRCReplacement = {
  7217. /**
  7218. * Method must be called before 'session-initiate' or 'session-invite' is
  7219. * sent. Scans the IQ for local video SSRC and stores it if detected.
  7220. *
  7221. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  7222. * which will be scanned for local video SSRC.
  7223. */
  7224. processSessionInit: function (sessionInit) {
  7225. if (!isEnabled)
  7226. return;
  7227. if (localVideoSSRC) {
  7228. logger.error("Local SSRC stored already: " + localVideoSSRC);
  7229. return;
  7230. }
  7231. storeLocalVideoSSRC(sessionInit);
  7232. },
  7233. /**
  7234. * If we have local video SSRC stored searched given
  7235. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  7236. * with the stored one.
  7237. * @param localDescription local description object that will have local
  7238. * video SSRC replaced with the stored one
  7239. * @returns modified <tt>localDescription</tt> object.
  7240. */
  7241. mungeLocalVideoSSRC: function (localDescription) {
  7242. if (!isEnabled)
  7243. return localDescription;
  7244. if (!localDescription) {
  7245. logger.warn("localDescription is null or undefined");
  7246. return localDescription;
  7247. }
  7248. // IF we have local video SSRC stored make sure it is replaced
  7249. // with old SSRC
  7250. if (localVideoSSRC) {
  7251. var newSdp = new SDP(localDescription.sdp);
  7252. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  7253. !newSdp.containsSSRC(localVideoSSRC)) {
  7254. // Get new video SSRC
  7255. var map = newSdp.getMediaSsrcMap();
  7256. var videoPart = map[1];
  7257. var videoSSRCs = videoPart.ssrcs;
  7258. var newSSRC = Object.keys(videoSSRCs)[0];
  7259. logger.info(
  7260. "Replacing new video SSRC: " + newSSRC +
  7261. " with " + localVideoSSRC);
  7262. localDescription.sdp =
  7263. newSdp.raw.replace(
  7264. new RegExp('a=ssrc:' + newSSRC, 'g'),
  7265. 'a=ssrc:' + localVideoSSRC);
  7266. }
  7267. } else {
  7268. // Make sure we have any SSRC for recvonly video stream
  7269. var sdp = new SDP(localDescription.sdp);
  7270. if (sdp.media[1] && sdp.media[1].indexOf('a=ssrc:') === -1 &&
  7271. sdp.media[1].indexOf('a=recvonly') !== -1) {
  7272. if (!localRecvOnlySSRC) {
  7273. generateRecvonlySSRC();
  7274. }
  7275. localVideoSSRC = localRecvOnlySSRC;
  7276. logger.info('No SSRC in video recvonly stream' +
  7277. ' - adding SSRC: ' + localRecvOnlySSRC);
  7278. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  7279. ' cname:' + localRecvOnlyCName + '\r\n' +
  7280. 'a=ssrc:' + localRecvOnlySSRC +
  7281. ' msid:' + localRecvOnlyMSID + '\r\n' +
  7282. 'a=ssrc:' + localRecvOnlySSRC +
  7283. ' mslabel:' + localRecvOnlyMSLabel + '\r\n' +
  7284. 'a=ssrc:' + localRecvOnlySSRC +
  7285. ' label:' + localRecvOnlyLabel + '\r\n';
  7286. localDescription.sdp = sdp.session + sdp.media.join('');
  7287. }
  7288. }
  7289. return localDescription;
  7290. },
  7291. /**
  7292. * Method must be called before 'source-add' notification is sent. In case
  7293. * we have local video SSRC advertised already it will be removed from the
  7294. * notification. If no other SSRCs are described by given IQ null will be
  7295. * returned which means that there is no point in sending the notification.
  7296. * @param sourceAdd 'source-add' Jingle IQ to be processed
  7297. * @returns modified 'source-add' IQ which can be sent to the focus or
  7298. * <tt>null</tt> if no notification shall be sent. It is no longer
  7299. * a Strophe IQ Builder instance, but DOM element tree.
  7300. */
  7301. processSourceAdd: function (sourceAdd) {
  7302. if (!isEnabled)
  7303. return sourceAdd;
  7304. if (!localVideoSSRC) {
  7305. // Store local SSRC if available
  7306. storeLocalVideoSSRC(sourceAdd);
  7307. return sourceAdd;
  7308. } else {
  7309. return filterOutSource(sourceAdd, 'source-add');
  7310. }
  7311. },
  7312. /**
  7313. * Method must be called before 'source-remove' notification is sent.
  7314. * Removes local video SSRC from the notification. If there are no other
  7315. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  7316. * means that there is no point in sending the notification.
  7317. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  7318. * @returns modified 'source-remove' IQ which can be sent to the focus or
  7319. * <tt>null</tt> if no notification shall be sent. It is no longer
  7320. * a Strophe IQ Builder instance, but DOM element tree.
  7321. */
  7322. processSourceRemove: function (sourceRemove) {
  7323. if (!isEnabled)
  7324. return sourceRemove;
  7325. return filterOutSource(sourceRemove, 'source-remove');
  7326. },
  7327. /**
  7328. * Turns the hack on or off
  7329. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  7330. * to disable it
  7331. */
  7332. setEnabled: function (enabled) {
  7333. isEnabled = enabled;
  7334. }
  7335. };
  7336. module.exports = LocalSSRCReplacement;
  7337. }).call(this,"/modules/xmpp/LocalSSRCReplacement.js")
  7338. },{"../RTC/RTCBrowserType":17,"../util/RandomUtil":25,"./SDP":30,"jitsi-meet-logger":47}],30:[function(require,module,exports){
  7339. (function (__filename){
  7340. /* jshint -W117 */
  7341. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7342. var SDPUtil = require("./SDPUtil");
  7343. // SDP STUFF
  7344. function SDP(sdp) {
  7345. /**
  7346. * Whether or not to remove TCP ice candidates when translating from/to jingle.
  7347. * @type {boolean}
  7348. */
  7349. this.removeTcpCandidates = false;
  7350. /**
  7351. * Whether or not to remove UDP ice candidates when translating from/to jingle.
  7352. * @type {boolean}
  7353. */
  7354. this.removeUdpCandidates = false;
  7355. this.media = sdp.split('\r\nm=');
  7356. for (var i = 1; i < this.media.length; i++) {
  7357. this.media[i] = 'm=' + this.media[i];
  7358. if (i != this.media.length - 1) {
  7359. this.media[i] += '\r\n';
  7360. }
  7361. }
  7362. this.session = this.media.shift() + '\r\n';
  7363. this.raw = this.session + this.media.join('');
  7364. }
  7365. /**
  7366. * Returns map of MediaChannel mapped per channel idx.
  7367. */
  7368. SDP.prototype.getMediaSsrcMap = function() {
  7369. var self = this;
  7370. var media_ssrcs = {};
  7371. var tmp;
  7372. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  7373. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  7374. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  7375. var media = {
  7376. mediaindex: mediaindex,
  7377. mid: mid,
  7378. ssrcs: {},
  7379. ssrcGroups: []
  7380. };
  7381. media_ssrcs[mediaindex] = media;
  7382. tmp.forEach(function (line) {
  7383. var linessrc = line.substring(7).split(' ')[0];
  7384. // allocate new ChannelSsrc
  7385. if(!media.ssrcs[linessrc]) {
  7386. media.ssrcs[linessrc] = {
  7387. ssrc: linessrc,
  7388. lines: []
  7389. };
  7390. }
  7391. media.ssrcs[linessrc].lines.push(line);
  7392. });
  7393. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  7394. tmp.forEach(function(line){
  7395. var idx = line.indexOf(' ');
  7396. var semantics = line.substr(0, idx).substr(13);
  7397. var ssrcs = line.substr(14 + semantics.length).split(' ');
  7398. if (ssrcs.length) {
  7399. media.ssrcGroups.push({
  7400. semantics: semantics,
  7401. ssrcs: ssrcs
  7402. });
  7403. }
  7404. });
  7405. }
  7406. return media_ssrcs;
  7407. };
  7408. /**
  7409. * Returns <tt>true</tt> if this SDP contains given SSRC.
  7410. * @param ssrc the ssrc to check.
  7411. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  7412. */
  7413. SDP.prototype.containsSSRC = function(ssrc) {
  7414. var medias = this.getMediaSsrcMap();
  7415. Object.keys(medias).forEach(function(mediaindex){
  7416. var media = medias[mediaindex];
  7417. //logger.log("Check", channel, ssrc);
  7418. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  7419. return true;
  7420. }
  7421. });
  7422. return false;
  7423. };
  7424. // remove iSAC and CN from SDP
  7425. SDP.prototype.mangle = function () {
  7426. var i, j, mline, lines, rtpmap, newdesc;
  7427. for (i = 0; i < this.media.length; i++) {
  7428. lines = this.media[i].split('\r\n');
  7429. lines.pop(); // remove empty last element
  7430. mline = SDPUtil.parse_mline(lines.shift());
  7431. if (mline.media != 'audio')
  7432. continue;
  7433. newdesc = '';
  7434. mline.fmt.length = 0;
  7435. for (j = 0; j < lines.length; j++) {
  7436. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  7437. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  7438. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  7439. continue;
  7440. mline.fmt.push(rtpmap.id);
  7441. newdesc += lines[j] + '\r\n';
  7442. } else {
  7443. newdesc += lines[j] + '\r\n';
  7444. }
  7445. }
  7446. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  7447. this.media[i] += newdesc;
  7448. }
  7449. this.raw = this.session + this.media.join('');
  7450. };
  7451. // remove lines matching prefix from session section
  7452. SDP.prototype.removeSessionLines = function(prefix) {
  7453. var self = this;
  7454. var lines = SDPUtil.find_lines(this.session, prefix);
  7455. lines.forEach(function(line) {
  7456. self.session = self.session.replace(line + '\r\n', '');
  7457. });
  7458. this.raw = this.session + this.media.join('');
  7459. return lines;
  7460. }
  7461. // remove lines matching prefix from a media section specified by mediaindex
  7462. // TODO: non-numeric mediaindex could match mid
  7463. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  7464. var self = this;
  7465. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  7466. lines.forEach(function(line) {
  7467. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  7468. });
  7469. this.raw = this.session + this.media.join('');
  7470. return lines;
  7471. }
  7472. // add content's to a jingle element
  7473. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  7474. // logger.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  7475. var self = this;
  7476. var i, j, k, mline, ssrc, rtpmap, tmp, lines;
  7477. // new bundle plan
  7478. if (SDPUtil.find_line(this.session, 'a=group:')) {
  7479. lines = SDPUtil.find_lines(this.session, 'a=group:');
  7480. for (i = 0; i < lines.length; i++) {
  7481. tmp = lines[i].split(' ');
  7482. var semantics = tmp.shift().substr(8);
  7483. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  7484. for (j = 0; j < tmp.length; j++) {
  7485. elem.c('content', {name: tmp[j]}).up();
  7486. }
  7487. elem.up();
  7488. }
  7489. }
  7490. for (i = 0; i < this.media.length; i++) {
  7491. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  7492. if (!(mline.media === 'audio' ||
  7493. mline.media === 'video' ||
  7494. mline.media === 'application'))
  7495. {
  7496. continue;
  7497. }
  7498. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  7499. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  7500. } else {
  7501. if(ssrcs && ssrcs[mline.media]) {
  7502. ssrc = ssrcs[mline.media];
  7503. } else {
  7504. ssrc = false;
  7505. }
  7506. }
  7507. elem.c('content', {creator: thecreator, name: mline.media});
  7508. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  7509. // prefer identifier from a=mid if present
  7510. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  7511. elem.attrs({ name: mid });
  7512. }
  7513. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length) {
  7514. elem.c('description',
  7515. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  7516. media: mline.media });
  7517. if (ssrc) {
  7518. elem.attrs({ssrc: ssrc});
  7519. }
  7520. for (j = 0; j < mline.fmt.length; j++) {
  7521. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  7522. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  7523. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  7524. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  7525. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  7526. for (k = 0; k < tmp.length; k++) {
  7527. elem.c('parameter', tmp[k]).up();
  7528. }
  7529. }
  7530. this.rtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  7531. elem.up();
  7532. }
  7533. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  7534. elem.c('encryption', {required: 1});
  7535. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  7536. crypto.forEach(function(line) {
  7537. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  7538. });
  7539. elem.up(); // end of encryption
  7540. }
  7541. if (ssrc) {
  7542. // new style mapping
  7543. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7544. // FIXME: group by ssrc and support multiple different ssrcs
  7545. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  7546. if(ssrclines.length > 0) {
  7547. ssrclines.forEach(function (line) {
  7548. var idx = line.indexOf(' ');
  7549. var linessrc = line.substr(0, idx).substr(7);
  7550. if (linessrc != ssrc) {
  7551. elem.up();
  7552. ssrc = linessrc;
  7553. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7554. }
  7555. var kv = line.substr(idx + 1);
  7556. elem.c('parameter');
  7557. if (kv.indexOf(':') == -1) {
  7558. elem.attrs({ name: kv });
  7559. } else {
  7560. var k = kv.split(':', 2)[0];
  7561. elem.attrs({ name: k });
  7562. var v = kv.split(':', 2)[1];
  7563. v = SDPUtil.filter_special_chars(v);
  7564. elem.attrs({ value: v });
  7565. }
  7566. elem.up();
  7567. });
  7568. } else {
  7569. elem.up();
  7570. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7571. elem.c('parameter');
  7572. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  7573. elem.up();
  7574. var msid = null;
  7575. if(mline.media == "audio")
  7576. {
  7577. msid = APP.RTC.localAudio.getId();
  7578. }
  7579. else
  7580. {
  7581. msid = APP.RTC.localVideo.getId();
  7582. }
  7583. if(msid != null)
  7584. {
  7585. msid = SDPUtil.filter_special_chars(msid);
  7586. elem.c('parameter');
  7587. elem.attrs({name: "msid", value:msid});
  7588. elem.up();
  7589. elem.c('parameter');
  7590. elem.attrs({name: "mslabel", value:msid});
  7591. elem.up();
  7592. elem.c('parameter');
  7593. elem.attrs({name: "label", value:msid});
  7594. elem.up();
  7595. }
  7596. }
  7597. elem.up();
  7598. // XEP-0339 handle ssrc-group attributes
  7599. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  7600. ssrc_group_lines.forEach(function(line) {
  7601. var idx = line.indexOf(' ');
  7602. var semantics = line.substr(0, idx).substr(13);
  7603. var ssrcs = line.substr(14 + semantics.length).split(' ');
  7604. if (ssrcs.length) {
  7605. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7606. ssrcs.forEach(function(ssrc) {
  7607. elem.c('source', { ssrc: ssrc })
  7608. .up();
  7609. });
  7610. elem.up();
  7611. }
  7612. });
  7613. }
  7614. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  7615. elem.c('rtcp-mux').up();
  7616. }
  7617. // XEP-0293 -- map a=rtcp-fb:*
  7618. this.rtcpFbToJingle(i, elem, '*');
  7619. // XEP-0294
  7620. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  7621. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  7622. for (j = 0; j < lines.length; j++) {
  7623. tmp = SDPUtil.parse_extmap(lines[j]);
  7624. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  7625. uri: tmp.uri,
  7626. id: tmp.value });
  7627. if (tmp.hasOwnProperty('direction')) {
  7628. switch (tmp.direction) {
  7629. case 'sendonly':
  7630. elem.attrs({senders: 'responder'});
  7631. break;
  7632. case 'recvonly':
  7633. elem.attrs({senders: 'initiator'});
  7634. break;
  7635. case 'sendrecv':
  7636. elem.attrs({senders: 'both'});
  7637. break;
  7638. case 'inactive':
  7639. elem.attrs({senders: 'none'});
  7640. break;
  7641. }
  7642. }
  7643. // TODO: handle params
  7644. elem.up();
  7645. }
  7646. }
  7647. elem.up(); // end of description
  7648. }
  7649. // map ice-ufrag/pwd, dtls fingerprint, candidates
  7650. this.transportToJingle(i, elem);
  7651. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  7652. elem.attrs({senders: 'both'});
  7653. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  7654. elem.attrs({senders: 'initiator'});
  7655. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  7656. elem.attrs({senders: 'responder'});
  7657. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  7658. elem.attrs({senders: 'none'});
  7659. }
  7660. if (mline.port == '0') {
  7661. // estos hack to reject an m-line
  7662. elem.attrs({senders: 'rejected'});
  7663. }
  7664. elem.up(); // end of content
  7665. }
  7666. elem.up();
  7667. return elem;
  7668. };
  7669. SDP.prototype.transportToJingle = function (mediaindex, elem) {
  7670. var tmp, sctpmap, sctpAttrs, fingerprints;
  7671. var self = this;
  7672. elem.c('transport');
  7673. // XEP-0343 DTLS/SCTP
  7674. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  7675. {
  7676. sctpmap = SDPUtil.find_line(
  7677. this.media[mediaindex], 'a=sctpmap:', self.session);
  7678. if (sctpmap)
  7679. {
  7680. sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  7681. elem.c('sctpmap',
  7682. {
  7683. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  7684. number: sctpAttrs[0], /* SCTP port */
  7685. protocol: sctpAttrs[1] /* protocol */
  7686. });
  7687. // Optional stream count attribute
  7688. if (sctpAttrs.length > 2)
  7689. elem.attrs({ streams: sctpAttrs[2]});
  7690. elem.up();
  7691. }
  7692. }
  7693. // XEP-0320
  7694. fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  7695. fingerprints.forEach(function(line) {
  7696. tmp = SDPUtil.parse_fingerprint(line);
  7697. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  7698. elem.c('fingerprint').t(tmp.fingerprint);
  7699. delete tmp.fingerprint;
  7700. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  7701. if (line) {
  7702. tmp.setup = line.substr(8);
  7703. }
  7704. elem.attrs(tmp);
  7705. elem.up(); // end of fingerprint
  7706. });
  7707. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  7708. if (tmp) {
  7709. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  7710. elem.attrs(tmp);
  7711. // XEP-0176
  7712. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  7713. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  7714. lines.forEach(function (line) {
  7715. var candidate = SDPUtil.candidateToJingle(line);
  7716. var protocol = (candidate &&
  7717. typeof candidate.protocol === 'string')
  7718. ? candidate.protocol.toLowerCase() : '';
  7719. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  7720. (self.removeUdpCandidates && protocol === 'udp')) {
  7721. return;
  7722. }
  7723. elem.c('candidate', candidate).up();
  7724. });
  7725. }
  7726. }
  7727. elem.up(); // end of transport
  7728. }
  7729. SDP.prototype.rtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  7730. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  7731. lines.forEach(function (line) {
  7732. var tmp = SDPUtil.parse_rtcpfb(line);
  7733. if (tmp.type == 'trr-int') {
  7734. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  7735. elem.up();
  7736. } else {
  7737. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  7738. if (tmp.params.length > 0) {
  7739. elem.attrs({'subtype': tmp.params[0]});
  7740. }
  7741. elem.up();
  7742. }
  7743. });
  7744. };
  7745. SDP.prototype.rtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  7746. var media = '';
  7747. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  7748. if (tmp.length) {
  7749. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  7750. if (tmp.attr('value')) {
  7751. media += tmp.attr('value');
  7752. } else {
  7753. media += '0';
  7754. }
  7755. media += '\r\n';
  7756. }
  7757. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  7758. tmp.each(function () {
  7759. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  7760. if ($(this).attr('subtype')) {
  7761. media += ' ' + $(this).attr('subtype');
  7762. }
  7763. media += '\r\n';
  7764. });
  7765. return media;
  7766. };
  7767. // construct an SDP from a jingle stanza
  7768. SDP.prototype.fromJingle = function (jingle) {
  7769. var self = this;
  7770. this.raw = 'v=0\r\n' +
  7771. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  7772. 's=-\r\n' +
  7773. 't=0 0\r\n';
  7774. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  7775. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  7776. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  7777. var contents = $(group).find('>content').map(function (idx, content) {
  7778. return content.getAttribute('name');
  7779. }).get();
  7780. if (contents.length > 0) {
  7781. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  7782. }
  7783. });
  7784. }
  7785. this.session = this.raw;
  7786. jingle.find('>content').each(function () {
  7787. var m = self.jingle2media($(this));
  7788. self.media.push(m);
  7789. });
  7790. // reconstruct msid-semantic -- apparently not necessary
  7791. /*
  7792. var msid = SDPUtil.parse_ssrc(this.raw);
  7793. if (msid.hasOwnProperty('mslabel')) {
  7794. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  7795. }
  7796. */
  7797. this.raw = this.session + this.media.join('');
  7798. };
  7799. // translate a jingle content element into an an SDP media part
  7800. SDP.prototype.jingle2media = function (content) {
  7801. var media = '',
  7802. desc = content.find('description'),
  7803. ssrc = desc.attr('ssrc'),
  7804. self = this,
  7805. tmp;
  7806. var sctp = content.find(
  7807. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  7808. tmp = { media: desc.attr('media') };
  7809. tmp.port = '1';
  7810. if (content.attr('senders') == 'rejected') {
  7811. // estos hack to reject an m-line.
  7812. tmp.port = '0';
  7813. }
  7814. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  7815. if (sctp.length)
  7816. tmp.proto = 'DTLS/SCTP';
  7817. else
  7818. tmp.proto = 'RTP/SAVPF';
  7819. } else {
  7820. tmp.proto = 'RTP/AVPF';
  7821. }
  7822. if (!sctp.length) {
  7823. tmp.fmt = desc.find('payload-type').map(
  7824. function () { return this.getAttribute('id'); }).get();
  7825. media += SDPUtil.build_mline(tmp) + '\r\n';
  7826. } else {
  7827. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  7828. media += 'a=sctpmap:' + sctp.attr('number') +
  7829. ' ' + sctp.attr('protocol');
  7830. var streamCount = sctp.attr('streams');
  7831. if (streamCount)
  7832. media += ' ' + streamCount + '\r\n';
  7833. else
  7834. media += '\r\n';
  7835. }
  7836. media += 'c=IN IP4 0.0.0.0\r\n';
  7837. if (!sctp.length)
  7838. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  7839. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  7840. if (tmp.length) {
  7841. if (tmp.attr('ufrag')) {
  7842. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  7843. }
  7844. if (tmp.attr('pwd')) {
  7845. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  7846. }
  7847. tmp.find('>fingerprint').each(function () {
  7848. // FIXME: check namespace at some point
  7849. media += 'a=fingerprint:' + this.getAttribute('hash');
  7850. media += ' ' + $(this).text();
  7851. media += '\r\n';
  7852. if (this.getAttribute('setup')) {
  7853. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  7854. }
  7855. });
  7856. }
  7857. switch (content.attr('senders')) {
  7858. case 'initiator':
  7859. media += 'a=sendonly\r\n';
  7860. break;
  7861. case 'responder':
  7862. media += 'a=recvonly\r\n';
  7863. break;
  7864. case 'none':
  7865. media += 'a=inactive\r\n';
  7866. break;
  7867. case 'both':
  7868. media += 'a=sendrecv\r\n';
  7869. break;
  7870. }
  7871. media += 'a=mid:' + content.attr('name') + '\r\n';
  7872. // <description><rtcp-mux/></description>
  7873. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  7874. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  7875. if (desc.find('rtcp-mux').length) {
  7876. media += 'a=rtcp-mux\r\n';
  7877. }
  7878. if (desc.find('encryption').length) {
  7879. desc.find('encryption>crypto').each(function () {
  7880. media += 'a=crypto:' + this.getAttribute('tag');
  7881. media += ' ' + this.getAttribute('crypto-suite');
  7882. media += ' ' + this.getAttribute('key-params');
  7883. if (this.getAttribute('session-params')) {
  7884. media += ' ' + this.getAttribute('session-params');
  7885. }
  7886. media += '\r\n';
  7887. });
  7888. }
  7889. desc.find('payload-type').each(function () {
  7890. media += SDPUtil.build_rtpmap(this) + '\r\n';
  7891. if ($(this).find('>parameter').length) {
  7892. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  7893. media += $(this).find('parameter').map(function () {
  7894. return (this.getAttribute('name')
  7895. ? (this.getAttribute('name') + '=') : '') +
  7896. this.getAttribute('value');
  7897. }).get().join('; ');
  7898. media += '\r\n';
  7899. }
  7900. // xep-0293
  7901. media += self.rtcpFbFromJingle($(this), this.getAttribute('id'));
  7902. });
  7903. // xep-0293
  7904. media += self.rtcpFbFromJingle(desc, '*');
  7905. // xep-0294
  7906. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  7907. tmp.each(function () {
  7908. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  7909. });
  7910. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  7911. var protocol = this.getAttribute('protocol');
  7912. protocol = (typeof protocol === 'string') ? protocol.toLowerCase(): '';
  7913. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  7914. (self.removeUdpCandidates && protocol === 'udp')) {
  7915. return;
  7916. }
  7917. media += SDPUtil.candidateFromJingle(this);
  7918. });
  7919. // XEP-0339 handle ssrc-group attributes
  7920. content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  7921. var semantics = this.getAttribute('semantics');
  7922. var ssrcs = $(this).find('>source').map(function() {
  7923. return this.getAttribute('ssrc');
  7924. }).get();
  7925. if (ssrcs.length) {
  7926. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  7927. }
  7928. });
  7929. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  7930. tmp.each(function () {
  7931. var ssrc = this.getAttribute('ssrc');
  7932. $(this).find('>parameter').each(function () {
  7933. var name = this.getAttribute('name');
  7934. var value = this.getAttribute('value');
  7935. value = SDPUtil.filter_special_chars(value);
  7936. media += 'a=ssrc:' + ssrc + ' ' + name;
  7937. if (value && value.length)
  7938. media += ':' + value;
  7939. media += '\r\n';
  7940. });
  7941. });
  7942. return media;
  7943. };
  7944. module.exports = SDP;
  7945. }).call(this,"/modules/xmpp/SDP.js")
  7946. },{"./SDPUtil":32,"jitsi-meet-logger":47}],31:[function(require,module,exports){
  7947. var SDPUtil = require("./SDPUtil");
  7948. function SDPDiffer(mySDP, otherSDP)
  7949. {
  7950. this.mySDP = mySDP;
  7951. this.otherSDP = otherSDP;
  7952. }
  7953. /**
  7954. * Returns map of MediaChannel that contains media contained in
  7955. * 'mySDP', but not contained in 'otherSdp'. Mapped by channel idx.
  7956. */
  7957. SDPDiffer.prototype.getNewMedia = function() {
  7958. // this could be useful in Array.prototype.
  7959. function arrayEquals(array) {
  7960. // if the other array is a falsy value, return
  7961. if (!array)
  7962. return false;
  7963. // compare lengths - can save a lot of time
  7964. if (this.length != array.length)
  7965. return false;
  7966. for (var i = 0, l=this.length; i < l; i++) {
  7967. // Check if we have nested arrays
  7968. if (this[i] instanceof Array && array[i] instanceof Array) {
  7969. // recurse into the nested arrays
  7970. if (!this[i].equals(array[i]))
  7971. return false;
  7972. }
  7973. else if (this[i] != array[i]) {
  7974. // Warning - two different object instances will never be
  7975. // equal: {x:20} != {x:20}
  7976. return false;
  7977. }
  7978. }
  7979. return true;
  7980. }
  7981. var myMedias = this.mySDP.getMediaSsrcMap();
  7982. var othersMedias = this.otherSDP.getMediaSsrcMap();
  7983. var newMedia = {};
  7984. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  7985. var myMedia = myMedias[othersMediaIdx];
  7986. var othersMedia = othersMedias[othersMediaIdx];
  7987. if(!myMedia && othersMedia) {
  7988. // Add whole channel
  7989. newMedia[othersMediaIdx] = othersMedia;
  7990. return;
  7991. }
  7992. // Look for new ssrcs across the channel
  7993. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  7994. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  7995. // Allocate channel if we've found ssrc that doesn't exist in
  7996. // our channel
  7997. if(!newMedia[othersMediaIdx]){
  7998. newMedia[othersMediaIdx] = {
  7999. mediaindex: othersMedia.mediaindex,
  8000. mid: othersMedia.mid,
  8001. ssrcs: {},
  8002. ssrcGroups: []
  8003. };
  8004. }
  8005. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  8006. }
  8007. });
  8008. // Look for new ssrc groups across the channels
  8009. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  8010. // try to match the other ssrc-group with an ssrc-group of ours
  8011. var matched = false;
  8012. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  8013. var mySsrcGroup = myMedia.ssrcGroups[i];
  8014. if (otherSsrcGroup.semantics == mySsrcGroup.semantics &&
  8015. arrayEquals.apply(otherSsrcGroup.ssrcs,
  8016. [mySsrcGroup.ssrcs])) {
  8017. matched = true;
  8018. break;
  8019. }
  8020. }
  8021. if (!matched) {
  8022. // Allocate channel if we've found an ssrc-group that doesn't
  8023. // exist in our channel
  8024. if(!newMedia[othersMediaIdx]){
  8025. newMedia[othersMediaIdx] = {
  8026. mediaindex: othersMedia.mediaindex,
  8027. mid: othersMedia.mid,
  8028. ssrcs: {},
  8029. ssrcGroups: []
  8030. };
  8031. }
  8032. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  8033. }
  8034. });
  8035. });
  8036. return newMedia;
  8037. };
  8038. /**
  8039. * TODO: document!
  8040. */
  8041. SDPDiffer.prototype.toJingle = function(modify) {
  8042. var sdpMediaSsrcs = this.getNewMedia();
  8043. var modified = false;
  8044. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  8045. modified = true;
  8046. var media = sdpMediaSsrcs[mediaindex];
  8047. modify.c('content', {name: media.mid});
  8048. modify.c('description',
  8049. {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  8050. // FIXME: not completely sure this operates on blocks and / or handles
  8051. // different ssrcs correctly
  8052. // generate sources from lines
  8053. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  8054. var mediaSsrc = media.ssrcs[ssrcNum];
  8055. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8056. modify.attrs({ssrc: mediaSsrc.ssrc});
  8057. // iterate over ssrc lines
  8058. mediaSsrc.lines.forEach(function (line) {
  8059. var idx = line.indexOf(' ');
  8060. var kv = line.substr(idx + 1);
  8061. modify.c('parameter');
  8062. if (kv.indexOf(':') == -1) {
  8063. modify.attrs({ name: kv });
  8064. } else {
  8065. var nv = kv.split(':', 2);
  8066. var name = nv[0];
  8067. var value = SDPUtil.filter_special_chars(nv[1]);
  8068. modify.attrs({ name: name });
  8069. modify.attrs({ value: value });
  8070. }
  8071. modify.up(); // end of parameter
  8072. });
  8073. modify.up(); // end of source
  8074. });
  8075. // generate source groups from lines
  8076. media.ssrcGroups.forEach(function(ssrcGroup) {
  8077. if (ssrcGroup.ssrcs.length) {
  8078. modify.c('ssrc-group', {
  8079. semantics: ssrcGroup.semantics,
  8080. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  8081. });
  8082. ssrcGroup.ssrcs.forEach(function (ssrc) {
  8083. modify.c('source', { ssrc: ssrc })
  8084. .up(); // end of source
  8085. });
  8086. modify.up(); // end of ssrc-group
  8087. }
  8088. });
  8089. modify.up(); // end of description
  8090. modify.up(); // end of content
  8091. });
  8092. return modified;
  8093. };
  8094. module.exports = SDPDiffer;
  8095. },{"./SDPUtil":32}],32:[function(require,module,exports){
  8096. (function (__filename){
  8097. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8098. var RTCBrowserType = require("../RTC/RTCBrowserType");
  8099. SDPUtil = {
  8100. filter_special_chars: function (text) {
  8101. return text.replace(/[\\\/\{,\}\+]/g, "");
  8102. },
  8103. iceparams: function (mediadesc, sessiondesc) {
  8104. var data = null;
  8105. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  8106. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  8107. data = {
  8108. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  8109. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  8110. };
  8111. }
  8112. return data;
  8113. },
  8114. parse_iceufrag: function (line) {
  8115. return line.substring(12);
  8116. },
  8117. build_iceufrag: function (frag) {
  8118. return 'a=ice-ufrag:' + frag;
  8119. },
  8120. parse_icepwd: function (line) {
  8121. return line.substring(10);
  8122. },
  8123. build_icepwd: function (pwd) {
  8124. return 'a=ice-pwd:' + pwd;
  8125. },
  8126. parse_mid: function (line) {
  8127. return line.substring(6);
  8128. },
  8129. parse_mline: function (line) {
  8130. var parts = line.substring(2).split(' '),
  8131. data = {};
  8132. data.media = parts.shift();
  8133. data.port = parts.shift();
  8134. data.proto = parts.shift();
  8135. if (parts[parts.length - 1] === '') { // trailing whitespace
  8136. parts.pop();
  8137. }
  8138. data.fmt = parts;
  8139. return data;
  8140. },
  8141. build_mline: function (mline) {
  8142. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  8143. },
  8144. parse_rtpmap: function (line) {
  8145. var parts = line.substring(9).split(' '),
  8146. data = {};
  8147. data.id = parts.shift();
  8148. parts = parts[0].split('/');
  8149. data.name = parts.shift();
  8150. data.clockrate = parts.shift();
  8151. data.channels = parts.length ? parts.shift() : '1';
  8152. return data;
  8153. },
  8154. /**
  8155. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  8156. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  8157. * @returns [SCTP port number, protocol, streams]
  8158. */
  8159. parse_sctpmap: function (line)
  8160. {
  8161. var parts = line.substring(10).split(' ');
  8162. var sctpPort = parts[0];
  8163. var protocol = parts[1];
  8164. // Stream count is optional
  8165. var streamCount = parts.length > 2 ? parts[2] : null;
  8166. return [sctpPort, protocol, streamCount];// SCTP port
  8167. },
  8168. build_rtpmap: function (el) {
  8169. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  8170. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  8171. line += '/' + el.getAttribute('channels');
  8172. }
  8173. return line;
  8174. },
  8175. parse_crypto: function (line) {
  8176. var parts = line.substring(9).split(' '),
  8177. data = {};
  8178. data.tag = parts.shift();
  8179. data['crypto-suite'] = parts.shift();
  8180. data['key-params'] = parts.shift();
  8181. if (parts.length) {
  8182. data['session-params'] = parts.join(' ');
  8183. }
  8184. return data;
  8185. },
  8186. parse_fingerprint: function (line) { // RFC 4572
  8187. var parts = line.substring(14).split(' '),
  8188. data = {};
  8189. data.hash = parts.shift();
  8190. data.fingerprint = parts.shift();
  8191. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  8192. return data;
  8193. },
  8194. parse_fmtp: function (line) {
  8195. var parts = line.split(' '),
  8196. i, key, value,
  8197. data = [];
  8198. parts.shift();
  8199. parts = parts.join(' ').split(';');
  8200. for (i = 0; i < parts.length; i++) {
  8201. key = parts[i].split('=')[0];
  8202. while (key.length && key[0] == ' ') {
  8203. key = key.substring(1);
  8204. }
  8205. value = parts[i].split('=')[1];
  8206. if (key && value) {
  8207. data.push({name: key, value: value});
  8208. } else if (key) {
  8209. // rfc 4733 (DTMF) style stuff
  8210. data.push({name: '', value: key});
  8211. }
  8212. }
  8213. return data;
  8214. },
  8215. parse_icecandidate: function (line) {
  8216. var candidate = {},
  8217. elems = line.split(' ');
  8218. candidate.foundation = elems[0].substring(12);
  8219. candidate.component = elems[1];
  8220. candidate.protocol = elems[2].toLowerCase();
  8221. candidate.priority = elems[3];
  8222. candidate.ip = elems[4];
  8223. candidate.port = elems[5];
  8224. // elems[6] => "typ"
  8225. candidate.type = elems[7];
  8226. candidate.generation = 0; // default value, may be overwritten below
  8227. for (var i = 8; i < elems.length; i += 2) {
  8228. switch (elems[i]) {
  8229. case 'raddr':
  8230. candidate['rel-addr'] = elems[i + 1];
  8231. break;
  8232. case 'rport':
  8233. candidate['rel-port'] = elems[i + 1];
  8234. break;
  8235. case 'generation':
  8236. candidate.generation = elems[i + 1];
  8237. break;
  8238. case 'tcptype':
  8239. candidate.tcptype = elems[i + 1];
  8240. break;
  8241. default: // TODO
  8242. logger.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  8243. }
  8244. }
  8245. candidate.network = '1';
  8246. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  8247. return candidate;
  8248. },
  8249. build_icecandidate: function (cand) {
  8250. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  8251. line += ' ';
  8252. switch (cand.type) {
  8253. case 'srflx':
  8254. case 'prflx':
  8255. case 'relay':
  8256. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  8257. line += 'raddr';
  8258. line += ' ';
  8259. line += cand['rel-addr'];
  8260. line += ' ';
  8261. line += 'rport';
  8262. line += ' ';
  8263. line += cand['rel-port'];
  8264. line += ' ';
  8265. }
  8266. break;
  8267. }
  8268. if (cand.hasOwnAttribute('tcptype')) {
  8269. line += 'tcptype';
  8270. line += ' ';
  8271. line += cand.tcptype;
  8272. line += ' ';
  8273. }
  8274. line += 'generation';
  8275. line += ' ';
  8276. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  8277. return line;
  8278. },
  8279. parse_ssrc: function (desc) {
  8280. // proprietary mapping of a=ssrc lines
  8281. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  8282. // and parse according to that
  8283. var lines = desc.split('\r\n'),
  8284. data = {};
  8285. for (var i = 0; i < lines.length; i++) {
  8286. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  8287. var idx = lines[i].indexOf(' ');
  8288. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  8289. }
  8290. }
  8291. return data;
  8292. },
  8293. parse_rtcpfb: function (line) {
  8294. var parts = line.substr(10).split(' ');
  8295. var data = {};
  8296. data.pt = parts.shift();
  8297. data.type = parts.shift();
  8298. data.params = parts;
  8299. return data;
  8300. },
  8301. parse_extmap: function (line) {
  8302. var parts = line.substr(9).split(' ');
  8303. var data = {};
  8304. data.value = parts.shift();
  8305. if (data.value.indexOf('/') != -1) {
  8306. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  8307. data.value = data.value.substr(0, data.value.indexOf('/'));
  8308. } else {
  8309. data.direction = 'both';
  8310. }
  8311. data.uri = parts.shift();
  8312. data.params = parts;
  8313. return data;
  8314. },
  8315. find_line: function (haystack, needle, sessionpart) {
  8316. var lines = haystack.split('\r\n');
  8317. for (var i = 0; i < lines.length; i++) {
  8318. if (lines[i].substring(0, needle.length) == needle) {
  8319. return lines[i];
  8320. }
  8321. }
  8322. if (!sessionpart) {
  8323. return false;
  8324. }
  8325. // search session part
  8326. lines = sessionpart.split('\r\n');
  8327. for (var j = 0; j < lines.length; j++) {
  8328. if (lines[j].substring(0, needle.length) == needle) {
  8329. return lines[j];
  8330. }
  8331. }
  8332. return false;
  8333. },
  8334. find_lines: function (haystack, needle, sessionpart) {
  8335. var lines = haystack.split('\r\n'),
  8336. needles = [];
  8337. for (var i = 0; i < lines.length; i++) {
  8338. if (lines[i].substring(0, needle.length) == needle)
  8339. needles.push(lines[i]);
  8340. }
  8341. if (needles.length || !sessionpart) {
  8342. return needles;
  8343. }
  8344. // search session part
  8345. lines = sessionpart.split('\r\n');
  8346. for (var j = 0; j < lines.length; j++) {
  8347. if (lines[j].substring(0, needle.length) == needle) {
  8348. needles.push(lines[j]);
  8349. }
  8350. }
  8351. return needles;
  8352. },
  8353. candidateToJingle: function (line) {
  8354. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  8355. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  8356. if (line.indexOf('candidate:') === 0) {
  8357. line = 'a=' + line;
  8358. } else if (line.substring(0, 12) != 'a=candidate:') {
  8359. logger.log('parseCandidate called with a line that is not a candidate line');
  8360. logger.log(line);
  8361. return null;
  8362. }
  8363. if (line.substring(line.length - 2) == '\r\n') // chomp it
  8364. line = line.substring(0, line.length - 2);
  8365. var candidate = {},
  8366. elems = line.split(' '),
  8367. i;
  8368. if (elems[6] != 'typ') {
  8369. logger.log('did not find typ in the right place');
  8370. logger.log(line);
  8371. return null;
  8372. }
  8373. candidate.foundation = elems[0].substring(12);
  8374. candidate.component = elems[1];
  8375. candidate.protocol = elems[2].toLowerCase();
  8376. candidate.priority = elems[3];
  8377. candidate.ip = elems[4];
  8378. candidate.port = elems[5];
  8379. // elems[6] => "typ"
  8380. candidate.type = elems[7];
  8381. candidate.generation = '0'; // default, may be overwritten below
  8382. for (i = 8; i < elems.length; i += 2) {
  8383. switch (elems[i]) {
  8384. case 'raddr':
  8385. candidate['rel-addr'] = elems[i + 1];
  8386. break;
  8387. case 'rport':
  8388. candidate['rel-port'] = elems[i + 1];
  8389. break;
  8390. case 'generation':
  8391. candidate.generation = elems[i + 1];
  8392. break;
  8393. case 'tcptype':
  8394. candidate.tcptype = elems[i + 1];
  8395. break;
  8396. default: // TODO
  8397. logger.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  8398. }
  8399. }
  8400. candidate.network = '1';
  8401. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  8402. return candidate;
  8403. },
  8404. candidateFromJingle: function (cand) {
  8405. var line = 'a=candidate:';
  8406. line += cand.getAttribute('foundation');
  8407. line += ' ';
  8408. line += cand.getAttribute('component');
  8409. line += ' ';
  8410. var protocol = cand.getAttribute('protocol');
  8411. // use tcp candidates for FF
  8412. if (RTCBrowserType.isFirefox() && protocol.toLowerCase() == 'ssltcp') {
  8413. protocol = 'tcp';
  8414. }
  8415. line += protocol; //.toUpperCase(); // chrome M23 doesn't like this
  8416. line += ' ';
  8417. line += cand.getAttribute('priority');
  8418. line += ' ';
  8419. line += cand.getAttribute('ip');
  8420. line += ' ';
  8421. line += cand.getAttribute('port');
  8422. line += ' ';
  8423. line += 'typ';
  8424. line += ' ' + cand.getAttribute('type');
  8425. line += ' ';
  8426. switch (cand.getAttribute('type')) {
  8427. case 'srflx':
  8428. case 'prflx':
  8429. case 'relay':
  8430. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  8431. line += 'raddr';
  8432. line += ' ';
  8433. line += cand.getAttribute('rel-addr');
  8434. line += ' ';
  8435. line += 'rport';
  8436. line += ' ';
  8437. line += cand.getAttribute('rel-port');
  8438. line += ' ';
  8439. }
  8440. break;
  8441. }
  8442. if (protocol.toLowerCase() == 'tcp') {
  8443. line += 'tcptype';
  8444. line += ' ';
  8445. line += cand.getAttribute('tcptype');
  8446. line += ' ';
  8447. }
  8448. line += 'generation';
  8449. line += ' ';
  8450. line += cand.getAttribute('generation') || '0';
  8451. return line + '\r\n';
  8452. }
  8453. };
  8454. module.exports = SDPUtil;
  8455. }).call(this,"/modules/xmpp/SDPUtil.js")
  8456. },{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":47}],33:[function(require,module,exports){
  8457. (function (__filename){
  8458. /* global $ */
  8459. var RTC = require('../RTC/RTC');
  8460. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8461. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  8462. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8463. var SSRCReplacement = require("./LocalSSRCReplacement");
  8464. function TraceablePeerConnection(ice_config, constraints, session) {
  8465. var self = this;
  8466. this.session = session;
  8467. var RTCPeerConnectionType = null;
  8468. if (RTCBrowserType.isFirefox()) {
  8469. RTCPeerConnectionType = mozRTCPeerConnection;
  8470. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  8471. RTCPeerConnectionType = RTCPeerConnection;
  8472. } else {
  8473. RTCPeerConnectionType = webkitRTCPeerConnection;
  8474. }
  8475. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  8476. this.updateLog = [];
  8477. this.stats = {};
  8478. this.statsinterval = null;
  8479. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  8480. var Interop = require('sdp-interop').Interop;
  8481. this.interop = new Interop();
  8482. var Simulcast = require('sdp-simulcast');
  8483. this.simulcast = new Simulcast({numOfLayers: 2, explodeRemoteSimulcast: false});
  8484. // override as desired
  8485. this.trace = function (what, info) {
  8486. /*logger.warn('WTRACE', what, info);
  8487. if (info && RTCBrowserType.isIExplorer()) {
  8488. if (info.length > 1024) {
  8489. logger.warn('WTRACE', what, info.substr(1024));
  8490. }
  8491. if (info.length > 2048) {
  8492. logger.warn('WTRACE', what, info.substr(2048));
  8493. }
  8494. }*/
  8495. self.updateLog.push({
  8496. time: new Date(),
  8497. type: what,
  8498. value: info || ""
  8499. });
  8500. };
  8501. this.onicecandidate = null;
  8502. this.peerconnection.onicecandidate = function (event) {
  8503. // FIXME: this causes stack overflow with Temasys Plugin
  8504. if (!RTCBrowserType.isTemasysPluginUsed())
  8505. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  8506. if (self.onicecandidate !== null) {
  8507. self.onicecandidate(event);
  8508. }
  8509. };
  8510. this.onaddstream = null;
  8511. this.peerconnection.onaddstream = function (event) {
  8512. self.trace('onaddstream', event.stream.id);
  8513. if (self.onaddstream !== null) {
  8514. self.onaddstream(event);
  8515. }
  8516. };
  8517. this.onremovestream = null;
  8518. this.peerconnection.onremovestream = function (event) {
  8519. self.trace('onremovestream', event.stream.id);
  8520. if (self.onremovestream !== null) {
  8521. self.onremovestream(event);
  8522. }
  8523. };
  8524. this.onsignalingstatechange = null;
  8525. this.peerconnection.onsignalingstatechange = function (event) {
  8526. self.trace('onsignalingstatechange', self.signalingState);
  8527. if (self.onsignalingstatechange !== null) {
  8528. self.onsignalingstatechange(event);
  8529. }
  8530. };
  8531. this.oniceconnectionstatechange = null;
  8532. this.peerconnection.oniceconnectionstatechange = function (event) {
  8533. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  8534. if (self.oniceconnectionstatechange !== null) {
  8535. self.oniceconnectionstatechange(event);
  8536. }
  8537. };
  8538. this.onnegotiationneeded = null;
  8539. this.peerconnection.onnegotiationneeded = function (event) {
  8540. self.trace('onnegotiationneeded');
  8541. if (self.onnegotiationneeded !== null) {
  8542. self.onnegotiationneeded(event);
  8543. }
  8544. };
  8545. self.ondatachannel = null;
  8546. this.peerconnection.ondatachannel = function (event) {
  8547. self.trace('ondatachannel', event);
  8548. if (self.ondatachannel !== null) {
  8549. self.ondatachannel(event);
  8550. }
  8551. };
  8552. // XXX: do all non-firefox browsers which we support also support this?
  8553. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  8554. this.statsinterval = window.setInterval(function() {
  8555. self.peerconnection.getStats(function(stats) {
  8556. var results = stats.result();
  8557. var now = new Date();
  8558. for (var i = 0; i < results.length; ++i) {
  8559. results[i].names().forEach(function (name) {
  8560. var id = results[i].id + '-' + name;
  8561. if (!self.stats[id]) {
  8562. self.stats[id] = {
  8563. startTime: now,
  8564. endTime: now,
  8565. values: [],
  8566. times: []
  8567. };
  8568. }
  8569. self.stats[id].values.push(results[i].stat(name));
  8570. self.stats[id].times.push(now.getTime());
  8571. if (self.stats[id].values.length > self.maxstats) {
  8572. self.stats[id].values.shift();
  8573. self.stats[id].times.shift();
  8574. }
  8575. self.stats[id].endTime = now;
  8576. });
  8577. }
  8578. });
  8579. }, 1000);
  8580. }
  8581. }
  8582. /**
  8583. * Returns a string representation of a SessionDescription object.
  8584. */
  8585. var dumpSDP = function(description) {
  8586. if (typeof description === 'undefined' || description == null) {
  8587. return '';
  8588. }
  8589. return 'type: ' + description.type + '\r\n' + description.sdp;
  8590. };
  8591. /**
  8592. * Takes a SessionDescription object and returns a "normalized" version.
  8593. * Currently it only takes care of ordering the a=ssrc lines.
  8594. */
  8595. var normalizePlanB = function(desc) {
  8596. if (typeof desc !== 'object' || desc === null ||
  8597. typeof desc.sdp !== 'string') {
  8598. logger.warn('An empty description was passed as an argument.');
  8599. return desc;
  8600. }
  8601. var transform = require('sdp-transform');
  8602. var session = transform.parse(desc.sdp);
  8603. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  8604. Array.isArray(session.media)) {
  8605. session.media.forEach(function (mLine) {
  8606. // Chrome appears to be picky about the order in which a=ssrc lines
  8607. // are listed in an m-line when rtx is enabled (and thus there are
  8608. // a=ssrc-group lines with FID semantics). Specifically if we have
  8609. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  8610. // the "a=ssrc:S1" lines, SRD fails.
  8611. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  8612. // first.
  8613. var firstSsrcs = [];
  8614. var newSsrcLines = [];
  8615. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  8616. mLine.ssrcGroups.forEach(function (group) {
  8617. if (typeof group.semantics !== 'undefined' &&
  8618. group.semantics === 'FID') {
  8619. if (typeof group.ssrcs !== 'undefined') {
  8620. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  8621. }
  8622. }
  8623. });
  8624. }
  8625. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  8626. var i;
  8627. for (i = 0; i<mLine.ssrcs.length; i++){
  8628. if (typeof mLine.ssrcs[i] === 'object'
  8629. && typeof mLine.ssrcs[i].id !== 'undefined'
  8630. && !$.inArray(mLine.ssrcs[i].id, firstSsrcs)) {
  8631. newSsrcLines.push(mLine.ssrcs[i]);
  8632. delete mLine.ssrcs[i];
  8633. }
  8634. }
  8635. for (i = 0; i<mLine.ssrcs.length; i++){
  8636. if (typeof mLine.ssrcs[i] !== 'undefined') {
  8637. newSsrcLines.push(mLine.ssrcs[i]);
  8638. }
  8639. }
  8640. mLine.ssrcs = newSsrcLines;
  8641. }
  8642. });
  8643. }
  8644. var resStr = transform.write(session);
  8645. return new RTCSessionDescription({
  8646. type: desc.type,
  8647. sdp: resStr
  8648. });
  8649. };
  8650. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  8651. TraceablePeerConnection.prototype.__defineGetter__(
  8652. 'signalingState',
  8653. function() { return this.peerconnection.signalingState; });
  8654. TraceablePeerConnection.prototype.__defineGetter__(
  8655. 'iceConnectionState',
  8656. function() { return this.peerconnection.iceConnectionState; });
  8657. TraceablePeerConnection.prototype.__defineGetter__(
  8658. 'localDescription',
  8659. function() {
  8660. var desc = this.peerconnection.localDescription;
  8661. // FIXME this should probably be after the Unified Plan -> Plan B
  8662. // transformation.
  8663. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  8664. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  8665. // if we're running on FF, transform to Plan B first.
  8666. if (RTCBrowserType.usesUnifiedPlan()) {
  8667. desc = this.interop.toPlanB(desc);
  8668. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  8669. }
  8670. return desc;
  8671. });
  8672. TraceablePeerConnection.prototype.__defineGetter__(
  8673. 'remoteDescription',
  8674. function() {
  8675. var desc = this.peerconnection.remoteDescription;
  8676. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  8677. // if we're running on FF, transform to Plan B first.
  8678. if (RTCBrowserType.usesUnifiedPlan()) {
  8679. desc = this.interop.toPlanB(desc);
  8680. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  8681. }
  8682. return desc;
  8683. });
  8684. }
  8685. TraceablePeerConnection.prototype.addStream = function (stream) {
  8686. this.trace('addStream', stream.id);
  8687. try
  8688. {
  8689. this.peerconnection.addStream(stream);
  8690. }
  8691. catch (e)
  8692. {
  8693. logger.error(e);
  8694. }
  8695. };
  8696. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  8697. this.trace('removeStream', stream.id);
  8698. if(stopStreams) {
  8699. RTC.stopMediaStream(stream);
  8700. }
  8701. try {
  8702. // FF doesn't support this yet.
  8703. if (this.peerconnection.removeStream)
  8704. this.peerconnection.removeStream(stream);
  8705. } catch (e) {
  8706. logger.error(e);
  8707. }
  8708. };
  8709. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  8710. this.trace('createDataChannel', label, opts);
  8711. return this.peerconnection.createDataChannel(label, opts);
  8712. };
  8713. TraceablePeerConnection.prototype.setLocalDescription
  8714. = function (description, successCallback, failureCallback) {
  8715. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  8716. // if we're running on FF, transform to Plan A first.
  8717. if (RTCBrowserType.usesUnifiedPlan()) {
  8718. description = this.interop.toUnifiedPlan(description);
  8719. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  8720. }
  8721. var self = this;
  8722. this.peerconnection.setLocalDescription(description,
  8723. function () {
  8724. self.trace('setLocalDescriptionOnSuccess');
  8725. successCallback();
  8726. },
  8727. function (err) {
  8728. self.trace('setLocalDescriptionOnFailure', err);
  8729. failureCallback(err);
  8730. }
  8731. );
  8732. /*
  8733. if (this.statsinterval === null && this.maxstats > 0) {
  8734. // start gathering stats
  8735. }
  8736. */
  8737. };
  8738. TraceablePeerConnection.prototype.setRemoteDescription
  8739. = function (description, successCallback, failureCallback) {
  8740. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  8741. // TODO the focus should squeze or explode the remote simulcast
  8742. description = this.simulcast.mungeRemoteDescription(description);
  8743. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  8744. // if we're running on FF, transform to Plan A first.
  8745. if (RTCBrowserType.usesUnifiedPlan()) {
  8746. description = this.interop.toUnifiedPlan(description);
  8747. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  8748. }
  8749. if (RTCBrowserType.usesPlanB()) {
  8750. description = normalizePlanB(description);
  8751. }
  8752. var self = this;
  8753. this.peerconnection.setRemoteDescription(description,
  8754. function () {
  8755. self.trace('setRemoteDescriptionOnSuccess');
  8756. successCallback();
  8757. },
  8758. function (err) {
  8759. self.trace('setRemoteDescriptionOnFailure', err);
  8760. failureCallback(err);
  8761. }
  8762. );
  8763. /*
  8764. if (this.statsinterval === null && this.maxstats > 0) {
  8765. // start gathering stats
  8766. }
  8767. */
  8768. };
  8769. TraceablePeerConnection.prototype.close = function () {
  8770. this.trace('stop');
  8771. if (this.statsinterval !== null) {
  8772. window.clearInterval(this.statsinterval);
  8773. this.statsinterval = null;
  8774. }
  8775. this.peerconnection.close();
  8776. };
  8777. TraceablePeerConnection.prototype.createOffer
  8778. = function (successCallback, failureCallback, constraints) {
  8779. var self = this;
  8780. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  8781. this.peerconnection.createOffer(
  8782. function (offer) {
  8783. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  8784. // NOTE this is not tested because in meet the focus generates the
  8785. // offer.
  8786. // if we're running on FF, transform to Plan B first.
  8787. if (RTCBrowserType.usesUnifiedPlan()) {
  8788. offer = self.interop.toPlanB(offer);
  8789. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  8790. }
  8791. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  8792. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  8793. offer = self.simulcast.mungeLocalDescription(offer);
  8794. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  8795. }
  8796. successCallback(offer);
  8797. },
  8798. function(err) {
  8799. self.trace('createOfferOnFailure', err);
  8800. failureCallback(err);
  8801. },
  8802. constraints
  8803. );
  8804. };
  8805. TraceablePeerConnection.prototype.createAnswer
  8806. = function (successCallback, failureCallback, constraints) {
  8807. var self = this;
  8808. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  8809. this.peerconnection.createAnswer(
  8810. function (answer) {
  8811. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  8812. // if we're running on FF, transform to Plan A first.
  8813. if (RTCBrowserType.usesUnifiedPlan()) {
  8814. answer = self.interop.toPlanB(answer);
  8815. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  8816. }
  8817. // munge local video SSRC
  8818. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  8819. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  8820. answer = self.simulcast.mungeLocalDescription(answer);
  8821. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  8822. }
  8823. successCallback(answer);
  8824. },
  8825. function(err) {
  8826. self.trace('createAnswerOnFailure', err);
  8827. failureCallback(err);
  8828. },
  8829. constraints
  8830. );
  8831. };
  8832. TraceablePeerConnection.prototype.addIceCandidate
  8833. = function (candidate, successCallback, failureCallback) {
  8834. //var self = this;
  8835. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  8836. this.peerconnection.addIceCandidate(candidate);
  8837. /* maybe later
  8838. this.peerconnection.addIceCandidate(candidate,
  8839. function () {
  8840. self.trace('addIceCandidateOnSuccess');
  8841. successCallback();
  8842. },
  8843. function (err) {
  8844. self.trace('addIceCandidateOnFailure', err);
  8845. failureCallback(err);
  8846. }
  8847. );
  8848. */
  8849. };
  8850. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  8851. // TODO: Is this the correct way to handle Opera, Temasys?
  8852. if (RTCBrowserType.isFirefox()) {
  8853. // ignore for now...
  8854. if(!errback)
  8855. errback = function () {};
  8856. this.peerconnection.getStats(null, callback, errback);
  8857. } else {
  8858. this.peerconnection.getStats(callback);
  8859. }
  8860. };
  8861. module.exports = TraceablePeerConnection;
  8862. }).call(this,"/modules/xmpp/TraceablePeerConnection.js")
  8863. },{"../../service/xmpp/XMPPEvents":86,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"./LocalSSRCReplacement":29,"jitsi-meet-logger":47,"sdp-interop":65,"sdp-simulcast":68,"sdp-transform":75}],34:[function(require,module,exports){
  8864. (function (__filename){
  8865. /* global $, $iq, APP, config, messageHandler,
  8866. roomName, sessionTerminated, Strophe, Util */
  8867. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8868. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8869. var Settings = require("../settings/Settings");
  8870. var AuthenticationEvents
  8871. = require("../../service/authentication/AuthenticationEvents");
  8872. function createExpBackoffTimer(step) {
  8873. var count = 1;
  8874. return function (reset) {
  8875. // Reset call
  8876. if (reset) {
  8877. count = 1;
  8878. return;
  8879. }
  8880. // Calculate next timeout
  8881. var timeout = Math.pow(2, count - 1);
  8882. count += 1;
  8883. return timeout * step;
  8884. };
  8885. }
  8886. function Moderator(roomName, xmpp, emitter) {
  8887. this.roomName = roomName;
  8888. this.xmppService = xmpp;
  8889. this.getNextTimeout = createExpBackoffTimer(1000);
  8890. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  8891. // External authentication stuff
  8892. this.externalAuthEnabled = false;
  8893. this.settings = new Settings(roomName);
  8894. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  8895. // it will be enabled automatically if focus detects the component through
  8896. // service discovery.
  8897. this.sipGatewayEnabled =
  8898. this.xmppService.options.hosts.call_control !== undefined;
  8899. this.eventEmitter = emitter;
  8900. this.connection = this.xmppService.connection;
  8901. this.focusUserJid;
  8902. //FIXME:
  8903. // Message listener that talks to POPUP window
  8904. function listener(event) {
  8905. if (event.data && event.data.sessionId) {
  8906. if (event.origin !== window.location.origin) {
  8907. logger.warn("Ignoring sessionId from different origin: " +
  8908. event.origin);
  8909. return;
  8910. }
  8911. localStorage.setItem('sessionId', event.data.sessionId);
  8912. // After popup is closed we will authenticate
  8913. }
  8914. }
  8915. // Register
  8916. if (window.addEventListener) {
  8917. window.addEventListener("message", listener, false);
  8918. } else {
  8919. window.attachEvent("onmessage", listener);
  8920. }
  8921. }
  8922. Moderator.prototype.isExternalAuthEnabled = function () {
  8923. return this.externalAuthEnabled;
  8924. };
  8925. Moderator.prototype.isSipGatewayEnabled = function () {
  8926. return this.sipGatewayEnabled;
  8927. };
  8928. Moderator.prototype.onMucMemberLeft = function (jid) {
  8929. logger.info("Someone left is it focus ? " + jid);
  8930. var resource = Strophe.getResourceFromJid(jid);
  8931. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  8932. logger.info(
  8933. "Focus has left the room - leaving conference");
  8934. //hangUp();
  8935. // We'd rather reload to have everything re-initialized
  8936. //FIXME: show some message before reload
  8937. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  8938. }
  8939. };
  8940. Moderator.prototype.setFocusUserJid = function (focusJid) {
  8941. if (!this.focusUserJid) {
  8942. this.focusUserJid = focusJid;
  8943. logger.info("Focus jid set to: " + this.focusUserJid);
  8944. }
  8945. };
  8946. Moderator.prototype.getFocusUserJid = function () {
  8947. return this.focusUserJid;
  8948. };
  8949. Moderator.prototype.getFocusComponent = function () {
  8950. // Get focus component address
  8951. var focusComponent = this.xmppService.options.hosts.focus;
  8952. // If not specified use default: 'focus.domain'
  8953. if (!focusComponent) {
  8954. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  8955. }
  8956. return focusComponent;
  8957. };
  8958. Moderator.prototype.createConferenceIq = function () {
  8959. // Generate create conference IQ
  8960. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  8961. // Session Id used for authentication
  8962. var sessionId = localStorage.getItem('sessionId');
  8963. var machineUID = this.settings.getSettings().uid;
  8964. logger.info(
  8965. "Session ID: " + sessionId + " machine UID: " + machineUID);
  8966. elem.c('conference', {
  8967. xmlns: 'http://jitsi.org/protocol/focus',
  8968. room: this.roomName,
  8969. 'machine-uid': machineUID
  8970. });
  8971. if (sessionId) {
  8972. elem.attrs({ 'session-id': sessionId});
  8973. }
  8974. if (this.xmppService.options.hosts.bridge !== undefined) {
  8975. elem.c(
  8976. 'property', {
  8977. name: 'bridge',
  8978. value: this.xmppService.options.hosts.bridge
  8979. }).up();
  8980. }
  8981. // Tell the focus we have Jigasi configured
  8982. if (this.xmppService.options.hosts.call_control !== undefined) {
  8983. elem.c(
  8984. 'property', {
  8985. name: 'call_control',
  8986. value: this.xmppService.options.hosts.call_control
  8987. }).up();
  8988. }
  8989. if (this.xmppService.options.channelLastN !== undefined) {
  8990. elem.c(
  8991. 'property', {
  8992. name: 'channelLastN',
  8993. value: this.xmppService.options.channelLastN
  8994. }).up();
  8995. }
  8996. if (this.xmppService.options.adaptiveLastN !== undefined) {
  8997. elem.c(
  8998. 'property', {
  8999. name: 'adaptiveLastN',
  9000. value: this.xmppService.options.adaptiveLastN
  9001. }).up();
  9002. }
  9003. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  9004. elem.c(
  9005. 'property', {
  9006. name: 'adaptiveSimulcast',
  9007. value: this.xmppService.options.adaptiveSimulcast
  9008. }).up();
  9009. }
  9010. if (this.xmppService.options.openSctp !== undefined) {
  9011. elem.c(
  9012. 'property', {
  9013. name: 'openSctp',
  9014. value: this.xmppService.options.openSctp
  9015. }).up();
  9016. }
  9017. if (this.xmppService.options.startAudioMuted !== undefined)
  9018. {
  9019. elem.c(
  9020. 'property', {
  9021. name: 'startAudioMuted',
  9022. value: this.xmppService.options.startAudioMuted
  9023. }).up();
  9024. }
  9025. if (this.xmppService.options.startVideoMuted !== undefined)
  9026. {
  9027. elem.c(
  9028. 'property', {
  9029. name: 'startVideoMuted',
  9030. value: this.xmppService.options.startVideoMuted
  9031. }).up();
  9032. }
  9033. elem.c(
  9034. 'property', {
  9035. name: 'simulcastMode',
  9036. value: 'rewriting'
  9037. }).up();
  9038. elem.up();
  9039. return elem;
  9040. };
  9041. Moderator.prototype.parseSessionId = function (resultIq) {
  9042. var sessionId = $(resultIq).find('conference').attr('session-id');
  9043. if (sessionId) {
  9044. logger.info('Received sessionId: ' + sessionId);
  9045. localStorage.setItem('sessionId', sessionId);
  9046. }
  9047. };
  9048. Moderator.prototype.parseConfigOptions = function (resultIq) {
  9049. this.setFocusUserJid(
  9050. $(resultIq).find('conference').attr('focusjid'));
  9051. var authenticationEnabled
  9052. = $(resultIq).find(
  9053. '>conference>property' +
  9054. '[name=\'authentication\'][value=\'true\']').length > 0;
  9055. logger.info("Authentication enabled: " + authenticationEnabled);
  9056. this.externalAuthEnabled = $(resultIq).find(
  9057. '>conference>property' +
  9058. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  9059. console.info(
  9060. 'External authentication enabled: ' + this.externalAuthEnabled);
  9061. if (!this.externalAuthEnabled) {
  9062. // We expect to receive sessionId in 'internal' authentication mode
  9063. this.parseSessionId(resultIq);
  9064. }
  9065. var authIdentity = $(resultIq).find('>conference').attr('identity');
  9066. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  9067. authenticationEnabled, authIdentity);
  9068. // Check if focus has auto-detected Jigasi component(this will be also
  9069. // included if we have passed our host from the config)
  9070. if ($(resultIq).find(
  9071. '>conference>property' +
  9072. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  9073. this.sipGatewayEnabled = true;
  9074. }
  9075. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  9076. };
  9077. // FIXME = we need to show the fact that we're waiting for the focus
  9078. // to the user(or that focus is not available)
  9079. Moderator.prototype.allocateConferenceFocus = function (callback) {
  9080. // Try to use focus user JID from the config
  9081. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  9082. // Send create conference IQ
  9083. var iq = this.createConferenceIq();
  9084. var self = this;
  9085. this.connection.sendIQ(
  9086. iq,
  9087. function (result) {
  9088. // Setup config options
  9089. self.parseConfigOptions(result);
  9090. if ('true' === $(result).find('conference').attr('ready')) {
  9091. // Reset both timers
  9092. self.getNextTimeout(true);
  9093. self.getNextErrorTimeout(true);
  9094. // Exec callback
  9095. callback();
  9096. } else {
  9097. var waitMs = self.getNextTimeout();
  9098. logger.info("Waiting for the focus... " + waitMs);
  9099. // Reset error timeout
  9100. self.getNextErrorTimeout(true);
  9101. window.setTimeout(
  9102. function () {
  9103. self.allocateConferenceFocus(callback);
  9104. }, waitMs);
  9105. }
  9106. },
  9107. function (error) {
  9108. // Invalid session ? remove and try again
  9109. // without session ID to get a new one
  9110. var invalidSession
  9111. = $(error).find('>error>session-invalid').length;
  9112. if (invalidSession) {
  9113. logger.info("Session expired! - removing");
  9114. localStorage.removeItem("sessionId");
  9115. }
  9116. if ($(error).find('>error>graceful-shutdown').length) {
  9117. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  9118. return;
  9119. }
  9120. // Check for error returned by the reservation system
  9121. var reservationErr = $(error).find('>error>reservation-error');
  9122. if (reservationErr.length) {
  9123. // Trigger error event
  9124. var errorCode = reservationErr.attr('error-code');
  9125. var errorMsg;
  9126. if ($(error).find('>error>text')) {
  9127. errorMsg = $(error).find('>error>text').text();
  9128. }
  9129. self.eventEmitter.emit(
  9130. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  9131. return;
  9132. }
  9133. // Not authorized to create new room
  9134. if ($(error).find('>error>not-authorized').length) {
  9135. logger.warn("Unauthorized to start the conference", error);
  9136. var toDomain
  9137. = Strophe.getDomainFromJid(error.getAttribute('to'));
  9138. if (toDomain !==
  9139. this.xmppService.options.hosts.anonymousdomain) {
  9140. //FIXME: "is external" should come either from
  9141. // the focus or config.js
  9142. self.externalAuthEnabled = true;
  9143. }
  9144. self.eventEmitter.emit(
  9145. XMPPEvents.AUTHENTICATION_REQUIRED,
  9146. function () {
  9147. self.allocateConferenceFocus(
  9148. callback);
  9149. });
  9150. return;
  9151. }
  9152. var waitMs = self.getNextErrorTimeout();
  9153. logger.error("Focus error, retry after " + waitMs, error);
  9154. // Show message
  9155. var focusComponent = self.getFocusComponent();
  9156. var retrySec = waitMs / 1000;
  9157. //FIXME: message is duplicated ?
  9158. // Do not show in case of session invalid
  9159. // which means just a retry
  9160. if (!invalidSession) {
  9161. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  9162. focusComponent, retrySec);
  9163. }
  9164. // Reset response timeout
  9165. self.getNextTimeout(true);
  9166. window.setTimeout(
  9167. function () {
  9168. self.allocateConferenceFocus(callback);
  9169. }, waitMs);
  9170. }
  9171. );
  9172. };
  9173. Moderator.prototype.getLoginUrl = function (urlCallback) {
  9174. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9175. iq.c('login-url', {
  9176. xmlns: 'http://jitsi.org/protocol/focus',
  9177. room: this.roomName,
  9178. 'machine-uid': this.settings.getSettings().uid
  9179. });
  9180. this.connection.sendIQ(
  9181. iq,
  9182. function (result) {
  9183. var url = $(result).find('login-url').attr('url');
  9184. url = url = decodeURIComponent(url);
  9185. if (url) {
  9186. logger.info("Got auth url: " + url);
  9187. urlCallback(url);
  9188. } else {
  9189. logger.error(
  9190. "Failed to get auth url from the focus", result);
  9191. }
  9192. },
  9193. function (error) {
  9194. logger.error("Get auth url error", error);
  9195. }
  9196. );
  9197. };
  9198. Moderator.prototype.getPopupLoginUrl = function (urlCallback) {
  9199. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9200. iq.c('login-url', {
  9201. xmlns: 'http://jitsi.org/protocol/focus',
  9202. room: this.roomName,
  9203. 'machine-uid': this.settings.getSettings().uid,
  9204. popup: true
  9205. });
  9206. this.connection.sendIQ(
  9207. iq,
  9208. function (result) {
  9209. var url = $(result).find('login-url').attr('url');
  9210. url = url = decodeURIComponent(url);
  9211. if (url) {
  9212. logger.info("Got POPUP auth url: " + url);
  9213. urlCallback(url);
  9214. } else {
  9215. logger.error(
  9216. "Failed to get POPUP auth url from the focus", result);
  9217. }
  9218. },
  9219. function (error) {
  9220. logger.error('Get POPUP auth url error', error);
  9221. }
  9222. );
  9223. };
  9224. Moderator.prototype.logout = function (callback) {
  9225. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  9226. var sessionId = localStorage.getItem('sessionId');
  9227. if (!sessionId) {
  9228. callback();
  9229. return;
  9230. }
  9231. iq.c('logout', {
  9232. xmlns: 'http://jitsi.org/protocol/focus',
  9233. 'session-id': sessionId
  9234. });
  9235. this.connection.sendIQ(
  9236. iq,
  9237. function (result) {
  9238. var logoutUrl = $(result).find('logout').attr('logout-url');
  9239. if (logoutUrl) {
  9240. logoutUrl = decodeURIComponent(logoutUrl);
  9241. }
  9242. logger.info("Log out OK, url: " + logoutUrl, result);
  9243. localStorage.removeItem('sessionId');
  9244. callback(logoutUrl);
  9245. },
  9246. function (error) {
  9247. logger.error("Logout error", error);
  9248. }
  9249. );
  9250. };
  9251. module.exports = Moderator;
  9252. }).call(this,"/modules/xmpp/moderator.js")
  9253. },{"../../service/authentication/AuthenticationEvents":82,"../../service/xmpp/XMPPEvents":86,"../settings/Settings":21,"jitsi-meet-logger":47}],35:[function(require,module,exports){
  9254. (function (__filename){
  9255. /* jshint -W117 */
  9256. /* a simple MUC connection plugin
  9257. * can only handle a single MUC room
  9258. */
  9259. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9260. var ChatRoom = require("./ChatRoom");
  9261. module.exports = function(XMPP) {
  9262. Strophe.addConnectionPlugin('emuc', {
  9263. connection: null,
  9264. rooms: {},//map with the rooms
  9265. init: function (conn) {
  9266. this.connection = conn;
  9267. // add handlers (just once)
  9268. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, null, null);
  9269. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null);
  9270. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null);
  9271. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null);
  9272. },
  9273. createRoom: function (jid, password, options) {
  9274. var roomJid = Strophe.getBareJidFromJid(jid);
  9275. if (this.rooms[roomJid]) {
  9276. logger.error("You are already in the room!");
  9277. return;
  9278. }
  9279. this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, options);
  9280. return this.rooms[roomJid];
  9281. },
  9282. doLeave: function (jid) {
  9283. this.rooms[jid].doLeave();
  9284. delete this.rooms[jid];
  9285. },
  9286. onPresence: function (pres) {
  9287. var from = pres.getAttribute('from');
  9288. // What is this for? A workaround for something?
  9289. if (pres.getAttribute('type')) {
  9290. return true;
  9291. }
  9292. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9293. if(!room)
  9294. return;
  9295. // Parse status.
  9296. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  9297. room.createNonAnonymousRoom();
  9298. }
  9299. room.onPresence(pres);
  9300. return true;
  9301. },
  9302. onPresenceUnavailable: function (pres) {
  9303. var from = pres.getAttribute('from');
  9304. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9305. if(!room)
  9306. return;
  9307. room.onPresenceUnavailable(pres, from);
  9308. return true;
  9309. },
  9310. onPresenceError: function (pres) {
  9311. var from = pres.getAttribute('from');
  9312. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9313. if(!room)
  9314. return;
  9315. room.onPresenceError(pres, from);
  9316. return true;
  9317. },
  9318. onMessage: function (msg) {
  9319. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  9320. var from = msg.getAttribute('from');
  9321. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9322. if(!room)
  9323. return;
  9324. room.onMessage(msg, from);
  9325. return true;
  9326. },
  9327. setJingleSession: function (from, session) {
  9328. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9329. if(!room)
  9330. return;
  9331. room.setJingleSession(session);
  9332. }
  9333. });
  9334. };
  9335. }).call(this,"/modules/xmpp/strophe.emuc.js")
  9336. },{"./ChatRoom":26,"jitsi-meet-logger":47}],36:[function(require,module,exports){
  9337. (function (__filename){
  9338. /* jshint -W117 */
  9339. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9340. var JingleSession = require("./JingleSessionPC");
  9341. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9342. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9343. module.exports = function(XMPP, eventEmitter) {
  9344. Strophe.addConnectionPlugin('jingle', {
  9345. connection: null,
  9346. sessions: {},
  9347. jid2session: {},
  9348. ice_config: {iceServers: []},
  9349. media_constraints: {
  9350. mandatory: {
  9351. 'OfferToReceiveAudio': true,
  9352. 'OfferToReceiveVideo': true
  9353. }
  9354. // MozDontOfferDataChannel: true when this is firefox
  9355. },
  9356. init: function (conn) {
  9357. this.connection = conn;
  9358. if (this.connection.disco) {
  9359. // http://xmpp.org/extensions/xep-0167.html#support
  9360. // http://xmpp.org/extensions/xep-0176.html#support
  9361. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  9362. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  9363. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  9364. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  9365. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  9366. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  9367. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  9368. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  9369. || RTCBrowserType.isTemasysPluginUsed()) {
  9370. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  9371. }
  9372. // this is dealt with by SDP O/A so we don't need to announce this
  9373. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  9374. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  9375. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  9376. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  9377. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  9378. }
  9379. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  9380. },
  9381. onJingle: function (iq) {
  9382. var sid = $(iq).find('jingle').attr('sid');
  9383. var action = $(iq).find('jingle').attr('action');
  9384. var fromJid = iq.getAttribute('from');
  9385. // send ack first
  9386. var ack = $iq({type: 'result',
  9387. to: fromJid,
  9388. id: iq.getAttribute('id')
  9389. });
  9390. logger.log('on jingle ' + action + ' from ' + fromJid, iq);
  9391. var sess = this.sessions[sid];
  9392. if ('session-initiate' != action) {
  9393. if (sess === null) {
  9394. ack.type = 'error';
  9395. ack.c('error', {type: 'cancel'})
  9396. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  9397. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  9398. this.connection.send(ack);
  9399. return true;
  9400. }
  9401. // local jid is not checked
  9402. if (fromJid != sess.peerjid) {
  9403. logger.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  9404. ack.type = 'error';
  9405. ack.c('error', {type: 'cancel'})
  9406. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  9407. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  9408. this.connection.send(ack);
  9409. return true;
  9410. }
  9411. } else if (sess !== undefined) {
  9412. // existing session with same session id
  9413. // this might be out-of-order if the sess.peerjid is the same as from
  9414. ack.type = 'error';
  9415. ack.c('error', {type: 'cancel'})
  9416. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  9417. logger.warn('duplicate session id', sid);
  9418. this.connection.send(ack);
  9419. return true;
  9420. }
  9421. // FIXME: check for a defined action
  9422. this.connection.send(ack);
  9423. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  9424. switch (action) {
  9425. case 'session-initiate':
  9426. console.log("(TIME) received session-initiate:\t",
  9427. window.performance.now());
  9428. var startMuted = $(iq).find('jingle>startmuted');
  9429. if (startMuted && startMuted.length > 0) {
  9430. var audioMuted = startMuted.attr("audio");
  9431. var videoMuted = startMuted.attr("video");
  9432. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  9433. audioMuted === "true", videoMuted === "true");
  9434. }
  9435. sess = new JingleSession(
  9436. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  9437. this.connection, XMPP);
  9438. // configure session
  9439. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  9440. this.connection.emuc.setJingleSession(fromBareJid, sess);
  9441. sess.media_constraints = this.media_constraints;
  9442. sess.ice_config = this.ice_config;
  9443. sess.initialize(fromJid, false);
  9444. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  9445. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  9446. sess.setOffer($(iq).find('>jingle'));
  9447. this.sessions[sess.sid] = sess;
  9448. this.jid2session[sess.peerjid] = sess;
  9449. // the callback should either
  9450. // .sendAnswer and .accept
  9451. // or .sendTerminate -- not necessarily synchronous
  9452. sess.sendAnswer();
  9453. sess.accept();
  9454. break;
  9455. case 'session-accept':
  9456. sess.setAnswer($(iq).find('>jingle'));
  9457. sess.accept();
  9458. break;
  9459. case 'session-terminate':
  9460. // If this is not the focus sending the terminate, we have
  9461. // nothing more to do here.
  9462. if (Object.keys(this.sessions).length < 1
  9463. || !(this.sessions[Object.keys(this.sessions)[0]]
  9464. instanceof JingleSession))
  9465. {
  9466. break;
  9467. }
  9468. logger.log('terminating...', sess.sid);
  9469. sess.terminate();
  9470. this.terminate(sess.sid);
  9471. if ($(iq).find('>jingle>reason').length) {
  9472. $(document).trigger('callterminated.jingle', [
  9473. sess.sid,
  9474. sess.peerjid,
  9475. $(iq).find('>jingle>reason>:first')[0].tagName,
  9476. $(iq).find('>jingle>reason>text').text()
  9477. ]);
  9478. } else {
  9479. $(document).trigger('callterminated.jingle',
  9480. [sess.sid, sess.peerjid]);
  9481. }
  9482. break;
  9483. case 'transport-info':
  9484. sess.addIceCandidate($(iq).find('>jingle>content'));
  9485. break;
  9486. case 'session-info':
  9487. var affected;
  9488. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9489. $(document).trigger('ringing.jingle', [sess.sid]);
  9490. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9491. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  9492. $(document).trigger('mute.jingle', [sess.sid, affected]);
  9493. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9494. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  9495. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  9496. }
  9497. break;
  9498. case 'addsource': // FIXME: proprietary, un-jingleish
  9499. case 'source-add': // FIXME: proprietary
  9500. sess.addSource($(iq).find('>jingle>content'));
  9501. break;
  9502. case 'removesource': // FIXME: proprietary, un-jingleish
  9503. case 'source-remove': // FIXME: proprietary
  9504. sess.removeSource($(iq).find('>jingle>content'));
  9505. break;
  9506. default:
  9507. logger.warn('jingle action not implemented', action);
  9508. break;
  9509. }
  9510. return true;
  9511. },
  9512. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  9513. if (sid === null || sid === undefined) {
  9514. for (sid in this.sessions) {
  9515. if (this.sessions[sid].state != 'ended') {
  9516. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  9517. this.sessions[sid].terminate();
  9518. }
  9519. delete this.jid2session[this.sessions[sid].peerjid];
  9520. delete this.sessions[sid];
  9521. }
  9522. } else if (this.sessions.hasOwnProperty(sid)) {
  9523. if (this.sessions[sid].state != 'ended') {
  9524. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  9525. this.sessions[sid].terminate();
  9526. }
  9527. delete this.jid2session[this.sessions[sid].peerjid];
  9528. delete this.sessions[sid];
  9529. }
  9530. },
  9531. getStunAndTurnCredentials: function () {
  9532. // get stun and turn configuration from server via xep-0215
  9533. // uses time-limited credentials as described in
  9534. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  9535. //
  9536. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  9537. // for a prosody module which implements this
  9538. //
  9539. // currently, this doesn't work with updateIce and therefore credentials with a long
  9540. // validity have to be fetched before creating the peerconnection
  9541. // TODO: implement refresh via updateIce as described in
  9542. // https://code.google.com/p/webrtc/issues/detail?id=1650
  9543. var self = this;
  9544. this.connection.sendIQ(
  9545. $iq({type: 'get', to: this.connection.domain})
  9546. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  9547. function (res) {
  9548. var iceservers = [];
  9549. $(res).find('>services>service').each(function (idx, el) {
  9550. el = $(el);
  9551. var dict = {};
  9552. var type = el.attr('type');
  9553. switch (type) {
  9554. case 'stun':
  9555. dict.url = 'stun:' + el.attr('host');
  9556. if (el.attr('port')) {
  9557. dict.url += ':' + el.attr('port');
  9558. }
  9559. iceservers.push(dict);
  9560. break;
  9561. case 'turn':
  9562. case 'turns':
  9563. dict.url = type + ':';
  9564. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  9565. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  9566. dict.url += el.attr('username') + '@';
  9567. } else {
  9568. dict.username = el.attr('username'); // only works in M28
  9569. }
  9570. }
  9571. dict.url += el.attr('host');
  9572. if (el.attr('port') && el.attr('port') != '3478') {
  9573. dict.url += ':' + el.attr('port');
  9574. }
  9575. if (el.attr('transport') && el.attr('transport') != 'udp') {
  9576. dict.url += '?transport=' + el.attr('transport');
  9577. }
  9578. if (el.attr('password')) {
  9579. dict.credential = el.attr('password');
  9580. }
  9581. iceservers.push(dict);
  9582. break;
  9583. }
  9584. });
  9585. self.ice_config.iceServers = iceservers;
  9586. },
  9587. function (err) {
  9588. logger.warn('getting turn credentials failed', err);
  9589. logger.warn('is mod_turncredentials or similar installed?');
  9590. }
  9591. );
  9592. // implement push?
  9593. },
  9594. /**
  9595. * Returns the data saved in 'updateLog' in a format to be logged.
  9596. */
  9597. getLog: function () {
  9598. var data = {};
  9599. var self = this;
  9600. Object.keys(this.sessions).forEach(function (sid) {
  9601. var session = self.sessions[sid];
  9602. if (session.peerconnection && session.peerconnection.updateLog) {
  9603. // FIXME: should probably be a .dump call
  9604. data["jingle_" + session.sid] = {
  9605. updateLog: session.peerconnection.updateLog,
  9606. stats: session.peerconnection.stats,
  9607. url: window.location.href
  9608. };
  9609. }
  9610. });
  9611. return data;
  9612. }
  9613. });
  9614. };
  9615. }).call(this,"/modules/xmpp/strophe.jingle.js")
  9616. },{"../../service/xmpp/XMPPEvents":86,"../RTC/RTCBrowserType":17,"./JingleSessionPC":28,"jitsi-meet-logger":47}],37:[function(require,module,exports){
  9617. /* global Strophe */
  9618. module.exports = function () {
  9619. Strophe.addConnectionPlugin('logger', {
  9620. // logs raw stanzas and makes them available for download as JSON
  9621. connection: null,
  9622. log: [],
  9623. init: function (conn) {
  9624. this.connection = conn;
  9625. this.connection.rawInput = this.log_incoming.bind(this);
  9626. this.connection.rawOutput = this.log_outgoing.bind(this);
  9627. },
  9628. log_incoming: function (stanza) {
  9629. this.log.push([new Date().getTime(), 'incoming', stanza]);
  9630. },
  9631. log_outgoing: function (stanza) {
  9632. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  9633. }
  9634. });
  9635. };
  9636. },{}],38:[function(require,module,exports){
  9637. (function (__filename){
  9638. /* global $, $iq, Strophe */
  9639. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9640. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9641. /**
  9642. * Ping every 20 sec
  9643. */
  9644. var PING_INTERVAL = 20000;
  9645. /**
  9646. * Ping timeout error after 15 sec of waiting.
  9647. */
  9648. var PING_TIMEOUT = 15000;
  9649. /**
  9650. * Will close the connection after 3 consecutive ping errors.
  9651. */
  9652. var PING_THRESHOLD = 3;
  9653. /**
  9654. * XEP-0199 ping plugin.
  9655. *
  9656. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  9657. */
  9658. module.exports = function (XMPP, eventEmitter) {
  9659. Strophe.addConnectionPlugin('ping', {
  9660. connection: null,
  9661. failedPings: 0,
  9662. /**
  9663. * Initializes the plugin. Method called by Strophe.
  9664. * @param connection Strophe connection instance.
  9665. */
  9666. init: function (connection) {
  9667. this.connection = connection;
  9668. Strophe.addNamespace('PING', "urn:xmpp:ping");
  9669. },
  9670. /**
  9671. * Sends "ping" to given <tt>jid</tt>
  9672. * @param jid the JID to which ping request will be sent.
  9673. * @param success callback called on success.
  9674. * @param error callback called on error.
  9675. * @param timeout ms how long are we going to wait for the response. On
  9676. * timeout <tt>error<//t> callback is called with undefined error
  9677. * argument.
  9678. */
  9679. ping: function (jid, success, error, timeout) {
  9680. var iq = $iq({type: 'get', to: jid});
  9681. iq.c('ping', {xmlns: Strophe.NS.PING});
  9682. this.connection.sendIQ(iq, success, error, timeout);
  9683. },
  9684. /**
  9685. * Checks if given <tt>jid</tt> has XEP-0199 ping support.
  9686. * @param jid the JID to be checked for ping support.
  9687. * @param callback function with boolean argument which will be
  9688. * <tt>true</tt> if XEP-0199 ping is supported by given <tt>jid</tt>
  9689. */
  9690. hasPingSupport: function (jid, callback) {
  9691. this.connection.disco.info(
  9692. jid, null,
  9693. function (result) {
  9694. var ping = $(result).find('>>feature[var="urn:xmpp:ping"]');
  9695. callback(ping.length > 0);
  9696. },
  9697. function (error) {
  9698. logger.error("Ping feature discovery error", error);
  9699. callback(false);
  9700. }
  9701. );
  9702. },
  9703. /**
  9704. * Starts to send ping in given interval to specified remote JID.
  9705. * This plugin supports only one such task and <tt>stopInterval</tt>
  9706. * must be called before starting a new one.
  9707. * @param remoteJid remote JID to which ping requests will be sent to.
  9708. * @param interval task interval in ms.
  9709. */
  9710. startInterval: function (remoteJid, interval) {
  9711. if (this.intervalId) {
  9712. logger.error("Ping task scheduled already");
  9713. return;
  9714. }
  9715. if (!interval)
  9716. interval = PING_INTERVAL;
  9717. var self = this;
  9718. this.intervalId = window.setInterval(function () {
  9719. self.ping(remoteJid,
  9720. function (result) {
  9721. // Ping OK
  9722. self.failedPings = 0;
  9723. },
  9724. function (error) {
  9725. self.failedPings += 1;
  9726. logger.error(
  9727. "Ping " + (error ? "error" : "timeout"), error);
  9728. if (self.failedPings >= PING_THRESHOLD) {
  9729. self.connection.disconnect();
  9730. }
  9731. }, PING_TIMEOUT);
  9732. }, interval);
  9733. logger.info("XMPP pings will be sent every " + interval + " ms");
  9734. },
  9735. /**
  9736. * Stops current "ping" interval task.
  9737. */
  9738. stopInterval: function () {
  9739. if (this.intervalId) {
  9740. window.clearInterval(this.intervalId);
  9741. this.intervalId = null;
  9742. this.failedPings = 0;
  9743. logger.info("Ping interval cleared");
  9744. }
  9745. }
  9746. });
  9747. };
  9748. }).call(this,"/modules/xmpp/strophe.ping.js")
  9749. },{"../../service/xmpp/XMPPEvents":86,"jitsi-meet-logger":47}],39:[function(require,module,exports){
  9750. (function (__filename){
  9751. /* jshint -W117 */
  9752. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9753. module.exports = function() {
  9754. Strophe.addConnectionPlugin('rayo',
  9755. {
  9756. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  9757. connection: null,
  9758. init: function (conn) {
  9759. this.connection = conn;
  9760. if (this.connection.disco) {
  9761. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  9762. }
  9763. this.connection.addHandler(
  9764. this.onRayo.bind(this),
  9765. this.RAYO_XMLNS, 'iq', 'set', null, null);
  9766. },
  9767. onRayo: function (iq) {
  9768. logger.info("Rayo IQ", iq);
  9769. },
  9770. dial: function (to, from, roomName, roomPass) {
  9771. var self = this;
  9772. var req = $iq(
  9773. {
  9774. type: 'set',
  9775. to: this.connection.emuc.focusMucJid
  9776. }
  9777. );
  9778. req.c('dial',
  9779. {
  9780. xmlns: this.RAYO_XMLNS,
  9781. to: to,
  9782. from: from
  9783. });
  9784. req.c('header',
  9785. {
  9786. name: 'JvbRoomName',
  9787. value: roomName
  9788. }).up();
  9789. if (roomPass !== null && roomPass.length) {
  9790. req.c('header',
  9791. {
  9792. name: 'JvbRoomPassword',
  9793. value: roomPass
  9794. }).up();
  9795. }
  9796. this.connection.sendIQ(
  9797. req,
  9798. function (result) {
  9799. logger.info('Dial result ', result);
  9800. var resource = $(result).find('ref').attr('uri');
  9801. this.call_resource = resource.substr('xmpp:'.length);
  9802. logger.info(
  9803. "Received call resource: " + this.call_resource);
  9804. },
  9805. function (error) {
  9806. logger.info('Dial error ', error);
  9807. }
  9808. );
  9809. },
  9810. hang_up: function () {
  9811. if (!this.call_resource) {
  9812. logger.warn("No call in progress");
  9813. return;
  9814. }
  9815. var self = this;
  9816. var req = $iq(
  9817. {
  9818. type: 'set',
  9819. to: this.call_resource
  9820. }
  9821. );
  9822. req.c('hangup',
  9823. {
  9824. xmlns: this.RAYO_XMLNS
  9825. });
  9826. this.connection.sendIQ(
  9827. req,
  9828. function (result) {
  9829. logger.info('Hangup result ', result);
  9830. self.call_resource = null;
  9831. },
  9832. function (error) {
  9833. logger.info('Hangup error ', error);
  9834. self.call_resource = null;
  9835. }
  9836. );
  9837. }
  9838. }
  9839. );
  9840. };
  9841. }).call(this,"/modules/xmpp/strophe.rayo.js")
  9842. },{"jitsi-meet-logger":47}],40:[function(require,module,exports){
  9843. (function (__filename){
  9844. /* global Strophe */
  9845. /**
  9846. * Strophe logger implementation. Logs from level WARN and above.
  9847. */
  9848. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9849. module.exports = function () {
  9850. Strophe.log = function (level, msg) {
  9851. switch (level) {
  9852. case Strophe.LogLevel.WARN:
  9853. logger.warn("Strophe: " + msg);
  9854. break;
  9855. case Strophe.LogLevel.ERROR:
  9856. case Strophe.LogLevel.FATAL:
  9857. logger.error("Strophe: " + msg);
  9858. break;
  9859. }
  9860. };
  9861. Strophe.getStatusString = function (status) {
  9862. switch (status) {
  9863. case Strophe.Status.ERROR:
  9864. return "ERROR";
  9865. case Strophe.Status.CONNECTING:
  9866. return "CONNECTING";
  9867. case Strophe.Status.CONNFAIL:
  9868. return "CONNFAIL";
  9869. case Strophe.Status.AUTHENTICATING:
  9870. return "AUTHENTICATING";
  9871. case Strophe.Status.AUTHFAIL:
  9872. return "AUTHFAIL";
  9873. case Strophe.Status.CONNECTED:
  9874. return "CONNECTED";
  9875. case Strophe.Status.DISCONNECTED:
  9876. return "DISCONNECTED";
  9877. case Strophe.Status.DISCONNECTING:
  9878. return "DISCONNECTING";
  9879. case Strophe.Status.ATTACHED:
  9880. return "ATTACHED";
  9881. default:
  9882. return "unknown";
  9883. }
  9884. };
  9885. };
  9886. }).call(this,"/modules/xmpp/strophe.util.js")
  9887. },{"jitsi-meet-logger":47}],41:[function(require,module,exports){
  9888. (function (__filename){
  9889. /* global $, APP, config, Strophe*/
  9890. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9891. var EventEmitter = require("events");
  9892. var Pako = require("pako");
  9893. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  9894. var RTCEvents = require("../../service/RTC/RTCEvents");
  9895. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9896. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  9897. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  9898. var RTC = require("../RTC/RTC");
  9899. var authenticatedUser = false;
  9900. function createConnection(bosh) {
  9901. bosh = bosh || '/http-bind';
  9902. return new Strophe.Connection(bosh);
  9903. };
  9904. //!!!!!!!!!! FIXME: ...
  9905. function initStrophePlugins(XMPP)
  9906. {
  9907. require("./strophe.emuc")(XMPP);
  9908. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  9909. // require("./strophe.moderate")(XMPP, eventEmitter);
  9910. require("./strophe.util")();
  9911. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  9912. require("./strophe.rayo")();
  9913. require("./strophe.logger")();
  9914. }
  9915. //!!!!!!!!!! FIXME: ...
  9916. ///**
  9917. // * If given <tt>localStream</tt> is video one this method will advertise it's
  9918. // * video type in MUC presence.
  9919. // * @param localStream new or modified <tt>LocalStream</tt>.
  9920. // */
  9921. //function broadcastLocalVideoType(localStream) {
  9922. // if (localStream.videoType)
  9923. // XMPP.addToPresence('videoType', localStream.videoType);
  9924. //}
  9925. //
  9926. //function registerListeners() {
  9927. // RTC.addStreamListener(
  9928. // broadcastLocalVideoType,
  9929. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  9930. // );
  9931. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  9932. // XMPP.addToPresence("devices", devices);
  9933. // });
  9934. //}
  9935. function XMPP(options) {
  9936. this.eventEmitter = new EventEmitter();
  9937. this.connection = null;
  9938. this.disconnectInProgress = false;
  9939. this.forceMuted = false;
  9940. this.options = options;
  9941. initStrophePlugins(this);
  9942. // registerListeners();
  9943. this.connection = createConnection(options.bosh);
  9944. }
  9945. XMPP.prototype.getConnection = function(){ return connection; };
  9946. XMPP.prototype._connect = function (jid, password) {
  9947. var self = this;
  9948. // connection.connect() starts the connection process.
  9949. //
  9950. // As the connection process proceeds, the user supplied callback will
  9951. // be triggered multiple times with status updates. The callback should
  9952. // take two arguments - the status code and the error condition.
  9953. //
  9954. // The status code will be one of the values in the Strophe.Status
  9955. // constants. The error condition will be one of the conditions defined
  9956. // in RFC 3920 or the condition ‘strophe-parsererror’.
  9957. //
  9958. // The Parameters wait, hold and route are optional and only relevant
  9959. // for BOSH connections. Please see XEP 124 for a more detailed
  9960. // explanation of the optional parameters.
  9961. //
  9962. // Connection status constants for use by the connection handler
  9963. // callback.
  9964. //
  9965. // Status.ERROR - An error has occurred (websockets specific)
  9966. // Status.CONNECTING - The connection is currently being made
  9967. // Status.CONNFAIL - The connection attempt failed
  9968. // Status.AUTHENTICATING - The connection is authenticating
  9969. // Status.AUTHFAIL - The authentication attempt failed
  9970. // Status.CONNECTED - The connection has succeeded
  9971. // Status.DISCONNECTED - The connection has been terminated
  9972. // Status.DISCONNECTING - The connection is currently being terminated
  9973. // Status.ATTACHED - The connection has been attached
  9974. var anonymousConnectionFailed = false;
  9975. var connectionFailed = false;
  9976. var lastErrorMsg;
  9977. this.connection.connect(jid, password, function (status, msg) {
  9978. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  9979. (msg ? "[" + msg + "]" : "") + "\t:" + window.performance.now());
  9980. if (status === Strophe.Status.CONNECTED) {
  9981. if (self.options.useStunTurn) {
  9982. self.connection.jingle.getStunAndTurnCredentials();
  9983. }
  9984. logger.info("My Jabber ID: " + self.connection.jid);
  9985. // Schedule ping ?
  9986. var pingJid = self.connection.domain;
  9987. self.connection.ping.hasPingSupport(
  9988. pingJid,
  9989. function (hasPing) {
  9990. if (hasPing)
  9991. self.connection.ping.startInterval(pingJid);
  9992. else
  9993. logger.warn("Ping NOT supported by " + pingJid);
  9994. }
  9995. );
  9996. if (password)
  9997. authenticatedUser = true;
  9998. if (self.connection && self.connection.connected &&
  9999. Strophe.getResourceFromJid(self.connection.jid)) {
  10000. // .connected is true while connecting?
  10001. // self.connection.send($pres());
  10002. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  10003. Strophe.getResourceFromJid(self.connection.jid));
  10004. }
  10005. } else if (status === Strophe.Status.CONNFAIL) {
  10006. if (msg === 'x-strophe-bad-non-anon-jid') {
  10007. anonymousConnectionFailed = true;
  10008. }
  10009. else
  10010. {
  10011. connectionFailed = true;
  10012. }
  10013. lastErrorMsg = msg;
  10014. } else if (status === Strophe.Status.DISCONNECTED) {
  10015. // Stop ping interval
  10016. self.connection.ping.stopInterval();
  10017. self.disconnectInProgress = false;
  10018. if (anonymousConnectionFailed) {
  10019. // prompt user for username and password
  10020. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10021. JitsiConnectionErrors.PASSWORD_REQUIRED);
  10022. } else if(connectionFailed) {
  10023. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10024. JitsiConnectionErrors.OTHER_ERROR,
  10025. msg ? msg : lastErrorMsg);
  10026. } else {
  10027. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  10028. msg ? msg : lastErrorMsg);
  10029. }
  10030. } else if (status === Strophe.Status.AUTHFAIL) {
  10031. // wrong password or username, prompt user
  10032. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10033. JitsiConnectionErrors.PASSWORD_REQUIRED);
  10034. }
  10035. });
  10036. }
  10037. XMPP.prototype.connect = function (jid, password) {
  10038. if(!jid) {
  10039. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  10040. // Force authenticated domain if room is appended with '?login=true'
  10041. if (this.options.hosts.anonymousdomain &&
  10042. window.location.search.indexOf("login=true") !== -1) {
  10043. configDomain = this.options.hosts.domain;
  10044. }
  10045. jid = configDomain || window.location.hostname;
  10046. }
  10047. return this._connect(jid, password);
  10048. };
  10049. XMPP.prototype.createRoom = function (roomName, options, useNicks, nick) {
  10050. var roomjid = roomName + '@' + this.options.hosts.muc;
  10051. if (useNicks) {
  10052. if (nick) {
  10053. roomjid += '/' + nick;
  10054. } else {
  10055. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  10056. }
  10057. } else {
  10058. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  10059. if(!authenticatedUser)
  10060. tmpJid = tmpJid.substr(0, 8);
  10061. roomjid += '/' + tmpJid;
  10062. }
  10063. return this.connection.emuc.createRoom(roomjid, null, options);
  10064. }
  10065. XMPP.prototype.addListener = function(type, listener) {
  10066. this.eventEmitter.on(type, listener);
  10067. };
  10068. XMPP.prototype.removeListener = function (type, listener) {
  10069. this.eventEmitter.removeListener(type, listener);
  10070. };
  10071. //FIXME: this should work with the room
  10072. XMPP.prototype.leaveRoom = function (jid) {
  10073. var handler = this.connection.jingle.jid2session[jid];
  10074. if (handler && handler.peerconnection) {
  10075. // FIXME: probably removing streams is not required and close() should
  10076. // be enough
  10077. if (RTC.localAudio) {
  10078. handler.peerconnection.removeStream(
  10079. RTC.localAudio.getOriginalStream(), true);
  10080. }
  10081. if (RTC.localVideo) {
  10082. handler.peerconnection.removeStream(
  10083. RTC.localVideo.getOriginalStream(), true);
  10084. }
  10085. handler.peerconnection.close();
  10086. }
  10087. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  10088. this.connection.emuc.doLeave(jid);
  10089. };
  10090. /**
  10091. * Sends 'data' as a log message to the focus. Returns true iff a message
  10092. * was sent.
  10093. * @param data
  10094. * @returns {boolean} true iff a message was sent.
  10095. */
  10096. XMPP.prototype.sendLogs = function (data) {
  10097. if(!this.connection.emuc.focusMucJid)
  10098. return false;
  10099. var deflate = true;
  10100. var content = JSON.stringify(data);
  10101. if (deflate) {
  10102. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  10103. }
  10104. content = Base64.encode(content);
  10105. // XEP-0337-ish
  10106. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  10107. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  10108. id: 'PeerConnectionStats'});
  10109. message.c('message').t(content).up();
  10110. if (deflate) {
  10111. message.c('tag', {name: "deflated", value: "true"}).up();
  10112. }
  10113. message.up();
  10114. this.connection.send(message);
  10115. return true;
  10116. };
  10117. // Gets the logs from strophe.jingle.
  10118. XMPP.prototype.getJingleLog = function () {
  10119. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  10120. };
  10121. // Gets the logs from strophe.
  10122. XMPP.prototype.getXmppLog = function () {
  10123. return this.connection.logger ? this.connection.logger.log : null;
  10124. };
  10125. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  10126. this.connection.rayo.dial(to, from, roomName,roomPass);
  10127. };
  10128. XMPP.prototype.setMute = function (jid, mute) {
  10129. this.connection.moderate.setMute(jid, mute);
  10130. };
  10131. XMPP.prototype.eject = function (jid) {
  10132. this.connection.moderate.eject(jid);
  10133. };
  10134. XMPP.prototype.getSessions = function () {
  10135. return this.connection.jingle.sessions;
  10136. };
  10137. XMPP.prototype.disconnect = function () {
  10138. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  10139. {
  10140. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  10141. return;
  10142. }
  10143. this.disconnectInProgress = true;
  10144. this.connection.disconnect();
  10145. };
  10146. module.exports = XMPP;
  10147. }).call(this,"/modules/xmpp/xmpp.js")
  10148. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":79,"../../service/RTC/StreamEventTypes":81,"../../service/xmpp/XMPPEvents":86,"../RTC/RTC":16,"./strophe.emuc":35,"./strophe.jingle":36,"./strophe.logger":37,"./strophe.ping":38,"./strophe.rayo":39,"./strophe.util":40,"events":43,"jitsi-meet-logger":47,"pako":48}],42:[function(require,module,exports){
  10149. (function (process){
  10150. /*!
  10151. * async
  10152. * https://github.com/caolan/async
  10153. *
  10154. * Copyright 2010-2014 Caolan McMahon
  10155. * Released under the MIT license
  10156. */
  10157. /*jshint onevar: false, indent:4 */
  10158. /*global setImmediate: false, setTimeout: false, console: false */
  10159. (function () {
  10160. var async = {};
  10161. // global on the server, window in the browser
  10162. var root, previous_async;
  10163. root = this;
  10164. if (root != null) {
  10165. previous_async = root.async;
  10166. }
  10167. async.noConflict = function () {
  10168. root.async = previous_async;
  10169. return async;
  10170. };
  10171. function only_once(fn) {
  10172. var called = false;
  10173. return function() {
  10174. if (called) throw new Error("Callback was already called.");
  10175. called = true;
  10176. fn.apply(root, arguments);
  10177. }
  10178. }
  10179. //// cross-browser compatiblity functions ////
  10180. var _toString = Object.prototype.toString;
  10181. var _isArray = Array.isArray || function (obj) {
  10182. return _toString.call(obj) === '[object Array]';
  10183. };
  10184. var _each = function (arr, iterator) {
  10185. if (arr.forEach) {
  10186. return arr.forEach(iterator);
  10187. }
  10188. for (var i = 0; i < arr.length; i += 1) {
  10189. iterator(arr[i], i, arr);
  10190. }
  10191. };
  10192. var _map = function (arr, iterator) {
  10193. if (arr.map) {
  10194. return arr.map(iterator);
  10195. }
  10196. var results = [];
  10197. _each(arr, function (x, i, a) {
  10198. results.push(iterator(x, i, a));
  10199. });
  10200. return results;
  10201. };
  10202. var _reduce = function (arr, iterator, memo) {
  10203. if (arr.reduce) {
  10204. return arr.reduce(iterator, memo);
  10205. }
  10206. _each(arr, function (x, i, a) {
  10207. memo = iterator(memo, x, i, a);
  10208. });
  10209. return memo;
  10210. };
  10211. var _keys = function (obj) {
  10212. if (Object.keys) {
  10213. return Object.keys(obj);
  10214. }
  10215. var keys = [];
  10216. for (var k in obj) {
  10217. if (obj.hasOwnProperty(k)) {
  10218. keys.push(k);
  10219. }
  10220. }
  10221. return keys;
  10222. };
  10223. //// exported async module functions ////
  10224. //// nextTick implementation with browser-compatible fallback ////
  10225. if (typeof process === 'undefined' || !(process.nextTick)) {
  10226. if (typeof setImmediate === 'function') {
  10227. async.nextTick = function (fn) {
  10228. // not a direct alias for IE10 compatibility
  10229. setImmediate(fn);
  10230. };
  10231. async.setImmediate = async.nextTick;
  10232. }
  10233. else {
  10234. async.nextTick = function (fn) {
  10235. setTimeout(fn, 0);
  10236. };
  10237. async.setImmediate = async.nextTick;
  10238. }
  10239. }
  10240. else {
  10241. async.nextTick = process.nextTick;
  10242. if (typeof setImmediate !== 'undefined') {
  10243. async.setImmediate = function (fn) {
  10244. // not a direct alias for IE10 compatibility
  10245. setImmediate(fn);
  10246. };
  10247. }
  10248. else {
  10249. async.setImmediate = async.nextTick;
  10250. }
  10251. }
  10252. async.each = function (arr, iterator, callback) {
  10253. callback = callback || function () {};
  10254. if (!arr.length) {
  10255. return callback();
  10256. }
  10257. var completed = 0;
  10258. _each(arr, function (x) {
  10259. iterator(x, only_once(done) );
  10260. });
  10261. function done(err) {
  10262. if (err) {
  10263. callback(err);
  10264. callback = function () {};
  10265. }
  10266. else {
  10267. completed += 1;
  10268. if (completed >= arr.length) {
  10269. callback();
  10270. }
  10271. }
  10272. }
  10273. };
  10274. async.forEach = async.each;
  10275. async.eachSeries = function (arr, iterator, callback) {
  10276. callback = callback || function () {};
  10277. if (!arr.length) {
  10278. return callback();
  10279. }
  10280. var completed = 0;
  10281. var iterate = function () {
  10282. iterator(arr[completed], function (err) {
  10283. if (err) {
  10284. callback(err);
  10285. callback = function () {};
  10286. }
  10287. else {
  10288. completed += 1;
  10289. if (completed >= arr.length) {
  10290. callback();
  10291. }
  10292. else {
  10293. iterate();
  10294. }
  10295. }
  10296. });
  10297. };
  10298. iterate();
  10299. };
  10300. async.forEachSeries = async.eachSeries;
  10301. async.eachLimit = function (arr, limit, iterator, callback) {
  10302. var fn = _eachLimit(limit);
  10303. fn.apply(null, [arr, iterator, callback]);
  10304. };
  10305. async.forEachLimit = async.eachLimit;
  10306. var _eachLimit = function (limit) {
  10307. return function (arr, iterator, callback) {
  10308. callback = callback || function () {};
  10309. if (!arr.length || limit <= 0) {
  10310. return callback();
  10311. }
  10312. var completed = 0;
  10313. var started = 0;
  10314. var running = 0;
  10315. (function replenish () {
  10316. if (completed >= arr.length) {
  10317. return callback();
  10318. }
  10319. while (running < limit && started < arr.length) {
  10320. started += 1;
  10321. running += 1;
  10322. iterator(arr[started - 1], function (err) {
  10323. if (err) {
  10324. callback(err);
  10325. callback = function () {};
  10326. }
  10327. else {
  10328. completed += 1;
  10329. running -= 1;
  10330. if (completed >= arr.length) {
  10331. callback();
  10332. }
  10333. else {
  10334. replenish();
  10335. }
  10336. }
  10337. });
  10338. }
  10339. })();
  10340. };
  10341. };
  10342. var doParallel = function (fn) {
  10343. return function () {
  10344. var args = Array.prototype.slice.call(arguments);
  10345. return fn.apply(null, [async.each].concat(args));
  10346. };
  10347. };
  10348. var doParallelLimit = function(limit, fn) {
  10349. return function () {
  10350. var args = Array.prototype.slice.call(arguments);
  10351. return fn.apply(null, [_eachLimit(limit)].concat(args));
  10352. };
  10353. };
  10354. var doSeries = function (fn) {
  10355. return function () {
  10356. var args = Array.prototype.slice.call(arguments);
  10357. return fn.apply(null, [async.eachSeries].concat(args));
  10358. };
  10359. };
  10360. var _asyncMap = function (eachfn, arr, iterator, callback) {
  10361. arr = _map(arr, function (x, i) {
  10362. return {index: i, value: x};
  10363. });
  10364. if (!callback) {
  10365. eachfn(arr, function (x, callback) {
  10366. iterator(x.value, function (err) {
  10367. callback(err);
  10368. });
  10369. });
  10370. } else {
  10371. var results = [];
  10372. eachfn(arr, function (x, callback) {
  10373. iterator(x.value, function (err, v) {
  10374. results[x.index] = v;
  10375. callback(err);
  10376. });
  10377. }, function (err) {
  10378. callback(err, results);
  10379. });
  10380. }
  10381. };
  10382. async.map = doParallel(_asyncMap);
  10383. async.mapSeries = doSeries(_asyncMap);
  10384. async.mapLimit = function (arr, limit, iterator, callback) {
  10385. return _mapLimit(limit)(arr, iterator, callback);
  10386. };
  10387. var _mapLimit = function(limit) {
  10388. return doParallelLimit(limit, _asyncMap);
  10389. };
  10390. // reduce only has a series version, as doing reduce in parallel won't
  10391. // work in many situations.
  10392. async.reduce = function (arr, memo, iterator, callback) {
  10393. async.eachSeries(arr, function (x, callback) {
  10394. iterator(memo, x, function (err, v) {
  10395. memo = v;
  10396. callback(err);
  10397. });
  10398. }, function (err) {
  10399. callback(err, memo);
  10400. });
  10401. };
  10402. // inject alias
  10403. async.inject = async.reduce;
  10404. // foldl alias
  10405. async.foldl = async.reduce;
  10406. async.reduceRight = function (arr, memo, iterator, callback) {
  10407. var reversed = _map(arr, function (x) {
  10408. return x;
  10409. }).reverse();
  10410. async.reduce(reversed, memo, iterator, callback);
  10411. };
  10412. // foldr alias
  10413. async.foldr = async.reduceRight;
  10414. var _filter = function (eachfn, arr, iterator, callback) {
  10415. var results = [];
  10416. arr = _map(arr, function (x, i) {
  10417. return {index: i, value: x};
  10418. });
  10419. eachfn(arr, function (x, callback) {
  10420. iterator(x.value, function (v) {
  10421. if (v) {
  10422. results.push(x);
  10423. }
  10424. callback();
  10425. });
  10426. }, function (err) {
  10427. callback(_map(results.sort(function (a, b) {
  10428. return a.index - b.index;
  10429. }), function (x) {
  10430. return x.value;
  10431. }));
  10432. });
  10433. };
  10434. async.filter = doParallel(_filter);
  10435. async.filterSeries = doSeries(_filter);
  10436. // select alias
  10437. async.select = async.filter;
  10438. async.selectSeries = async.filterSeries;
  10439. var _reject = function (eachfn, arr, iterator, callback) {
  10440. var results = [];
  10441. arr = _map(arr, function (x, i) {
  10442. return {index: i, value: x};
  10443. });
  10444. eachfn(arr, function (x, callback) {
  10445. iterator(x.value, function (v) {
  10446. if (!v) {
  10447. results.push(x);
  10448. }
  10449. callback();
  10450. });
  10451. }, function (err) {
  10452. callback(_map(results.sort(function (a, b) {
  10453. return a.index - b.index;
  10454. }), function (x) {
  10455. return x.value;
  10456. }));
  10457. });
  10458. };
  10459. async.reject = doParallel(_reject);
  10460. async.rejectSeries = doSeries(_reject);
  10461. var _detect = function (eachfn, arr, iterator, main_callback) {
  10462. eachfn(arr, function (x, callback) {
  10463. iterator(x, function (result) {
  10464. if (result) {
  10465. main_callback(x);
  10466. main_callback = function () {};
  10467. }
  10468. else {
  10469. callback();
  10470. }
  10471. });
  10472. }, function (err) {
  10473. main_callback();
  10474. });
  10475. };
  10476. async.detect = doParallel(_detect);
  10477. async.detectSeries = doSeries(_detect);
  10478. async.some = function (arr, iterator, main_callback) {
  10479. async.each(arr, function (x, callback) {
  10480. iterator(x, function (v) {
  10481. if (v) {
  10482. main_callback(true);
  10483. main_callback = function () {};
  10484. }
  10485. callback();
  10486. });
  10487. }, function (err) {
  10488. main_callback(false);
  10489. });
  10490. };
  10491. // any alias
  10492. async.any = async.some;
  10493. async.every = function (arr, iterator, main_callback) {
  10494. async.each(arr, function (x, callback) {
  10495. iterator(x, function (v) {
  10496. if (!v) {
  10497. main_callback(false);
  10498. main_callback = function () {};
  10499. }
  10500. callback();
  10501. });
  10502. }, function (err) {
  10503. main_callback(true);
  10504. });
  10505. };
  10506. // all alias
  10507. async.all = async.every;
  10508. async.sortBy = function (arr, iterator, callback) {
  10509. async.map(arr, function (x, callback) {
  10510. iterator(x, function (err, criteria) {
  10511. if (err) {
  10512. callback(err);
  10513. }
  10514. else {
  10515. callback(null, {value: x, criteria: criteria});
  10516. }
  10517. });
  10518. }, function (err, results) {
  10519. if (err) {
  10520. return callback(err);
  10521. }
  10522. else {
  10523. var fn = function (left, right) {
  10524. var a = left.criteria, b = right.criteria;
  10525. return a < b ? -1 : a > b ? 1 : 0;
  10526. };
  10527. callback(null, _map(results.sort(fn), function (x) {
  10528. return x.value;
  10529. }));
  10530. }
  10531. });
  10532. };
  10533. async.auto = function (tasks, callback) {
  10534. callback = callback || function () {};
  10535. var keys = _keys(tasks);
  10536. var remainingTasks = keys.length
  10537. if (!remainingTasks) {
  10538. return callback();
  10539. }
  10540. var results = {};
  10541. var listeners = [];
  10542. var addListener = function (fn) {
  10543. listeners.unshift(fn);
  10544. };
  10545. var removeListener = function (fn) {
  10546. for (var i = 0; i < listeners.length; i += 1) {
  10547. if (listeners[i] === fn) {
  10548. listeners.splice(i, 1);
  10549. return;
  10550. }
  10551. }
  10552. };
  10553. var taskComplete = function () {
  10554. remainingTasks--
  10555. _each(listeners.slice(0), function (fn) {
  10556. fn();
  10557. });
  10558. };
  10559. addListener(function () {
  10560. if (!remainingTasks) {
  10561. var theCallback = callback;
  10562. // prevent final callback from calling itself if it errors
  10563. callback = function () {};
  10564. theCallback(null, results);
  10565. }
  10566. });
  10567. _each(keys, function (k) {
  10568. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  10569. var taskCallback = function (err) {
  10570. var args = Array.prototype.slice.call(arguments, 1);
  10571. if (args.length <= 1) {
  10572. args = args[0];
  10573. }
  10574. if (err) {
  10575. var safeResults = {};
  10576. _each(_keys(results), function(rkey) {
  10577. safeResults[rkey] = results[rkey];
  10578. });
  10579. safeResults[k] = args;
  10580. callback(err, safeResults);
  10581. // stop subsequent errors hitting callback multiple times
  10582. callback = function () {};
  10583. }
  10584. else {
  10585. results[k] = args;
  10586. async.setImmediate(taskComplete);
  10587. }
  10588. };
  10589. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  10590. var ready = function () {
  10591. return _reduce(requires, function (a, x) {
  10592. return (a && results.hasOwnProperty(x));
  10593. }, true) && !results.hasOwnProperty(k);
  10594. };
  10595. if (ready()) {
  10596. task[task.length - 1](taskCallback, results);
  10597. }
  10598. else {
  10599. var listener = function () {
  10600. if (ready()) {
  10601. removeListener(listener);
  10602. task[task.length - 1](taskCallback, results);
  10603. }
  10604. };
  10605. addListener(listener);
  10606. }
  10607. });
  10608. };
  10609. async.retry = function(times, task, callback) {
  10610. var DEFAULT_TIMES = 5;
  10611. var attempts = [];
  10612. // Use defaults if times not passed
  10613. if (typeof times === 'function') {
  10614. callback = task;
  10615. task = times;
  10616. times = DEFAULT_TIMES;
  10617. }
  10618. // Make sure times is a number
  10619. times = parseInt(times, 10) || DEFAULT_TIMES;
  10620. var wrappedTask = function(wrappedCallback, wrappedResults) {
  10621. var retryAttempt = function(task, finalAttempt) {
  10622. return function(seriesCallback) {
  10623. task(function(err, result){
  10624. seriesCallback(!err || finalAttempt, {err: err, result: result});
  10625. }, wrappedResults);
  10626. };
  10627. };
  10628. while (times) {
  10629. attempts.push(retryAttempt(task, !(times-=1)));
  10630. }
  10631. async.series(attempts, function(done, data){
  10632. data = data[data.length - 1];
  10633. (wrappedCallback || callback)(data.err, data.result);
  10634. });
  10635. }
  10636. // If a callback is passed, run this as a controll flow
  10637. return callback ? wrappedTask() : wrappedTask
  10638. };
  10639. async.waterfall = function (tasks, callback) {
  10640. callback = callback || function () {};
  10641. if (!_isArray(tasks)) {
  10642. var err = new Error('First argument to waterfall must be an array of functions');
  10643. return callback(err);
  10644. }
  10645. if (!tasks.length) {
  10646. return callback();
  10647. }
  10648. var wrapIterator = function (iterator) {
  10649. return function (err) {
  10650. if (err) {
  10651. callback.apply(null, arguments);
  10652. callback = function () {};
  10653. }
  10654. else {
  10655. var args = Array.prototype.slice.call(arguments, 1);
  10656. var next = iterator.next();
  10657. if (next) {
  10658. args.push(wrapIterator(next));
  10659. }
  10660. else {
  10661. args.push(callback);
  10662. }
  10663. async.setImmediate(function () {
  10664. iterator.apply(null, args);
  10665. });
  10666. }
  10667. };
  10668. };
  10669. wrapIterator(async.iterator(tasks))();
  10670. };
  10671. var _parallel = function(eachfn, tasks, callback) {
  10672. callback = callback || function () {};
  10673. if (_isArray(tasks)) {
  10674. eachfn.map(tasks, function (fn, callback) {
  10675. if (fn) {
  10676. fn(function (err) {
  10677. var args = Array.prototype.slice.call(arguments, 1);
  10678. if (args.length <= 1) {
  10679. args = args[0];
  10680. }
  10681. callback.call(null, err, args);
  10682. });
  10683. }
  10684. }, callback);
  10685. }
  10686. else {
  10687. var results = {};
  10688. eachfn.each(_keys(tasks), function (k, callback) {
  10689. tasks[k](function (err) {
  10690. var args = Array.prototype.slice.call(arguments, 1);
  10691. if (args.length <= 1) {
  10692. args = args[0];
  10693. }
  10694. results[k] = args;
  10695. callback(err);
  10696. });
  10697. }, function (err) {
  10698. callback(err, results);
  10699. });
  10700. }
  10701. };
  10702. async.parallel = function (tasks, callback) {
  10703. _parallel({ map: async.map, each: async.each }, tasks, callback);
  10704. };
  10705. async.parallelLimit = function(tasks, limit, callback) {
  10706. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  10707. };
  10708. async.series = function (tasks, callback) {
  10709. callback = callback || function () {};
  10710. if (_isArray(tasks)) {
  10711. async.mapSeries(tasks, function (fn, callback) {
  10712. if (fn) {
  10713. fn(function (err) {
  10714. var args = Array.prototype.slice.call(arguments, 1);
  10715. if (args.length <= 1) {
  10716. args = args[0];
  10717. }
  10718. callback.call(null, err, args);
  10719. });
  10720. }
  10721. }, callback);
  10722. }
  10723. else {
  10724. var results = {};
  10725. async.eachSeries(_keys(tasks), function (k, callback) {
  10726. tasks[k](function (err) {
  10727. var args = Array.prototype.slice.call(arguments, 1);
  10728. if (args.length <= 1) {
  10729. args = args[0];
  10730. }
  10731. results[k] = args;
  10732. callback(err);
  10733. });
  10734. }, function (err) {
  10735. callback(err, results);
  10736. });
  10737. }
  10738. };
  10739. async.iterator = function (tasks) {
  10740. var makeCallback = function (index) {
  10741. var fn = function () {
  10742. if (tasks.length) {
  10743. tasks[index].apply(null, arguments);
  10744. }
  10745. return fn.next();
  10746. };
  10747. fn.next = function () {
  10748. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  10749. };
  10750. return fn;
  10751. };
  10752. return makeCallback(0);
  10753. };
  10754. async.apply = function (fn) {
  10755. var args = Array.prototype.slice.call(arguments, 1);
  10756. return function () {
  10757. return fn.apply(
  10758. null, args.concat(Array.prototype.slice.call(arguments))
  10759. );
  10760. };
  10761. };
  10762. var _concat = function (eachfn, arr, fn, callback) {
  10763. var r = [];
  10764. eachfn(arr, function (x, cb) {
  10765. fn(x, function (err, y) {
  10766. r = r.concat(y || []);
  10767. cb(err);
  10768. });
  10769. }, function (err) {
  10770. callback(err, r);
  10771. });
  10772. };
  10773. async.concat = doParallel(_concat);
  10774. async.concatSeries = doSeries(_concat);
  10775. async.whilst = function (test, iterator, callback) {
  10776. if (test()) {
  10777. iterator(function (err) {
  10778. if (err) {
  10779. return callback(err);
  10780. }
  10781. async.whilst(test, iterator, callback);
  10782. });
  10783. }
  10784. else {
  10785. callback();
  10786. }
  10787. };
  10788. async.doWhilst = function (iterator, test, callback) {
  10789. iterator(function (err) {
  10790. if (err) {
  10791. return callback(err);
  10792. }
  10793. var args = Array.prototype.slice.call(arguments, 1);
  10794. if (test.apply(null, args)) {
  10795. async.doWhilst(iterator, test, callback);
  10796. }
  10797. else {
  10798. callback();
  10799. }
  10800. });
  10801. };
  10802. async.until = function (test, iterator, callback) {
  10803. if (!test()) {
  10804. iterator(function (err) {
  10805. if (err) {
  10806. return callback(err);
  10807. }
  10808. async.until(test, iterator, callback);
  10809. });
  10810. }
  10811. else {
  10812. callback();
  10813. }
  10814. };
  10815. async.doUntil = function (iterator, test, callback) {
  10816. iterator(function (err) {
  10817. if (err) {
  10818. return callback(err);
  10819. }
  10820. var args = Array.prototype.slice.call(arguments, 1);
  10821. if (!test.apply(null, args)) {
  10822. async.doUntil(iterator, test, callback);
  10823. }
  10824. else {
  10825. callback();
  10826. }
  10827. });
  10828. };
  10829. async.queue = function (worker, concurrency) {
  10830. if (concurrency === undefined) {
  10831. concurrency = 1;
  10832. }
  10833. function _insert(q, data, pos, callback) {
  10834. if (!q.started){
  10835. q.started = true;
  10836. }
  10837. if (!_isArray(data)) {
  10838. data = [data];
  10839. }
  10840. if(data.length == 0) {
  10841. // call drain immediately if there are no tasks
  10842. return async.setImmediate(function() {
  10843. if (q.drain) {
  10844. q.drain();
  10845. }
  10846. });
  10847. }
  10848. _each(data, function(task) {
  10849. var item = {
  10850. data: task,
  10851. callback: typeof callback === 'function' ? callback : null
  10852. };
  10853. if (pos) {
  10854. q.tasks.unshift(item);
  10855. } else {
  10856. q.tasks.push(item);
  10857. }
  10858. if (q.saturated && q.tasks.length === q.concurrency) {
  10859. q.saturated();
  10860. }
  10861. async.setImmediate(q.process);
  10862. });
  10863. }
  10864. var workers = 0;
  10865. var q = {
  10866. tasks: [],
  10867. concurrency: concurrency,
  10868. saturated: null,
  10869. empty: null,
  10870. drain: null,
  10871. started: false,
  10872. paused: false,
  10873. push: function (data, callback) {
  10874. _insert(q, data, false, callback);
  10875. },
  10876. kill: function () {
  10877. q.drain = null;
  10878. q.tasks = [];
  10879. },
  10880. unshift: function (data, callback) {
  10881. _insert(q, data, true, callback);
  10882. },
  10883. process: function () {
  10884. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  10885. var task = q.tasks.shift();
  10886. if (q.empty && q.tasks.length === 0) {
  10887. q.empty();
  10888. }
  10889. workers += 1;
  10890. var next = function () {
  10891. workers -= 1;
  10892. if (task.callback) {
  10893. task.callback.apply(task, arguments);
  10894. }
  10895. if (q.drain && q.tasks.length + workers === 0) {
  10896. q.drain();
  10897. }
  10898. q.process();
  10899. };
  10900. var cb = only_once(next);
  10901. worker(task.data, cb);
  10902. }
  10903. },
  10904. length: function () {
  10905. return q.tasks.length;
  10906. },
  10907. running: function () {
  10908. return workers;
  10909. },
  10910. idle: function() {
  10911. return q.tasks.length + workers === 0;
  10912. },
  10913. pause: function () {
  10914. if (q.paused === true) { return; }
  10915. q.paused = true;
  10916. q.process();
  10917. },
  10918. resume: function () {
  10919. if (q.paused === false) { return; }
  10920. q.paused = false;
  10921. q.process();
  10922. }
  10923. };
  10924. return q;
  10925. };
  10926. async.priorityQueue = function (worker, concurrency) {
  10927. function _compareTasks(a, b){
  10928. return a.priority - b.priority;
  10929. };
  10930. function _binarySearch(sequence, item, compare) {
  10931. var beg = -1,
  10932. end = sequence.length - 1;
  10933. while (beg < end) {
  10934. var mid = beg + ((end - beg + 1) >>> 1);
  10935. if (compare(item, sequence[mid]) >= 0) {
  10936. beg = mid;
  10937. } else {
  10938. end = mid - 1;
  10939. }
  10940. }
  10941. return beg;
  10942. }
  10943. function _insert(q, data, priority, callback) {
  10944. if (!q.started){
  10945. q.started = true;
  10946. }
  10947. if (!_isArray(data)) {
  10948. data = [data];
  10949. }
  10950. if(data.length == 0) {
  10951. // call drain immediately if there are no tasks
  10952. return async.setImmediate(function() {
  10953. if (q.drain) {
  10954. q.drain();
  10955. }
  10956. });
  10957. }
  10958. _each(data, function(task) {
  10959. var item = {
  10960. data: task,
  10961. priority: priority,
  10962. callback: typeof callback === 'function' ? callback : null
  10963. };
  10964. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  10965. if (q.saturated && q.tasks.length === q.concurrency) {
  10966. q.saturated();
  10967. }
  10968. async.setImmediate(q.process);
  10969. });
  10970. }
  10971. // Start with a normal queue
  10972. var q = async.queue(worker, concurrency);
  10973. // Override push to accept second parameter representing priority
  10974. q.push = function (data, priority, callback) {
  10975. _insert(q, data, priority, callback);
  10976. };
  10977. // Remove unshift function
  10978. delete q.unshift;
  10979. return q;
  10980. };
  10981. async.cargo = function (worker, payload) {
  10982. var working = false,
  10983. tasks = [];
  10984. var cargo = {
  10985. tasks: tasks,
  10986. payload: payload,
  10987. saturated: null,
  10988. empty: null,
  10989. drain: null,
  10990. drained: true,
  10991. push: function (data, callback) {
  10992. if (!_isArray(data)) {
  10993. data = [data];
  10994. }
  10995. _each(data, function(task) {
  10996. tasks.push({
  10997. data: task,
  10998. callback: typeof callback === 'function' ? callback : null
  10999. });
  11000. cargo.drained = false;
  11001. if (cargo.saturated && tasks.length === payload) {
  11002. cargo.saturated();
  11003. }
  11004. });
  11005. async.setImmediate(cargo.process);
  11006. },
  11007. process: function process() {
  11008. if (working) return;
  11009. if (tasks.length === 0) {
  11010. if(cargo.drain && !cargo.drained) cargo.drain();
  11011. cargo.drained = true;
  11012. return;
  11013. }
  11014. var ts = typeof payload === 'number'
  11015. ? tasks.splice(0, payload)
  11016. : tasks.splice(0, tasks.length);
  11017. var ds = _map(ts, function (task) {
  11018. return task.data;
  11019. });
  11020. if(cargo.empty) cargo.empty();
  11021. working = true;
  11022. worker(ds, function () {
  11023. working = false;
  11024. var args = arguments;
  11025. _each(ts, function (data) {
  11026. if (data.callback) {
  11027. data.callback.apply(null, args);
  11028. }
  11029. });
  11030. process();
  11031. });
  11032. },
  11033. length: function () {
  11034. return tasks.length;
  11035. },
  11036. running: function () {
  11037. return working;
  11038. }
  11039. };
  11040. return cargo;
  11041. };
  11042. var _console_fn = function (name) {
  11043. return function (fn) {
  11044. var args = Array.prototype.slice.call(arguments, 1);
  11045. fn.apply(null, args.concat([function (err) {
  11046. var args = Array.prototype.slice.call(arguments, 1);
  11047. if (typeof console !== 'undefined') {
  11048. if (err) {
  11049. if (console.error) {
  11050. console.error(err);
  11051. }
  11052. }
  11053. else if (console[name]) {
  11054. _each(args, function (x) {
  11055. console[name](x);
  11056. });
  11057. }
  11058. }
  11059. }]));
  11060. };
  11061. };
  11062. async.log = _console_fn('log');
  11063. async.dir = _console_fn('dir');
  11064. /*async.info = _console_fn('info');
  11065. async.warn = _console_fn('warn');
  11066. async.error = _console_fn('error');*/
  11067. async.memoize = function (fn, hasher) {
  11068. var memo = {};
  11069. var queues = {};
  11070. hasher = hasher || function (x) {
  11071. return x;
  11072. };
  11073. var memoized = function () {
  11074. var args = Array.prototype.slice.call(arguments);
  11075. var callback = args.pop();
  11076. var key = hasher.apply(null, args);
  11077. if (key in memo) {
  11078. async.nextTick(function () {
  11079. callback.apply(null, memo[key]);
  11080. });
  11081. }
  11082. else if (key in queues) {
  11083. queues[key].push(callback);
  11084. }
  11085. else {
  11086. queues[key] = [callback];
  11087. fn.apply(null, args.concat([function () {
  11088. memo[key] = arguments;
  11089. var q = queues[key];
  11090. delete queues[key];
  11091. for (var i = 0, l = q.length; i < l; i++) {
  11092. q[i].apply(null, arguments);
  11093. }
  11094. }]));
  11095. }
  11096. };
  11097. memoized.memo = memo;
  11098. memoized.unmemoized = fn;
  11099. return memoized;
  11100. };
  11101. async.unmemoize = function (fn) {
  11102. return function () {
  11103. return (fn.unmemoized || fn).apply(null, arguments);
  11104. };
  11105. };
  11106. async.times = function (count, iterator, callback) {
  11107. var counter = [];
  11108. for (var i = 0; i < count; i++) {
  11109. counter.push(i);
  11110. }
  11111. return async.map(counter, iterator, callback);
  11112. };
  11113. async.timesSeries = function (count, iterator, callback) {
  11114. var counter = [];
  11115. for (var i = 0; i < count; i++) {
  11116. counter.push(i);
  11117. }
  11118. return async.mapSeries(counter, iterator, callback);
  11119. };
  11120. async.seq = function (/* functions... */) {
  11121. var fns = arguments;
  11122. return function () {
  11123. var that = this;
  11124. var args = Array.prototype.slice.call(arguments);
  11125. var callback = args.pop();
  11126. async.reduce(fns, args, function (newargs, fn, cb) {
  11127. fn.apply(that, newargs.concat([function () {
  11128. var err = arguments[0];
  11129. var nextargs = Array.prototype.slice.call(arguments, 1);
  11130. cb(err, nextargs);
  11131. }]))
  11132. },
  11133. function (err, results) {
  11134. callback.apply(that, [err].concat(results));
  11135. });
  11136. };
  11137. };
  11138. async.compose = function (/* functions... */) {
  11139. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  11140. };
  11141. var _applyEach = function (eachfn, fns /*args...*/) {
  11142. var go = function () {
  11143. var that = this;
  11144. var args = Array.prototype.slice.call(arguments);
  11145. var callback = args.pop();
  11146. return eachfn(fns, function (fn, cb) {
  11147. fn.apply(that, args.concat([cb]));
  11148. },
  11149. callback);
  11150. };
  11151. if (arguments.length > 2) {
  11152. var args = Array.prototype.slice.call(arguments, 2);
  11153. return go.apply(this, args);
  11154. }
  11155. else {
  11156. return go;
  11157. }
  11158. };
  11159. async.applyEach = doParallel(_applyEach);
  11160. async.applyEachSeries = doSeries(_applyEach);
  11161. async.forever = function (fn, callback) {
  11162. function next(err) {
  11163. if (err) {
  11164. if (callback) {
  11165. return callback(err);
  11166. }
  11167. throw err;
  11168. }
  11169. fn(next);
  11170. }
  11171. next();
  11172. };
  11173. // Node.js
  11174. if (typeof module !== 'undefined' && module.exports) {
  11175. module.exports = async;
  11176. }
  11177. // AMD / RequireJS
  11178. else if (typeof define !== 'undefined' && define.amd) {
  11179. define([], function () {
  11180. return async;
  11181. });
  11182. }
  11183. // included directly via <script> tag
  11184. else {
  11185. root.async = async;
  11186. }
  11187. }());
  11188. }).call(this,require('_process'))
  11189. },{"_process":44}],43:[function(require,module,exports){
  11190. // Copyright Joyent, Inc. and other Node contributors.
  11191. //
  11192. // Permission is hereby granted, free of charge, to any person obtaining a
  11193. // copy of this software and associated documentation files (the
  11194. // "Software"), to deal in the Software without restriction, including
  11195. // without limitation the rights to use, copy, modify, merge, publish,
  11196. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11197. // persons to whom the Software is furnished to do so, subject to the
  11198. // following conditions:
  11199. //
  11200. // The above copyright notice and this permission notice shall be included
  11201. // in all copies or substantial portions of the Software.
  11202. //
  11203. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11204. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11205. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11206. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11207. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11208. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11209. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11210. function EventEmitter() {
  11211. this._events = this._events || {};
  11212. this._maxListeners = this._maxListeners || undefined;
  11213. }
  11214. module.exports = EventEmitter;
  11215. // Backwards-compat with node 0.10.x
  11216. EventEmitter.EventEmitter = EventEmitter;
  11217. EventEmitter.prototype._events = undefined;
  11218. EventEmitter.prototype._maxListeners = undefined;
  11219. // By default EventEmitters will print a warning if more than 10 listeners are
  11220. // added to it. This is a useful default which helps finding memory leaks.
  11221. EventEmitter.defaultMaxListeners = 10;
  11222. // Obviously not all Emitters should be limited to 10. This function allows
  11223. // that to be increased. Set to zero for unlimited.
  11224. EventEmitter.prototype.setMaxListeners = function(n) {
  11225. if (!isNumber(n) || n < 0 || isNaN(n))
  11226. throw TypeError('n must be a positive number');
  11227. this._maxListeners = n;
  11228. return this;
  11229. };
  11230. EventEmitter.prototype.emit = function(type) {
  11231. var er, handler, len, args, i, listeners;
  11232. if (!this._events)
  11233. this._events = {};
  11234. // If there is no 'error' event listener then throw.
  11235. if (type === 'error') {
  11236. if (!this._events.error ||
  11237. (isObject(this._events.error) && !this._events.error.length)) {
  11238. er = arguments[1];
  11239. if (er instanceof Error) {
  11240. throw er; // Unhandled 'error' event
  11241. }
  11242. throw TypeError('Uncaught, unspecified "error" event.');
  11243. }
  11244. }
  11245. handler = this._events[type];
  11246. if (isUndefined(handler))
  11247. return false;
  11248. if (isFunction(handler)) {
  11249. switch (arguments.length) {
  11250. // fast cases
  11251. case 1:
  11252. handler.call(this);
  11253. break;
  11254. case 2:
  11255. handler.call(this, arguments[1]);
  11256. break;
  11257. case 3:
  11258. handler.call(this, arguments[1], arguments[2]);
  11259. break;
  11260. // slower
  11261. default:
  11262. len = arguments.length;
  11263. args = new Array(len - 1);
  11264. for (i = 1; i < len; i++)
  11265. args[i - 1] = arguments[i];
  11266. handler.apply(this, args);
  11267. }
  11268. } else if (isObject(handler)) {
  11269. len = arguments.length;
  11270. args = new Array(len - 1);
  11271. for (i = 1; i < len; i++)
  11272. args[i - 1] = arguments[i];
  11273. listeners = handler.slice();
  11274. len = listeners.length;
  11275. for (i = 0; i < len; i++)
  11276. listeners[i].apply(this, args);
  11277. }
  11278. return true;
  11279. };
  11280. EventEmitter.prototype.addListener = function(type, listener) {
  11281. var m;
  11282. if (!isFunction(listener))
  11283. throw TypeError('listener must be a function');
  11284. if (!this._events)
  11285. this._events = {};
  11286. // To avoid recursion in the case that type === "newListener"! Before
  11287. // adding it to the listeners, first emit "newListener".
  11288. if (this._events.newListener)
  11289. this.emit('newListener', type,
  11290. isFunction(listener.listener) ?
  11291. listener.listener : listener);
  11292. if (!this._events[type])
  11293. // Optimize the case of one listener. Don't need the extra array object.
  11294. this._events[type] = listener;
  11295. else if (isObject(this._events[type]))
  11296. // If we've already got an array, just append.
  11297. this._events[type].push(listener);
  11298. else
  11299. // Adding the second element, need to change to array.
  11300. this._events[type] = [this._events[type], listener];
  11301. // Check for listener leak
  11302. if (isObject(this._events[type]) && !this._events[type].warned) {
  11303. var m;
  11304. if (!isUndefined(this._maxListeners)) {
  11305. m = this._maxListeners;
  11306. } else {
  11307. m = EventEmitter.defaultMaxListeners;
  11308. }
  11309. if (m && m > 0 && this._events[type].length > m) {
  11310. this._events[type].warned = true;
  11311. console.error('(node) warning: possible EventEmitter memory ' +
  11312. 'leak detected. %d listeners added. ' +
  11313. 'Use emitter.setMaxListeners() to increase limit.',
  11314. this._events[type].length);
  11315. if (typeof console.trace === 'function') {
  11316. // not supported in IE 10
  11317. console.trace();
  11318. }
  11319. }
  11320. }
  11321. return this;
  11322. };
  11323. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  11324. EventEmitter.prototype.once = function(type, listener) {
  11325. if (!isFunction(listener))
  11326. throw TypeError('listener must be a function');
  11327. var fired = false;
  11328. function g() {
  11329. this.removeListener(type, g);
  11330. if (!fired) {
  11331. fired = true;
  11332. listener.apply(this, arguments);
  11333. }
  11334. }
  11335. g.listener = listener;
  11336. this.on(type, g);
  11337. return this;
  11338. };
  11339. // emits a 'removeListener' event iff the listener was removed
  11340. EventEmitter.prototype.removeListener = function(type, listener) {
  11341. var list, position, length, i;
  11342. if (!isFunction(listener))
  11343. throw TypeError('listener must be a function');
  11344. if (!this._events || !this._events[type])
  11345. return this;
  11346. list = this._events[type];
  11347. length = list.length;
  11348. position = -1;
  11349. if (list === listener ||
  11350. (isFunction(list.listener) && list.listener === listener)) {
  11351. delete this._events[type];
  11352. if (this._events.removeListener)
  11353. this.emit('removeListener', type, listener);
  11354. } else if (isObject(list)) {
  11355. for (i = length; i-- > 0;) {
  11356. if (list[i] === listener ||
  11357. (list[i].listener && list[i].listener === listener)) {
  11358. position = i;
  11359. break;
  11360. }
  11361. }
  11362. if (position < 0)
  11363. return this;
  11364. if (list.length === 1) {
  11365. list.length = 0;
  11366. delete this._events[type];
  11367. } else {
  11368. list.splice(position, 1);
  11369. }
  11370. if (this._events.removeListener)
  11371. this.emit('removeListener', type, listener);
  11372. }
  11373. return this;
  11374. };
  11375. EventEmitter.prototype.removeAllListeners = function(type) {
  11376. var key, listeners;
  11377. if (!this._events)
  11378. return this;
  11379. // not listening for removeListener, no need to emit
  11380. if (!this._events.removeListener) {
  11381. if (arguments.length === 0)
  11382. this._events = {};
  11383. else if (this._events[type])
  11384. delete this._events[type];
  11385. return this;
  11386. }
  11387. // emit removeListener for all listeners on all events
  11388. if (arguments.length === 0) {
  11389. for (key in this._events) {
  11390. if (key === 'removeListener') continue;
  11391. this.removeAllListeners(key);
  11392. }
  11393. this.removeAllListeners('removeListener');
  11394. this._events = {};
  11395. return this;
  11396. }
  11397. listeners = this._events[type];
  11398. if (isFunction(listeners)) {
  11399. this.removeListener(type, listeners);
  11400. } else {
  11401. // LIFO order
  11402. while (listeners.length)
  11403. this.removeListener(type, listeners[listeners.length - 1]);
  11404. }
  11405. delete this._events[type];
  11406. return this;
  11407. };
  11408. EventEmitter.prototype.listeners = function(type) {
  11409. var ret;
  11410. if (!this._events || !this._events[type])
  11411. ret = [];
  11412. else if (isFunction(this._events[type]))
  11413. ret = [this._events[type]];
  11414. else
  11415. ret = this._events[type].slice();
  11416. return ret;
  11417. };
  11418. EventEmitter.listenerCount = function(emitter, type) {
  11419. var ret;
  11420. if (!emitter._events || !emitter._events[type])
  11421. ret = 0;
  11422. else if (isFunction(emitter._events[type]))
  11423. ret = 1;
  11424. else
  11425. ret = emitter._events[type].length;
  11426. return ret;
  11427. };
  11428. function isFunction(arg) {
  11429. return typeof arg === 'function';
  11430. }
  11431. function isNumber(arg) {
  11432. return typeof arg === 'number';
  11433. }
  11434. function isObject(arg) {
  11435. return typeof arg === 'object' && arg !== null;
  11436. }
  11437. function isUndefined(arg) {
  11438. return arg === void 0;
  11439. }
  11440. },{}],44:[function(require,module,exports){
  11441. // shim for using process in browser
  11442. var process = module.exports = {};
  11443. var queue = [];
  11444. var draining = false;
  11445. var currentQueue;
  11446. var queueIndex = -1;
  11447. function cleanUpNextTick() {
  11448. draining = false;
  11449. if (currentQueue.length) {
  11450. queue = currentQueue.concat(queue);
  11451. } else {
  11452. queueIndex = -1;
  11453. }
  11454. if (queue.length) {
  11455. drainQueue();
  11456. }
  11457. }
  11458. function drainQueue() {
  11459. if (draining) {
  11460. return;
  11461. }
  11462. var timeout = setTimeout(cleanUpNextTick);
  11463. draining = true;
  11464. var len = queue.length;
  11465. while(len) {
  11466. currentQueue = queue;
  11467. queue = [];
  11468. while (++queueIndex < len) {
  11469. if (currentQueue) {
  11470. currentQueue[queueIndex].run();
  11471. }
  11472. }
  11473. queueIndex = -1;
  11474. len = queue.length;
  11475. }
  11476. currentQueue = null;
  11477. draining = false;
  11478. clearTimeout(timeout);
  11479. }
  11480. process.nextTick = function (fun) {
  11481. var args = new Array(arguments.length - 1);
  11482. if (arguments.length > 1) {
  11483. for (var i = 1; i < arguments.length; i++) {
  11484. args[i - 1] = arguments[i];
  11485. }
  11486. }
  11487. queue.push(new Item(fun, args));
  11488. if (queue.length === 1 && !draining) {
  11489. setTimeout(drainQueue, 0);
  11490. }
  11491. };
  11492. // v8 likes predictible objects
  11493. function Item(fun, array) {
  11494. this.fun = fun;
  11495. this.array = array;
  11496. }
  11497. Item.prototype.run = function () {
  11498. this.fun.apply(null, this.array);
  11499. };
  11500. process.title = 'browser';
  11501. process.browser = true;
  11502. process.env = {};
  11503. process.argv = [];
  11504. process.version = ''; // empty string to avoid regexp issues
  11505. process.versions = {};
  11506. function noop() {}
  11507. process.on = noop;
  11508. process.addListener = noop;
  11509. process.once = noop;
  11510. process.off = noop;
  11511. process.removeListener = noop;
  11512. process.removeAllListeners = noop;
  11513. process.emit = noop;
  11514. process.binding = function (name) {
  11515. throw new Error('process.binding is not supported');
  11516. };
  11517. process.cwd = function () { return '/' };
  11518. process.chdir = function (dir) {
  11519. throw new Error('process.chdir is not supported');
  11520. };
  11521. process.umask = function() { return 0; };
  11522. },{}],45:[function(require,module,exports){
  11523. (function (process,global){
  11524. /*!
  11525. * @overview es6-promise - a tiny implementation of Promises/A+.
  11526. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  11527. * @license Licensed under MIT license
  11528. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  11529. * @version 3.0.2
  11530. */
  11531. (function() {
  11532. "use strict";
  11533. function lib$es6$promise$utils$$objectOrFunction(x) {
  11534. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  11535. }
  11536. function lib$es6$promise$utils$$isFunction(x) {
  11537. return typeof x === 'function';
  11538. }
  11539. function lib$es6$promise$utils$$isMaybeThenable(x) {
  11540. return typeof x === 'object' && x !== null;
  11541. }
  11542. var lib$es6$promise$utils$$_isArray;
  11543. if (!Array.isArray) {
  11544. lib$es6$promise$utils$$_isArray = function (x) {
  11545. return Object.prototype.toString.call(x) === '[object Array]';
  11546. };
  11547. } else {
  11548. lib$es6$promise$utils$$_isArray = Array.isArray;
  11549. }
  11550. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  11551. var lib$es6$promise$asap$$len = 0;
  11552. var lib$es6$promise$asap$$toString = {}.toString;
  11553. var lib$es6$promise$asap$$vertxNext;
  11554. var lib$es6$promise$asap$$customSchedulerFn;
  11555. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  11556. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  11557. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  11558. lib$es6$promise$asap$$len += 2;
  11559. if (lib$es6$promise$asap$$len === 2) {
  11560. // If len is 2, that means that we need to schedule an async flush.
  11561. // If additional callbacks are queued before the queue is flushed, they
  11562. // will be processed by this flush that we are scheduling.
  11563. if (lib$es6$promise$asap$$customSchedulerFn) {
  11564. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  11565. } else {
  11566. lib$es6$promise$asap$$scheduleFlush();
  11567. }
  11568. }
  11569. }
  11570. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  11571. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  11572. }
  11573. function lib$es6$promise$asap$$setAsap(asapFn) {
  11574. lib$es6$promise$asap$$asap = asapFn;
  11575. }
  11576. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  11577. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  11578. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  11579. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  11580. // test for web worker but not in IE10
  11581. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  11582. typeof importScripts !== 'undefined' &&
  11583. typeof MessageChannel !== 'undefined';
  11584. // node
  11585. function lib$es6$promise$asap$$useNextTick() {
  11586. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  11587. // see https://github.com/cujojs/when/issues/410 for details
  11588. return function() {
  11589. process.nextTick(lib$es6$promise$asap$$flush);
  11590. };
  11591. }
  11592. // vertx
  11593. function lib$es6$promise$asap$$useVertxTimer() {
  11594. return function() {
  11595. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  11596. };
  11597. }
  11598. function lib$es6$promise$asap$$useMutationObserver() {
  11599. var iterations = 0;
  11600. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  11601. var node = document.createTextNode('');
  11602. observer.observe(node, { characterData: true });
  11603. return function() {
  11604. node.data = (iterations = ++iterations % 2);
  11605. };
  11606. }
  11607. // web worker
  11608. function lib$es6$promise$asap$$useMessageChannel() {
  11609. var channel = new MessageChannel();
  11610. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  11611. return function () {
  11612. channel.port2.postMessage(0);
  11613. };
  11614. }
  11615. function lib$es6$promise$asap$$useSetTimeout() {
  11616. return function() {
  11617. setTimeout(lib$es6$promise$asap$$flush, 1);
  11618. };
  11619. }
  11620. var lib$es6$promise$asap$$queue = new Array(1000);
  11621. function lib$es6$promise$asap$$flush() {
  11622. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  11623. var callback = lib$es6$promise$asap$$queue[i];
  11624. var arg = lib$es6$promise$asap$$queue[i+1];
  11625. callback(arg);
  11626. lib$es6$promise$asap$$queue[i] = undefined;
  11627. lib$es6$promise$asap$$queue[i+1] = undefined;
  11628. }
  11629. lib$es6$promise$asap$$len = 0;
  11630. }
  11631. function lib$es6$promise$asap$$attemptVertx() {
  11632. try {
  11633. var r = require;
  11634. var vertx = r('vertx');
  11635. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  11636. return lib$es6$promise$asap$$useVertxTimer();
  11637. } catch(e) {
  11638. return lib$es6$promise$asap$$useSetTimeout();
  11639. }
  11640. }
  11641. var lib$es6$promise$asap$$scheduleFlush;
  11642. // Decide what async method to use to triggering processing of queued callbacks:
  11643. if (lib$es6$promise$asap$$isNode) {
  11644. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  11645. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  11646. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  11647. } else if (lib$es6$promise$asap$$isWorker) {
  11648. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  11649. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  11650. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  11651. } else {
  11652. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  11653. }
  11654. function lib$es6$promise$$internal$$noop() {}
  11655. var lib$es6$promise$$internal$$PENDING = void 0;
  11656. var lib$es6$promise$$internal$$FULFILLED = 1;
  11657. var lib$es6$promise$$internal$$REJECTED = 2;
  11658. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  11659. function lib$es6$promise$$internal$$selfFulfillment() {
  11660. return new TypeError("You cannot resolve a promise with itself");
  11661. }
  11662. function lib$es6$promise$$internal$$cannotReturnOwn() {
  11663. return new TypeError('A promises callback cannot return that same promise.');
  11664. }
  11665. function lib$es6$promise$$internal$$getThen(promise) {
  11666. try {
  11667. return promise.then;
  11668. } catch(error) {
  11669. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  11670. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  11671. }
  11672. }
  11673. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  11674. try {
  11675. then.call(value, fulfillmentHandler, rejectionHandler);
  11676. } catch(e) {
  11677. return e;
  11678. }
  11679. }
  11680. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  11681. lib$es6$promise$asap$$asap(function(promise) {
  11682. var sealed = false;
  11683. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  11684. if (sealed) { return; }
  11685. sealed = true;
  11686. if (thenable !== value) {
  11687. lib$es6$promise$$internal$$resolve(promise, value);
  11688. } else {
  11689. lib$es6$promise$$internal$$fulfill(promise, value);
  11690. }
  11691. }, function(reason) {
  11692. if (sealed) { return; }
  11693. sealed = true;
  11694. lib$es6$promise$$internal$$reject(promise, reason);
  11695. }, 'Settle: ' + (promise._label || ' unknown promise'));
  11696. if (!sealed && error) {
  11697. sealed = true;
  11698. lib$es6$promise$$internal$$reject(promise, error);
  11699. }
  11700. }, promise);
  11701. }
  11702. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  11703. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  11704. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  11705. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  11706. lib$es6$promise$$internal$$reject(promise, thenable._result);
  11707. } else {
  11708. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  11709. lib$es6$promise$$internal$$resolve(promise, value);
  11710. }, function(reason) {
  11711. lib$es6$promise$$internal$$reject(promise, reason);
  11712. });
  11713. }
  11714. }
  11715. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  11716. if (maybeThenable.constructor === promise.constructor) {
  11717. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  11718. } else {
  11719. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  11720. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  11721. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  11722. } else if (then === undefined) {
  11723. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  11724. } else if (lib$es6$promise$utils$$isFunction(then)) {
  11725. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  11726. } else {
  11727. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  11728. }
  11729. }
  11730. }
  11731. function lib$es6$promise$$internal$$resolve(promise, value) {
  11732. if (promise === value) {
  11733. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  11734. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  11735. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  11736. } else {
  11737. lib$es6$promise$$internal$$fulfill(promise, value);
  11738. }
  11739. }
  11740. function lib$es6$promise$$internal$$publishRejection(promise) {
  11741. if (promise._onerror) {
  11742. promise._onerror(promise._result);
  11743. }
  11744. lib$es6$promise$$internal$$publish(promise);
  11745. }
  11746. function lib$es6$promise$$internal$$fulfill(promise, value) {
  11747. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  11748. promise._result = value;
  11749. promise._state = lib$es6$promise$$internal$$FULFILLED;
  11750. if (promise._subscribers.length !== 0) {
  11751. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  11752. }
  11753. }
  11754. function lib$es6$promise$$internal$$reject(promise, reason) {
  11755. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  11756. promise._state = lib$es6$promise$$internal$$REJECTED;
  11757. promise._result = reason;
  11758. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  11759. }
  11760. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  11761. var subscribers = parent._subscribers;
  11762. var length = subscribers.length;
  11763. parent._onerror = null;
  11764. subscribers[length] = child;
  11765. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  11766. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  11767. if (length === 0 && parent._state) {
  11768. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  11769. }
  11770. }
  11771. function lib$es6$promise$$internal$$publish(promise) {
  11772. var subscribers = promise._subscribers;
  11773. var settled = promise._state;
  11774. if (subscribers.length === 0) { return; }
  11775. var child, callback, detail = promise._result;
  11776. for (var i = 0; i < subscribers.length; i += 3) {
  11777. child = subscribers[i];
  11778. callback = subscribers[i + settled];
  11779. if (child) {
  11780. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  11781. } else {
  11782. callback(detail);
  11783. }
  11784. }
  11785. promise._subscribers.length = 0;
  11786. }
  11787. function lib$es6$promise$$internal$$ErrorObject() {
  11788. this.error = null;
  11789. }
  11790. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  11791. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  11792. try {
  11793. return callback(detail);
  11794. } catch(e) {
  11795. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  11796. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  11797. }
  11798. }
  11799. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  11800. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  11801. value, error, succeeded, failed;
  11802. if (hasCallback) {
  11803. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  11804. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  11805. failed = true;
  11806. error = value.error;
  11807. value = null;
  11808. } else {
  11809. succeeded = true;
  11810. }
  11811. if (promise === value) {
  11812. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  11813. return;
  11814. }
  11815. } else {
  11816. value = detail;
  11817. succeeded = true;
  11818. }
  11819. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  11820. // noop
  11821. } else if (hasCallback && succeeded) {
  11822. lib$es6$promise$$internal$$resolve(promise, value);
  11823. } else if (failed) {
  11824. lib$es6$promise$$internal$$reject(promise, error);
  11825. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  11826. lib$es6$promise$$internal$$fulfill(promise, value);
  11827. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  11828. lib$es6$promise$$internal$$reject(promise, value);
  11829. }
  11830. }
  11831. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  11832. try {
  11833. resolver(function resolvePromise(value){
  11834. lib$es6$promise$$internal$$resolve(promise, value);
  11835. }, function rejectPromise(reason) {
  11836. lib$es6$promise$$internal$$reject(promise, reason);
  11837. });
  11838. } catch(e) {
  11839. lib$es6$promise$$internal$$reject(promise, e);
  11840. }
  11841. }
  11842. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  11843. var enumerator = this;
  11844. enumerator._instanceConstructor = Constructor;
  11845. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  11846. if (enumerator._validateInput(input)) {
  11847. enumerator._input = input;
  11848. enumerator.length = input.length;
  11849. enumerator._remaining = input.length;
  11850. enumerator._init();
  11851. if (enumerator.length === 0) {
  11852. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  11853. } else {
  11854. enumerator.length = enumerator.length || 0;
  11855. enumerator._enumerate();
  11856. if (enumerator._remaining === 0) {
  11857. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  11858. }
  11859. }
  11860. } else {
  11861. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  11862. }
  11863. }
  11864. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  11865. return lib$es6$promise$utils$$isArray(input);
  11866. };
  11867. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  11868. return new Error('Array Methods must be provided an Array');
  11869. };
  11870. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  11871. this._result = new Array(this.length);
  11872. };
  11873. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  11874. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  11875. var enumerator = this;
  11876. var length = enumerator.length;
  11877. var promise = enumerator.promise;
  11878. var input = enumerator._input;
  11879. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  11880. enumerator._eachEntry(input[i], i);
  11881. }
  11882. };
  11883. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  11884. var enumerator = this;
  11885. var c = enumerator._instanceConstructor;
  11886. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  11887. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  11888. entry._onerror = null;
  11889. enumerator._settledAt(entry._state, i, entry._result);
  11890. } else {
  11891. enumerator._willSettleAt(c.resolve(entry), i);
  11892. }
  11893. } else {
  11894. enumerator._remaining--;
  11895. enumerator._result[i] = entry;
  11896. }
  11897. };
  11898. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  11899. var enumerator = this;
  11900. var promise = enumerator.promise;
  11901. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  11902. enumerator._remaining--;
  11903. if (state === lib$es6$promise$$internal$$REJECTED) {
  11904. lib$es6$promise$$internal$$reject(promise, value);
  11905. } else {
  11906. enumerator._result[i] = value;
  11907. }
  11908. }
  11909. if (enumerator._remaining === 0) {
  11910. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  11911. }
  11912. };
  11913. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  11914. var enumerator = this;
  11915. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  11916. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  11917. }, function(reason) {
  11918. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  11919. });
  11920. };
  11921. function lib$es6$promise$promise$all$$all(entries) {
  11922. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  11923. }
  11924. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  11925. function lib$es6$promise$promise$race$$race(entries) {
  11926. /*jshint validthis:true */
  11927. var Constructor = this;
  11928. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  11929. if (!lib$es6$promise$utils$$isArray(entries)) {
  11930. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  11931. return promise;
  11932. }
  11933. var length = entries.length;
  11934. function onFulfillment(value) {
  11935. lib$es6$promise$$internal$$resolve(promise, value);
  11936. }
  11937. function onRejection(reason) {
  11938. lib$es6$promise$$internal$$reject(promise, reason);
  11939. }
  11940. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  11941. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  11942. }
  11943. return promise;
  11944. }
  11945. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  11946. function lib$es6$promise$promise$resolve$$resolve(object) {
  11947. /*jshint validthis:true */
  11948. var Constructor = this;
  11949. if (object && typeof object === 'object' && object.constructor === Constructor) {
  11950. return object;
  11951. }
  11952. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  11953. lib$es6$promise$$internal$$resolve(promise, object);
  11954. return promise;
  11955. }
  11956. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  11957. function lib$es6$promise$promise$reject$$reject(reason) {
  11958. /*jshint validthis:true */
  11959. var Constructor = this;
  11960. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  11961. lib$es6$promise$$internal$$reject(promise, reason);
  11962. return promise;
  11963. }
  11964. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  11965. var lib$es6$promise$promise$$counter = 0;
  11966. function lib$es6$promise$promise$$needsResolver() {
  11967. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  11968. }
  11969. function lib$es6$promise$promise$$needsNew() {
  11970. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  11971. }
  11972. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  11973. /**
  11974. Promise objects represent the eventual result of an asynchronous operation. The
  11975. primary way of interacting with a promise is through its `then` method, which
  11976. registers callbacks to receive either a promise's eventual value or the reason
  11977. why the promise cannot be fulfilled.
  11978. Terminology
  11979. -----------
  11980. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  11981. - `thenable` is an object or function that defines a `then` method.
  11982. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  11983. - `exception` is a value that is thrown using the throw statement.
  11984. - `reason` is a value that indicates why a promise was rejected.
  11985. - `settled` the final resting state of a promise, fulfilled or rejected.
  11986. A promise can be in one of three states: pending, fulfilled, or rejected.
  11987. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  11988. state. Promises that are rejected have a rejection reason and are in the
  11989. rejected state. A fulfillment value is never a thenable.
  11990. Promises can also be said to *resolve* a value. If this value is also a
  11991. promise, then the original promise's settled state will match the value's
  11992. settled state. So a promise that *resolves* a promise that rejects will
  11993. itself reject, and a promise that *resolves* a promise that fulfills will
  11994. itself fulfill.
  11995. Basic Usage:
  11996. ------------
  11997. ```js
  11998. var promise = new Promise(function(resolve, reject) {
  11999. // on success
  12000. resolve(value);
  12001. // on failure
  12002. reject(reason);
  12003. });
  12004. promise.then(function(value) {
  12005. // on fulfillment
  12006. }, function(reason) {
  12007. // on rejection
  12008. });
  12009. ```
  12010. Advanced Usage:
  12011. ---------------
  12012. Promises shine when abstracting away asynchronous interactions such as
  12013. `XMLHttpRequest`s.
  12014. ```js
  12015. function getJSON(url) {
  12016. return new Promise(function(resolve, reject){
  12017. var xhr = new XMLHttpRequest();
  12018. xhr.open('GET', url);
  12019. xhr.onreadystatechange = handler;
  12020. xhr.responseType = 'json';
  12021. xhr.setRequestHeader('Accept', 'application/json');
  12022. xhr.send();
  12023. function handler() {
  12024. if (this.readyState === this.DONE) {
  12025. if (this.status === 200) {
  12026. resolve(this.response);
  12027. } else {
  12028. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  12029. }
  12030. }
  12031. };
  12032. });
  12033. }
  12034. getJSON('/posts.json').then(function(json) {
  12035. // on fulfillment
  12036. }, function(reason) {
  12037. // on rejection
  12038. });
  12039. ```
  12040. Unlike callbacks, promises are great composable primitives.
  12041. ```js
  12042. Promise.all([
  12043. getJSON('/posts'),
  12044. getJSON('/comments')
  12045. ]).then(function(values){
  12046. values[0] // => postsJSON
  12047. values[1] // => commentsJSON
  12048. return values;
  12049. });
  12050. ```
  12051. @class Promise
  12052. @param {function} resolver
  12053. Useful for tooling.
  12054. @constructor
  12055. */
  12056. function lib$es6$promise$promise$$Promise(resolver) {
  12057. this._id = lib$es6$promise$promise$$counter++;
  12058. this._state = undefined;
  12059. this._result = undefined;
  12060. this._subscribers = [];
  12061. if (lib$es6$promise$$internal$$noop !== resolver) {
  12062. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  12063. lib$es6$promise$promise$$needsResolver();
  12064. }
  12065. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  12066. lib$es6$promise$promise$$needsNew();
  12067. }
  12068. lib$es6$promise$$internal$$initializePromise(this, resolver);
  12069. }
  12070. }
  12071. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  12072. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  12073. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  12074. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  12075. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  12076. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  12077. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  12078. lib$es6$promise$promise$$Promise.prototype = {
  12079. constructor: lib$es6$promise$promise$$Promise,
  12080. /**
  12081. The primary way of interacting with a promise is through its `then` method,
  12082. which registers callbacks to receive either a promise's eventual value or the
  12083. reason why the promise cannot be fulfilled.
  12084. ```js
  12085. findUser().then(function(user){
  12086. // user is available
  12087. }, function(reason){
  12088. // user is unavailable, and you are given the reason why
  12089. });
  12090. ```
  12091. Chaining
  12092. --------
  12093. The return value of `then` is itself a promise. This second, 'downstream'
  12094. promise is resolved with the return value of the first promise's fulfillment
  12095. or rejection handler, or rejected if the handler throws an exception.
  12096. ```js
  12097. findUser().then(function (user) {
  12098. return user.name;
  12099. }, function (reason) {
  12100. return 'default name';
  12101. }).then(function (userName) {
  12102. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  12103. // will be `'default name'`
  12104. });
  12105. findUser().then(function (user) {
  12106. throw new Error('Found user, but still unhappy');
  12107. }, function (reason) {
  12108. throw new Error('`findUser` rejected and we're unhappy');
  12109. }).then(function (value) {
  12110. // never reached
  12111. }, function (reason) {
  12112. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  12113. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  12114. });
  12115. ```
  12116. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  12117. ```js
  12118. findUser().then(function (user) {
  12119. throw new PedagogicalException('Upstream error');
  12120. }).then(function (value) {
  12121. // never reached
  12122. }).then(function (value) {
  12123. // never reached
  12124. }, function (reason) {
  12125. // The `PedgagocialException` is propagated all the way down to here
  12126. });
  12127. ```
  12128. Assimilation
  12129. ------------
  12130. Sometimes the value you want to propagate to a downstream promise can only be
  12131. retrieved asynchronously. This can be achieved by returning a promise in the
  12132. fulfillment or rejection handler. The downstream promise will then be pending
  12133. until the returned promise is settled. This is called *assimilation*.
  12134. ```js
  12135. findUser().then(function (user) {
  12136. return findCommentsByAuthor(user);
  12137. }).then(function (comments) {
  12138. // The user's comments are now available
  12139. });
  12140. ```
  12141. If the assimliated promise rejects, then the downstream promise will also reject.
  12142. ```js
  12143. findUser().then(function (user) {
  12144. return findCommentsByAuthor(user);
  12145. }).then(function (comments) {
  12146. // If `findCommentsByAuthor` fulfills, we'll have the value here
  12147. }, function (reason) {
  12148. // If `findCommentsByAuthor` rejects, we'll have the reason here
  12149. });
  12150. ```
  12151. Simple Example
  12152. --------------
  12153. Synchronous Example
  12154. ```javascript
  12155. var result;
  12156. try {
  12157. result = findResult();
  12158. // success
  12159. } catch(reason) {
  12160. // failure
  12161. }
  12162. ```
  12163. Errback Example
  12164. ```js
  12165. findResult(function(result, err){
  12166. if (err) {
  12167. // failure
  12168. } else {
  12169. // success
  12170. }
  12171. });
  12172. ```
  12173. Promise Example;
  12174. ```javascript
  12175. findResult().then(function(result){
  12176. // success
  12177. }, function(reason){
  12178. // failure
  12179. });
  12180. ```
  12181. Advanced Example
  12182. --------------
  12183. Synchronous Example
  12184. ```javascript
  12185. var author, books;
  12186. try {
  12187. author = findAuthor();
  12188. books = findBooksByAuthor(author);
  12189. // success
  12190. } catch(reason) {
  12191. // failure
  12192. }
  12193. ```
  12194. Errback Example
  12195. ```js
  12196. function foundBooks(books) {
  12197. }
  12198. function failure(reason) {
  12199. }
  12200. findAuthor(function(author, err){
  12201. if (err) {
  12202. failure(err);
  12203. // failure
  12204. } else {
  12205. try {
  12206. findBoooksByAuthor(author, function(books, err) {
  12207. if (err) {
  12208. failure(err);
  12209. } else {
  12210. try {
  12211. foundBooks(books);
  12212. } catch(reason) {
  12213. failure(reason);
  12214. }
  12215. }
  12216. });
  12217. } catch(error) {
  12218. failure(err);
  12219. }
  12220. // success
  12221. }
  12222. });
  12223. ```
  12224. Promise Example;
  12225. ```javascript
  12226. findAuthor().
  12227. then(findBooksByAuthor).
  12228. then(function(books){
  12229. // found books
  12230. }).catch(function(reason){
  12231. // something went wrong
  12232. });
  12233. ```
  12234. @method then
  12235. @param {Function} onFulfilled
  12236. @param {Function} onRejected
  12237. Useful for tooling.
  12238. @return {Promise}
  12239. */
  12240. then: function(onFulfillment, onRejection) {
  12241. var parent = this;
  12242. var state = parent._state;
  12243. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  12244. return this;
  12245. }
  12246. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  12247. var result = parent._result;
  12248. if (state) {
  12249. var callback = arguments[state - 1];
  12250. lib$es6$promise$asap$$asap(function(){
  12251. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  12252. });
  12253. } else {
  12254. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  12255. }
  12256. return child;
  12257. },
  12258. /**
  12259. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  12260. as the catch block of a try/catch statement.
  12261. ```js
  12262. function findAuthor(){
  12263. throw new Error('couldn't find that author');
  12264. }
  12265. // synchronous
  12266. try {
  12267. findAuthor();
  12268. } catch(reason) {
  12269. // something went wrong
  12270. }
  12271. // async with promises
  12272. findAuthor().catch(function(reason){
  12273. // something went wrong
  12274. });
  12275. ```
  12276. @method catch
  12277. @param {Function} onRejection
  12278. Useful for tooling.
  12279. @return {Promise}
  12280. */
  12281. 'catch': function(onRejection) {
  12282. return this.then(null, onRejection);
  12283. }
  12284. };
  12285. function lib$es6$promise$polyfill$$polyfill() {
  12286. var local;
  12287. if (typeof global !== 'undefined') {
  12288. local = global;
  12289. } else if (typeof self !== 'undefined') {
  12290. local = self;
  12291. } else {
  12292. try {
  12293. local = Function('return this')();
  12294. } catch (e) {
  12295. throw new Error('polyfill failed because global object is unavailable in this environment');
  12296. }
  12297. }
  12298. var P = local.Promise;
  12299. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  12300. return;
  12301. }
  12302. local.Promise = lib$es6$promise$promise$$default;
  12303. }
  12304. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  12305. var lib$es6$promise$umd$$ES6Promise = {
  12306. 'Promise': lib$es6$promise$promise$$default,
  12307. 'polyfill': lib$es6$promise$polyfill$$default
  12308. };
  12309. /* global define:true module:true window: true */
  12310. if (typeof define === 'function' && define['amd']) {
  12311. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  12312. } else if (typeof module !== 'undefined' && module['exports']) {
  12313. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  12314. } else if (typeof this !== 'undefined') {
  12315. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  12316. }
  12317. lib$es6$promise$polyfill$$default();
  12318. }).call(this);
  12319. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12320. },{"_process":44}],46:[function(require,module,exports){
  12321. /* Copyright @ 2015 Atlassian Pty Ltd
  12322. *
  12323. * Licensed under the Apache License, Version 2.0 (the "License");
  12324. * you may not use this file except in compliance with the License.
  12325. * You may obtain a copy of the License at
  12326. *
  12327. * http://www.apache.org/licenses/LICENSE-2.0
  12328. *
  12329. * Unless required by applicable law or agreed to in writing, software
  12330. * distributed under the License is distributed on an "AS IS" BASIS,
  12331. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12332. * See the License for the specific language governing permissions and
  12333. * limitations under the License.
  12334. */
  12335. /**
  12336. * Ordered log levels.
  12337. */
  12338. var levels = {
  12339. "trace": 0,
  12340. "debug": 1,
  12341. "info": 2,
  12342. "log": 3,
  12343. "warn": 4,
  12344. "error": 5
  12345. };
  12346. /**
  12347. * Parses Error's object stack trace and extracts information about the last
  12348. * caller before the log method was called.
  12349. * @returns JS object with info about the caller - method name, file location,
  12350. * line and column.
  12351. */
  12352. function getCallerInfo() {
  12353. var callerInfo = {
  12354. methodName: "",
  12355. fileLocation: "",
  12356. line: null,
  12357. column: null
  12358. };
  12359. //gets the part of the stack without the logger wrappers
  12360. var error = new Error();
  12361. var stack = error.stack? error.stack.split("\n") : [];
  12362. if(!stack || stack.length < 1) {
  12363. return callerInfo;
  12364. }
  12365. var m = null;
  12366. if(stack[3]) {
  12367. m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);
  12368. }
  12369. if(!m || m.length <= 4) {
  12370. //Firefox && Safari
  12371. if(stack[2].indexOf("log@") === 0){
  12372. //Safari
  12373. callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));
  12374. } else {
  12375. //Firefox
  12376. callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));
  12377. }
  12378. return callerInfo;
  12379. }
  12380. callerInfo.methodName = m[1];
  12381. callerInfo.fileLocation = m[2];
  12382. callerInfo.line = m[3];
  12383. callerInfo.column = m[4];
  12384. return callerInfo;
  12385. }
  12386. /**
  12387. * Logs messages using the transports and level from the logger.
  12388. * @param logger a logger instance.
  12389. * @param level the log level of the message. See the levels variable.
  12390. * @param arguments array with arguments that will be logged.
  12391. */
  12392. function log() {
  12393. var logger = arguments[0], level = arguments[1],
  12394. args = Array.prototype.slice.call(arguments, 2);
  12395. if(levels[level] <= logger.level) {
  12396. return;
  12397. }
  12398. var callerInfo = getCallerInfo();
  12399. for(var i = 0; i < logger.transports.length; i++) {
  12400. var t = logger.transports[i];
  12401. var l = t[level];
  12402. if(l && typeof(l) === "function") {
  12403. l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")
  12404. .apply(t, args);
  12405. }
  12406. }
  12407. }
  12408. /**
  12409. *
  12410. * Constructs new logger object.
  12411. * @param level the logging level for the new logger
  12412. * @param id optional identifier for the logger instance.
  12413. * @param transports optional list of handlers(objects) for the logs.
  12414. * The handlers must support - log, warn, error, debug, info, trace.
  12415. * @param format optional (NOT implemented) string.
  12416. */
  12417. function Logger(level, id, transports, format) {
  12418. this.id = id;
  12419. this.format = format;
  12420. if(!this.transports) {
  12421. this.transports = [];
  12422. this.transports.push(Logger.consoleTransport);
  12423. }
  12424. this.level = levels[level];
  12425. var methods = Object.keys(levels);
  12426. for(var i = 0; i < methods.length; i++){
  12427. this[methods[i]] =
  12428. log.bind(null, this, methods[i]);
  12429. }
  12430. }
  12431. /**
  12432. * Sets the log level for the logger.
  12433. * @param level the new log level.
  12434. */
  12435. Logger.prototype.setLevel = function (level) {
  12436. this.level = levels[level];
  12437. };
  12438. module.exports = Logger;
  12439. /**
  12440. * The default transport - console
  12441. */
  12442. Logger.consoleTransport = console;
  12443. /**
  12444. * Enum for the supported log levels.
  12445. */
  12446. Logger.levels = {
  12447. TRACE: "trace",
  12448. DEBUG: "debug",
  12449. INFO: "info",
  12450. LOG: "log",
  12451. WARN: "warn",
  12452. ERROR: "error"
  12453. };
  12454. },{}],47:[function(require,module,exports){
  12455. /* Copyright @ 2015 Atlassian Pty Ltd
  12456. *
  12457. * Licensed under the Apache License, Version 2.0 (the "License");
  12458. * you may not use this file except in compliance with the License.
  12459. * You may obtain a copy of the License at
  12460. *
  12461. * http://www.apache.org/licenses/LICENSE-2.0
  12462. *
  12463. * Unless required by applicable law or agreed to in writing, software
  12464. * distributed under the License is distributed on an "AS IS" BASIS,
  12465. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12466. * See the License for the specific language governing permissions and
  12467. * limitations under the License.
  12468. */
  12469. var Logger = require("./Logger");
  12470. /**
  12471. * Map with the created loggers with ID.
  12472. */
  12473. var idLoggers = {};
  12474. /**
  12475. * Array with the loggers without id.
  12476. */
  12477. var loggers = [];
  12478. /**
  12479. * Log level for the lbrary.
  12480. */
  12481. var curLevel = Logger.levels.TRACE;
  12482. module.exports = {
  12483. /**
  12484. * Creates new logger.
  12485. * @arguments the same as Logger constructor
  12486. */
  12487. getLogger: function(id, transports, format) {
  12488. var logger = new Logger(curLevel, id, transports, format);
  12489. if(id) {
  12490. idLoggers[id] = idLoggers[id] || [];
  12491. idLoggers[id].push(logger);
  12492. } else {
  12493. loggers.push(logger);
  12494. }
  12495. return logger;
  12496. },
  12497. /**
  12498. * Changes the log level for the existing loggers by id.
  12499. * @param level the new log level.
  12500. * @param id if specified the level will be changed only for loggers with the
  12501. * same id. Otherwise the operation will affect all loggers that don't
  12502. * have id.
  12503. */
  12504. setLogLevelById: function(level, id) {
  12505. var l = id? (idLoggers[id] || []) : loggers;
  12506. for(var i = 0; i < l.length; i++) {
  12507. l[i].setLevel(level);
  12508. }
  12509. },
  12510. /**
  12511. * Changes the log level for all existing loggers.
  12512. * @param level the new log level.
  12513. */
  12514. setLogLevel: function (level) {
  12515. curLevel = level;
  12516. var i = 0;
  12517. for(; i < loggers.length; i++) {
  12518. loggers[i].setLevel(level);
  12519. }
  12520. for(var id in idLoggers) {
  12521. var l = idLoggers[id] || [];
  12522. for(i = 0; i < l.length; i++) {
  12523. l[i].setLevel(level);
  12524. }
  12525. }
  12526. },
  12527. /**
  12528. * The supported log levels.
  12529. */
  12530. levels: Logger.levels
  12531. };
  12532. },{"./Logger":46}],48:[function(require,module,exports){
  12533. // Top level file is just a mixin of submodules & constants
  12534. 'use strict';
  12535. var assign = require('./lib/utils/common').assign;
  12536. var deflate = require('./lib/deflate');
  12537. var inflate = require('./lib/inflate');
  12538. var constants = require('./lib/zlib/constants');
  12539. var pako = {};
  12540. assign(pako, deflate, inflate, constants);
  12541. module.exports = pako;
  12542. },{"./lib/deflate":49,"./lib/inflate":50,"./lib/utils/common":51,"./lib/zlib/constants":54}],49:[function(require,module,exports){
  12543. 'use strict';
  12544. var zlib_deflate = require('./zlib/deflate.js');
  12545. var utils = require('./utils/common');
  12546. var strings = require('./utils/strings');
  12547. var msg = require('./zlib/messages');
  12548. var zstream = require('./zlib/zstream');
  12549. var toString = Object.prototype.toString;
  12550. /* Public constants ==========================================================*/
  12551. /* ===========================================================================*/
  12552. var Z_NO_FLUSH = 0;
  12553. var Z_FINISH = 4;
  12554. var Z_OK = 0;
  12555. var Z_STREAM_END = 1;
  12556. var Z_SYNC_FLUSH = 2;
  12557. var Z_DEFAULT_COMPRESSION = -1;
  12558. var Z_DEFAULT_STRATEGY = 0;
  12559. var Z_DEFLATED = 8;
  12560. /* ===========================================================================*/
  12561. /**
  12562. * class Deflate
  12563. *
  12564. * Generic JS-style wrapper for zlib calls. If you don't need
  12565. * streaming behaviour - use more simple functions: [[deflate]],
  12566. * [[deflateRaw]] and [[gzip]].
  12567. **/
  12568. /* internal
  12569. * Deflate.chunks -> Array
  12570. *
  12571. * Chunks of output data, if [[Deflate#onData]] not overriden.
  12572. **/
  12573. /**
  12574. * Deflate.result -> Uint8Array|Array
  12575. *
  12576. * Compressed result, generated by default [[Deflate#onData]]
  12577. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  12578. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  12579. * push a chunk with explicit flush (call [[Deflate#push]] with
  12580. * `Z_SYNC_FLUSH` param).
  12581. **/
  12582. /**
  12583. * Deflate.err -> Number
  12584. *
  12585. * Error code after deflate finished. 0 (Z_OK) on success.
  12586. * You will not need it in real life, because deflate errors
  12587. * are possible only on wrong options or bad `onData` / `onEnd`
  12588. * custom handlers.
  12589. **/
  12590. /**
  12591. * Deflate.msg -> String
  12592. *
  12593. * Error message, if [[Deflate.err]] != 0
  12594. **/
  12595. /**
  12596. * new Deflate(options)
  12597. * - options (Object): zlib deflate options.
  12598. *
  12599. * Creates new deflator instance with specified params. Throws exception
  12600. * on bad params. Supported options:
  12601. *
  12602. * - `level`
  12603. * - `windowBits`
  12604. * - `memLevel`
  12605. * - `strategy`
  12606. *
  12607. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  12608. * for more information on these.
  12609. *
  12610. * Additional options, for internal needs:
  12611. *
  12612. * - `chunkSize` - size of generated data chunks (16K by default)
  12613. * - `raw` (Boolean) - do raw deflate
  12614. * - `gzip` (Boolean) - create gzip wrapper
  12615. * - `to` (String) - if equal to 'string', then result will be "binary string"
  12616. * (each char code [0..255])
  12617. * - `header` (Object) - custom header for gzip
  12618. * - `text` (Boolean) - true if compressed data believed to be text
  12619. * - `time` (Number) - modification time, unix timestamp
  12620. * - `os` (Number) - operation system code
  12621. * - `extra` (Array) - array of bytes with extra data (max 65536)
  12622. * - `name` (String) - file name (binary string)
  12623. * - `comment` (String) - comment (binary string)
  12624. * - `hcrc` (Boolean) - true if header crc should be added
  12625. *
  12626. * ##### Example:
  12627. *
  12628. * ```javascript
  12629. * var pako = require('pako')
  12630. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  12631. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  12632. *
  12633. * var deflate = new pako.Deflate({ level: 3});
  12634. *
  12635. * deflate.push(chunk1, false);
  12636. * deflate.push(chunk2, true); // true -> last chunk
  12637. *
  12638. * if (deflate.err) { throw new Error(deflate.err); }
  12639. *
  12640. * console.log(deflate.result);
  12641. * ```
  12642. **/
  12643. var Deflate = function(options) {
  12644. this.options = utils.assign({
  12645. level: Z_DEFAULT_COMPRESSION,
  12646. method: Z_DEFLATED,
  12647. chunkSize: 16384,
  12648. windowBits: 15,
  12649. memLevel: 8,
  12650. strategy: Z_DEFAULT_STRATEGY,
  12651. to: ''
  12652. }, options || {});
  12653. var opt = this.options;
  12654. if (opt.raw && (opt.windowBits > 0)) {
  12655. opt.windowBits = -opt.windowBits;
  12656. }
  12657. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  12658. opt.windowBits += 16;
  12659. }
  12660. this.err = 0; // error code, if happens (0 = Z_OK)
  12661. this.msg = ''; // error message
  12662. this.ended = false; // used to avoid multiple onEnd() calls
  12663. this.chunks = []; // chunks of compressed data
  12664. this.strm = new zstream();
  12665. this.strm.avail_out = 0;
  12666. var status = zlib_deflate.deflateInit2(
  12667. this.strm,
  12668. opt.level,
  12669. opt.method,
  12670. opt.windowBits,
  12671. opt.memLevel,
  12672. opt.strategy
  12673. );
  12674. if (status !== Z_OK) {
  12675. throw new Error(msg[status]);
  12676. }
  12677. if (opt.header) {
  12678. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  12679. }
  12680. };
  12681. /**
  12682. * Deflate#push(data[, mode]) -> Boolean
  12683. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  12684. * converted to utf8 byte sequence.
  12685. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  12686. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  12687. *
  12688. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  12689. * new compressed chunks. Returns `true` on success. The last data block must have
  12690. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  12691. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  12692. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  12693. *
  12694. * On fail call [[Deflate#onEnd]] with error code and return false.
  12695. *
  12696. * We strongly recommend to use `Uint8Array` on input for best speed (output
  12697. * array format is detected automatically). Also, don't skip last param and always
  12698. * use the same type in your code (boolean or number). That will improve JS speed.
  12699. *
  12700. * For regular `Array`-s make sure all elements are [0..255].
  12701. *
  12702. * ##### Example
  12703. *
  12704. * ```javascript
  12705. * push(chunk, false); // push one of data chunks
  12706. * ...
  12707. * push(chunk, true); // push last chunk
  12708. * ```
  12709. **/
  12710. Deflate.prototype.push = function(data, mode) {
  12711. var strm = this.strm;
  12712. var chunkSize = this.options.chunkSize;
  12713. var status, _mode;
  12714. if (this.ended) { return false; }
  12715. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  12716. // Convert data if needed
  12717. if (typeof data === 'string') {
  12718. // If we need to compress text, change encoding to utf8.
  12719. strm.input = strings.string2buf(data);
  12720. } else if (toString.call(data) === '[object ArrayBuffer]') {
  12721. strm.input = new Uint8Array(data);
  12722. } else {
  12723. strm.input = data;
  12724. }
  12725. strm.next_in = 0;
  12726. strm.avail_in = strm.input.length;
  12727. do {
  12728. if (strm.avail_out === 0) {
  12729. strm.output = new utils.Buf8(chunkSize);
  12730. strm.next_out = 0;
  12731. strm.avail_out = chunkSize;
  12732. }
  12733. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  12734. if (status !== Z_STREAM_END && status !== Z_OK) {
  12735. this.onEnd(status);
  12736. this.ended = true;
  12737. return false;
  12738. }
  12739. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  12740. if (this.options.to === 'string') {
  12741. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  12742. } else {
  12743. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  12744. }
  12745. }
  12746. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  12747. // Finalize on the last chunk.
  12748. if (_mode === Z_FINISH) {
  12749. status = zlib_deflate.deflateEnd(this.strm);
  12750. this.onEnd(status);
  12751. this.ended = true;
  12752. return status === Z_OK;
  12753. }
  12754. // callback interim results if Z_SYNC_FLUSH.
  12755. if (_mode === Z_SYNC_FLUSH) {
  12756. this.onEnd(Z_OK);
  12757. strm.avail_out = 0;
  12758. return true;
  12759. }
  12760. return true;
  12761. };
  12762. /**
  12763. * Deflate#onData(chunk) -> Void
  12764. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  12765. * on js engine support. When string output requested, each chunk
  12766. * will be string.
  12767. *
  12768. * By default, stores data blocks in `chunks[]` property and glue
  12769. * those in `onEnd`. Override this handler, if you need another behaviour.
  12770. **/
  12771. Deflate.prototype.onData = function(chunk) {
  12772. this.chunks.push(chunk);
  12773. };
  12774. /**
  12775. * Deflate#onEnd(status) -> Void
  12776. * - status (Number): deflate status. 0 (Z_OK) on success,
  12777. * other if not.
  12778. *
  12779. * Called once after you tell deflate that the input stream is
  12780. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  12781. * or if an error happened. By default - join collected chunks,
  12782. * free memory and fill `results` / `err` properties.
  12783. **/
  12784. Deflate.prototype.onEnd = function(status) {
  12785. // On success - join
  12786. if (status === Z_OK) {
  12787. if (this.options.to === 'string') {
  12788. this.result = this.chunks.join('');
  12789. } else {
  12790. this.result = utils.flattenChunks(this.chunks);
  12791. }
  12792. }
  12793. this.chunks = [];
  12794. this.err = status;
  12795. this.msg = this.strm.msg;
  12796. };
  12797. /**
  12798. * deflate(data[, options]) -> Uint8Array|Array|String
  12799. * - data (Uint8Array|Array|String): input data to compress.
  12800. * - options (Object): zlib deflate options.
  12801. *
  12802. * Compress `data` with deflate alrorythm and `options`.
  12803. *
  12804. * Supported options are:
  12805. *
  12806. * - level
  12807. * - windowBits
  12808. * - memLevel
  12809. * - strategy
  12810. *
  12811. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  12812. * for more information on these.
  12813. *
  12814. * Sugar (options):
  12815. *
  12816. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  12817. * negative windowBits implicitly.
  12818. * - `to` (String) - if equal to 'string', then result will be "binary string"
  12819. * (each char code [0..255])
  12820. *
  12821. * ##### Example:
  12822. *
  12823. * ```javascript
  12824. * var pako = require('pako')
  12825. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  12826. *
  12827. * console.log(pako.deflate(data));
  12828. * ```
  12829. **/
  12830. function deflate(input, options) {
  12831. var deflator = new Deflate(options);
  12832. deflator.push(input, true);
  12833. // That will never happens, if you don't cheat with options :)
  12834. if (deflator.err) { throw deflator.msg; }
  12835. return deflator.result;
  12836. }
  12837. /**
  12838. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  12839. * - data (Uint8Array|Array|String): input data to compress.
  12840. * - options (Object): zlib deflate options.
  12841. *
  12842. * The same as [[deflate]], but creates raw data, without wrapper
  12843. * (header and adler32 crc).
  12844. **/
  12845. function deflateRaw(input, options) {
  12846. options = options || {};
  12847. options.raw = true;
  12848. return deflate(input, options);
  12849. }
  12850. /**
  12851. * gzip(data[, options]) -> Uint8Array|Array|String
  12852. * - data (Uint8Array|Array|String): input data to compress.
  12853. * - options (Object): zlib deflate options.
  12854. *
  12855. * The same as [[deflate]], but create gzip wrapper instead of
  12856. * deflate one.
  12857. **/
  12858. function gzip(input, options) {
  12859. options = options || {};
  12860. options.gzip = true;
  12861. return deflate(input, options);
  12862. }
  12863. exports.Deflate = Deflate;
  12864. exports.deflate = deflate;
  12865. exports.deflateRaw = deflateRaw;
  12866. exports.gzip = gzip;
  12867. },{"./utils/common":51,"./utils/strings":52,"./zlib/deflate.js":56,"./zlib/messages":61,"./zlib/zstream":63}],50:[function(require,module,exports){
  12868. 'use strict';
  12869. var zlib_inflate = require('./zlib/inflate.js');
  12870. var utils = require('./utils/common');
  12871. var strings = require('./utils/strings');
  12872. var c = require('./zlib/constants');
  12873. var msg = require('./zlib/messages');
  12874. var zstream = require('./zlib/zstream');
  12875. var gzheader = require('./zlib/gzheader');
  12876. var toString = Object.prototype.toString;
  12877. /**
  12878. * class Inflate
  12879. *
  12880. * Generic JS-style wrapper for zlib calls. If you don't need
  12881. * streaming behaviour - use more simple functions: [[inflate]]
  12882. * and [[inflateRaw]].
  12883. **/
  12884. /* internal
  12885. * inflate.chunks -> Array
  12886. *
  12887. * Chunks of output data, if [[Inflate#onData]] not overriden.
  12888. **/
  12889. /**
  12890. * Inflate.result -> Uint8Array|Array|String
  12891. *
  12892. * Uncompressed result, generated by default [[Inflate#onData]]
  12893. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  12894. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  12895. * push a chunk with explicit flush (call [[Inflate#push]] with
  12896. * `Z_SYNC_FLUSH` param).
  12897. **/
  12898. /**
  12899. * Inflate.err -> Number
  12900. *
  12901. * Error code after inflate finished. 0 (Z_OK) on success.
  12902. * Should be checked if broken data possible.
  12903. **/
  12904. /**
  12905. * Inflate.msg -> String
  12906. *
  12907. * Error message, if [[Inflate.err]] != 0
  12908. **/
  12909. /**
  12910. * new Inflate(options)
  12911. * - options (Object): zlib inflate options.
  12912. *
  12913. * Creates new inflator instance with specified params. Throws exception
  12914. * on bad params. Supported options:
  12915. *
  12916. * - `windowBits`
  12917. *
  12918. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  12919. * for more information on these.
  12920. *
  12921. * Additional options, for internal needs:
  12922. *
  12923. * - `chunkSize` - size of generated data chunks (16K by default)
  12924. * - `raw` (Boolean) - do raw inflate
  12925. * - `to` (String) - if equal to 'string', then result will be converted
  12926. * from utf8 to utf16 (javascript) string. When string output requested,
  12927. * chunk length can differ from `chunkSize`, depending on content.
  12928. *
  12929. * By default, when no options set, autodetect deflate/gzip data format via
  12930. * wrapper header.
  12931. *
  12932. * ##### Example:
  12933. *
  12934. * ```javascript
  12935. * var pako = require('pako')
  12936. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  12937. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  12938. *
  12939. * var inflate = new pako.Inflate({ level: 3});
  12940. *
  12941. * inflate.push(chunk1, false);
  12942. * inflate.push(chunk2, true); // true -> last chunk
  12943. *
  12944. * if (inflate.err) { throw new Error(inflate.err); }
  12945. *
  12946. * console.log(inflate.result);
  12947. * ```
  12948. **/
  12949. var Inflate = function(options) {
  12950. this.options = utils.assign({
  12951. chunkSize: 16384,
  12952. windowBits: 0,
  12953. to: ''
  12954. }, options || {});
  12955. var opt = this.options;
  12956. // Force window size for `raw` data, if not set directly,
  12957. // because we have no header for autodetect.
  12958. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  12959. opt.windowBits = -opt.windowBits;
  12960. if (opt.windowBits === 0) { opt.windowBits = -15; }
  12961. }
  12962. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  12963. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  12964. !(options && options.windowBits)) {
  12965. opt.windowBits += 32;
  12966. }
  12967. // Gzip header has no info about windows size, we can do autodetect only
  12968. // for deflate. So, if window size not set, force it to max when gzip possible
  12969. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  12970. // bit 3 (16) -> gzipped data
  12971. // bit 4 (32) -> autodetect gzip/deflate
  12972. if ((opt.windowBits & 15) === 0) {
  12973. opt.windowBits |= 15;
  12974. }
  12975. }
  12976. this.err = 0; // error code, if happens (0 = Z_OK)
  12977. this.msg = ''; // error message
  12978. this.ended = false; // used to avoid multiple onEnd() calls
  12979. this.chunks = []; // chunks of compressed data
  12980. this.strm = new zstream();
  12981. this.strm.avail_out = 0;
  12982. var status = zlib_inflate.inflateInit2(
  12983. this.strm,
  12984. opt.windowBits
  12985. );
  12986. if (status !== c.Z_OK) {
  12987. throw new Error(msg[status]);
  12988. }
  12989. this.header = new gzheader();
  12990. zlib_inflate.inflateGetHeader(this.strm, this.header);
  12991. };
  12992. /**
  12993. * Inflate#push(data[, mode]) -> Boolean
  12994. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  12995. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  12996. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  12997. *
  12998. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  12999. * new output chunks. Returns `true` on success. The last data block must have
  13000. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  13001. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  13002. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  13003. *
  13004. * On fail call [[Inflate#onEnd]] with error code and return false.
  13005. *
  13006. * We strongly recommend to use `Uint8Array` on input for best speed (output
  13007. * format is detected automatically). Also, don't skip last param and always
  13008. * use the same type in your code (boolean or number). That will improve JS speed.
  13009. *
  13010. * For regular `Array`-s make sure all elements are [0..255].
  13011. *
  13012. * ##### Example
  13013. *
  13014. * ```javascript
  13015. * push(chunk, false); // push one of data chunks
  13016. * ...
  13017. * push(chunk, true); // push last chunk
  13018. * ```
  13019. **/
  13020. Inflate.prototype.push = function(data, mode) {
  13021. var strm = this.strm;
  13022. var chunkSize = this.options.chunkSize;
  13023. var status, _mode;
  13024. var next_out_utf8, tail, utf8str;
  13025. // Flag to properly process Z_BUF_ERROR on testing inflate call
  13026. // when we check that all output data was flushed.
  13027. var allowBufError = false;
  13028. if (this.ended) { return false; }
  13029. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  13030. // Convert data if needed
  13031. if (typeof data === 'string') {
  13032. // Only binary strings can be decompressed on practice
  13033. strm.input = strings.binstring2buf(data);
  13034. } else if (toString.call(data) === '[object ArrayBuffer]') {
  13035. strm.input = new Uint8Array(data);
  13036. } else {
  13037. strm.input = data;
  13038. }
  13039. strm.next_in = 0;
  13040. strm.avail_in = strm.input.length;
  13041. do {
  13042. if (strm.avail_out === 0) {
  13043. strm.output = new utils.Buf8(chunkSize);
  13044. strm.next_out = 0;
  13045. strm.avail_out = chunkSize;
  13046. }
  13047. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  13048. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  13049. status = c.Z_OK;
  13050. allowBufError = false;
  13051. }
  13052. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  13053. this.onEnd(status);
  13054. this.ended = true;
  13055. return false;
  13056. }
  13057. if (strm.next_out) {
  13058. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  13059. if (this.options.to === 'string') {
  13060. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  13061. tail = strm.next_out - next_out_utf8;
  13062. utf8str = strings.buf2string(strm.output, next_out_utf8);
  13063. // move tail
  13064. strm.next_out = tail;
  13065. strm.avail_out = chunkSize - tail;
  13066. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  13067. this.onData(utf8str);
  13068. } else {
  13069. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  13070. }
  13071. }
  13072. }
  13073. // When no more input data, we should check that internal inflate buffers
  13074. // are flushed. The only way to do it when avail_out = 0 - run one more
  13075. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  13076. // Here we set flag to process this error properly.
  13077. //
  13078. // NOTE. Deflate does not return error in this case and does not needs such
  13079. // logic.
  13080. if (strm.avail_in === 0 && strm.avail_out === 0) {
  13081. allowBufError = true;
  13082. }
  13083. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  13084. if (status === c.Z_STREAM_END) {
  13085. _mode = c.Z_FINISH;
  13086. }
  13087. // Finalize on the last chunk.
  13088. if (_mode === c.Z_FINISH) {
  13089. status = zlib_inflate.inflateEnd(this.strm);
  13090. this.onEnd(status);
  13091. this.ended = true;
  13092. return status === c.Z_OK;
  13093. }
  13094. // callback interim results if Z_SYNC_FLUSH.
  13095. if (_mode === c.Z_SYNC_FLUSH) {
  13096. this.onEnd(c.Z_OK);
  13097. strm.avail_out = 0;
  13098. return true;
  13099. }
  13100. return true;
  13101. };
  13102. /**
  13103. * Inflate#onData(chunk) -> Void
  13104. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  13105. * on js engine support. When string output requested, each chunk
  13106. * will be string.
  13107. *
  13108. * By default, stores data blocks in `chunks[]` property and glue
  13109. * those in `onEnd`. Override this handler, if you need another behaviour.
  13110. **/
  13111. Inflate.prototype.onData = function(chunk) {
  13112. this.chunks.push(chunk);
  13113. };
  13114. /**
  13115. * Inflate#onEnd(status) -> Void
  13116. * - status (Number): inflate status. 0 (Z_OK) on success,
  13117. * other if not.
  13118. *
  13119. * Called either after you tell inflate that the input stream is
  13120. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  13121. * or if an error happened. By default - join collected chunks,
  13122. * free memory and fill `results` / `err` properties.
  13123. **/
  13124. Inflate.prototype.onEnd = function(status) {
  13125. // On success - join
  13126. if (status === c.Z_OK) {
  13127. if (this.options.to === 'string') {
  13128. // Glue & convert here, until we teach pako to send
  13129. // utf8 alligned strings to onData
  13130. this.result = this.chunks.join('');
  13131. } else {
  13132. this.result = utils.flattenChunks(this.chunks);
  13133. }
  13134. }
  13135. this.chunks = [];
  13136. this.err = status;
  13137. this.msg = this.strm.msg;
  13138. };
  13139. /**
  13140. * inflate(data[, options]) -> Uint8Array|Array|String
  13141. * - data (Uint8Array|Array|String): input data to decompress.
  13142. * - options (Object): zlib inflate options.
  13143. *
  13144. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  13145. * format via wrapper header by default. That's why we don't provide
  13146. * separate `ungzip` method.
  13147. *
  13148. * Supported options are:
  13149. *
  13150. * - windowBits
  13151. *
  13152. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13153. * for more information.
  13154. *
  13155. * Sugar (options):
  13156. *
  13157. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  13158. * negative windowBits implicitly.
  13159. * - `to` (String) - if equal to 'string', then result will be converted
  13160. * from utf8 to utf16 (javascript) string. When string output requested,
  13161. * chunk length can differ from `chunkSize`, depending on content.
  13162. *
  13163. *
  13164. * ##### Example:
  13165. *
  13166. * ```javascript
  13167. * var pako = require('pako')
  13168. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  13169. * , output;
  13170. *
  13171. * try {
  13172. * output = pako.inflate(input);
  13173. * } catch (err)
  13174. * console.log(err);
  13175. * }
  13176. * ```
  13177. **/
  13178. function inflate(input, options) {
  13179. var inflator = new Inflate(options);
  13180. inflator.push(input, true);
  13181. // That will never happens, if you don't cheat with options :)
  13182. if (inflator.err) { throw inflator.msg; }
  13183. return inflator.result;
  13184. }
  13185. /**
  13186. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  13187. * - data (Uint8Array|Array|String): input data to decompress.
  13188. * - options (Object): zlib inflate options.
  13189. *
  13190. * The same as [[inflate]], but creates raw data, without wrapper
  13191. * (header and adler32 crc).
  13192. **/
  13193. function inflateRaw(input, options) {
  13194. options = options || {};
  13195. options.raw = true;
  13196. return inflate(input, options);
  13197. }
  13198. /**
  13199. * ungzip(data[, options]) -> Uint8Array|Array|String
  13200. * - data (Uint8Array|Array|String): input data to decompress.
  13201. * - options (Object): zlib inflate options.
  13202. *
  13203. * Just shortcut to [[inflate]], because it autodetects format
  13204. * by header.content. Done for convenience.
  13205. **/
  13206. exports.Inflate = Inflate;
  13207. exports.inflate = inflate;
  13208. exports.inflateRaw = inflateRaw;
  13209. exports.ungzip = inflate;
  13210. },{"./utils/common":51,"./utils/strings":52,"./zlib/constants":54,"./zlib/gzheader":57,"./zlib/inflate.js":59,"./zlib/messages":61,"./zlib/zstream":63}],51:[function(require,module,exports){
  13211. 'use strict';
  13212. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  13213. (typeof Uint16Array !== 'undefined') &&
  13214. (typeof Int32Array !== 'undefined');
  13215. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  13216. var sources = Array.prototype.slice.call(arguments, 1);
  13217. while (sources.length) {
  13218. var source = sources.shift();
  13219. if (!source) { continue; }
  13220. if (typeof source !== 'object') {
  13221. throw new TypeError(source + 'must be non-object');
  13222. }
  13223. for (var p in source) {
  13224. if (source.hasOwnProperty(p)) {
  13225. obj[p] = source[p];
  13226. }
  13227. }
  13228. }
  13229. return obj;
  13230. };
  13231. // reduce buffer size, avoiding mem copy
  13232. exports.shrinkBuf = function (buf, size) {
  13233. if (buf.length === size) { return buf; }
  13234. if (buf.subarray) { return buf.subarray(0, size); }
  13235. buf.length = size;
  13236. return buf;
  13237. };
  13238. var fnTyped = {
  13239. arraySet: function (dest, src, src_offs, len, dest_offs) {
  13240. if (src.subarray && dest.subarray) {
  13241. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  13242. return;
  13243. }
  13244. // Fallback to ordinary array
  13245. for (var i=0; i<len; i++) {
  13246. dest[dest_offs + i] = src[src_offs + i];
  13247. }
  13248. },
  13249. // Join array of chunks to single array.
  13250. flattenChunks: function(chunks) {
  13251. var i, l, len, pos, chunk, result;
  13252. // calculate data length
  13253. len = 0;
  13254. for (i=0, l=chunks.length; i<l; i++) {
  13255. len += chunks[i].length;
  13256. }
  13257. // join chunks
  13258. result = new Uint8Array(len);
  13259. pos = 0;
  13260. for (i=0, l=chunks.length; i<l; i++) {
  13261. chunk = chunks[i];
  13262. result.set(chunk, pos);
  13263. pos += chunk.length;
  13264. }
  13265. return result;
  13266. }
  13267. };
  13268. var fnUntyped = {
  13269. arraySet: function (dest, src, src_offs, len, dest_offs) {
  13270. for (var i=0; i<len; i++) {
  13271. dest[dest_offs + i] = src[src_offs + i];
  13272. }
  13273. },
  13274. // Join array of chunks to single array.
  13275. flattenChunks: function(chunks) {
  13276. return [].concat.apply([], chunks);
  13277. }
  13278. };
  13279. // Enable/Disable typed arrays use, for testing
  13280. //
  13281. exports.setTyped = function (on) {
  13282. if (on) {
  13283. exports.Buf8 = Uint8Array;
  13284. exports.Buf16 = Uint16Array;
  13285. exports.Buf32 = Int32Array;
  13286. exports.assign(exports, fnTyped);
  13287. } else {
  13288. exports.Buf8 = Array;
  13289. exports.Buf16 = Array;
  13290. exports.Buf32 = Array;
  13291. exports.assign(exports, fnUntyped);
  13292. }
  13293. };
  13294. exports.setTyped(TYPED_OK);
  13295. },{}],52:[function(require,module,exports){
  13296. // String encode/decode helpers
  13297. 'use strict';
  13298. var utils = require('./common');
  13299. // Quick check if we can use fast array to bin string conversion
  13300. //
  13301. // - apply(Array) can fail on Android 2.2
  13302. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  13303. //
  13304. var STR_APPLY_OK = true;
  13305. var STR_APPLY_UIA_OK = true;
  13306. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  13307. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  13308. // Table with utf8 lengths (calculated by first byte of sequence)
  13309. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  13310. // because max possible codepoint is 0x10ffff
  13311. var _utf8len = new utils.Buf8(256);
  13312. for (var q=0; q<256; q++) {
  13313. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  13314. }
  13315. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  13316. // convert string to array (typed, when possible)
  13317. exports.string2buf = function (str) {
  13318. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  13319. // count binary size
  13320. for (m_pos = 0; m_pos < str_len; m_pos++) {
  13321. c = str.charCodeAt(m_pos);
  13322. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  13323. c2 = str.charCodeAt(m_pos+1);
  13324. if ((c2 & 0xfc00) === 0xdc00) {
  13325. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  13326. m_pos++;
  13327. }
  13328. }
  13329. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  13330. }
  13331. // allocate buffer
  13332. buf = new utils.Buf8(buf_len);
  13333. // convert
  13334. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  13335. c = str.charCodeAt(m_pos);
  13336. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  13337. c2 = str.charCodeAt(m_pos+1);
  13338. if ((c2 & 0xfc00) === 0xdc00) {
  13339. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  13340. m_pos++;
  13341. }
  13342. }
  13343. if (c < 0x80) {
  13344. /* one byte */
  13345. buf[i++] = c;
  13346. } else if (c < 0x800) {
  13347. /* two bytes */
  13348. buf[i++] = 0xC0 | (c >>> 6);
  13349. buf[i++] = 0x80 | (c & 0x3f);
  13350. } else if (c < 0x10000) {
  13351. /* three bytes */
  13352. buf[i++] = 0xE0 | (c >>> 12);
  13353. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  13354. buf[i++] = 0x80 | (c & 0x3f);
  13355. } else {
  13356. /* four bytes */
  13357. buf[i++] = 0xf0 | (c >>> 18);
  13358. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  13359. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  13360. buf[i++] = 0x80 | (c & 0x3f);
  13361. }
  13362. }
  13363. return buf;
  13364. };
  13365. // Helper (used in 2 places)
  13366. function buf2binstring(buf, len) {
  13367. // use fallback for big arrays to avoid stack overflow
  13368. if (len < 65537) {
  13369. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  13370. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  13371. }
  13372. }
  13373. var result = '';
  13374. for (var i=0; i < len; i++) {
  13375. result += String.fromCharCode(buf[i]);
  13376. }
  13377. return result;
  13378. }
  13379. // Convert byte array to binary string
  13380. exports.buf2binstring = function(buf) {
  13381. return buf2binstring(buf, buf.length);
  13382. };
  13383. // Convert binary string (typed, when possible)
  13384. exports.binstring2buf = function(str) {
  13385. var buf = new utils.Buf8(str.length);
  13386. for (var i=0, len=buf.length; i < len; i++) {
  13387. buf[i] = str.charCodeAt(i);
  13388. }
  13389. return buf;
  13390. };
  13391. // convert array to string
  13392. exports.buf2string = function (buf, max) {
  13393. var i, out, c, c_len;
  13394. var len = max || buf.length;
  13395. // Reserve max possible length (2 words per char)
  13396. // NB: by unknown reasons, Array is significantly faster for
  13397. // String.fromCharCode.apply than Uint16Array.
  13398. var utf16buf = new Array(len*2);
  13399. for (out=0, i=0; i<len;) {
  13400. c = buf[i++];
  13401. // quick process ascii
  13402. if (c < 0x80) { utf16buf[out++] = c; continue; }
  13403. c_len = _utf8len[c];
  13404. // skip 5 & 6 byte codes
  13405. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  13406. // apply mask on first byte
  13407. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  13408. // join the rest
  13409. while (c_len > 1 && i < len) {
  13410. c = (c << 6) | (buf[i++] & 0x3f);
  13411. c_len--;
  13412. }
  13413. // terminated by end of string?
  13414. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  13415. if (c < 0x10000) {
  13416. utf16buf[out++] = c;
  13417. } else {
  13418. c -= 0x10000;
  13419. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  13420. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  13421. }
  13422. }
  13423. return buf2binstring(utf16buf, out);
  13424. };
  13425. // Calculate max possible position in utf8 buffer,
  13426. // that will not break sequence. If that's not possible
  13427. // - (very small limits) return max size as is.
  13428. //
  13429. // buf[] - utf8 bytes array
  13430. // max - length limit (mandatory);
  13431. exports.utf8border = function(buf, max) {
  13432. var pos;
  13433. max = max || buf.length;
  13434. if (max > buf.length) { max = buf.length; }
  13435. // go back from last position, until start of sequence found
  13436. pos = max-1;
  13437. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  13438. // Fuckup - very small and broken sequence,
  13439. // return max, because we should return something anyway.
  13440. if (pos < 0) { return max; }
  13441. // If we came to start of buffer - that means vuffer is too small,
  13442. // return max too.
  13443. if (pos === 0) { return max; }
  13444. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  13445. };
  13446. },{"./common":51}],53:[function(require,module,exports){
  13447. 'use strict';
  13448. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  13449. // It doesn't worth to make additional optimizationa as in original.
  13450. // Small size is preferable.
  13451. function adler32(adler, buf, len, pos) {
  13452. var s1 = (adler & 0xffff) |0,
  13453. s2 = ((adler >>> 16) & 0xffff) |0,
  13454. n = 0;
  13455. while (len !== 0) {
  13456. // Set limit ~ twice less than 5552, to keep
  13457. // s2 in 31-bits, because we force signed ints.
  13458. // in other case %= will fail.
  13459. n = len > 2000 ? 2000 : len;
  13460. len -= n;
  13461. do {
  13462. s1 = (s1 + buf[pos++]) |0;
  13463. s2 = (s2 + s1) |0;
  13464. } while (--n);
  13465. s1 %= 65521;
  13466. s2 %= 65521;
  13467. }
  13468. return (s1 | (s2 << 16)) |0;
  13469. }
  13470. module.exports = adler32;
  13471. },{}],54:[function(require,module,exports){
  13472. module.exports = {
  13473. /* Allowed flush values; see deflate() and inflate() below for details */
  13474. Z_NO_FLUSH: 0,
  13475. Z_PARTIAL_FLUSH: 1,
  13476. Z_SYNC_FLUSH: 2,
  13477. Z_FULL_FLUSH: 3,
  13478. Z_FINISH: 4,
  13479. Z_BLOCK: 5,
  13480. Z_TREES: 6,
  13481. /* Return codes for the compression/decompression functions. Negative values
  13482. * are errors, positive values are used for special but normal events.
  13483. */
  13484. Z_OK: 0,
  13485. Z_STREAM_END: 1,
  13486. Z_NEED_DICT: 2,
  13487. Z_ERRNO: -1,
  13488. Z_STREAM_ERROR: -2,
  13489. Z_DATA_ERROR: -3,
  13490. //Z_MEM_ERROR: -4,
  13491. Z_BUF_ERROR: -5,
  13492. //Z_VERSION_ERROR: -6,
  13493. /* compression levels */
  13494. Z_NO_COMPRESSION: 0,
  13495. Z_BEST_SPEED: 1,
  13496. Z_BEST_COMPRESSION: 9,
  13497. Z_DEFAULT_COMPRESSION: -1,
  13498. Z_FILTERED: 1,
  13499. Z_HUFFMAN_ONLY: 2,
  13500. Z_RLE: 3,
  13501. Z_FIXED: 4,
  13502. Z_DEFAULT_STRATEGY: 0,
  13503. /* Possible values of the data_type field (though see inflate()) */
  13504. Z_BINARY: 0,
  13505. Z_TEXT: 1,
  13506. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  13507. Z_UNKNOWN: 2,
  13508. /* The deflate compression method */
  13509. Z_DEFLATED: 8
  13510. //Z_NULL: null // Use -1 or null inline, depending on var type
  13511. };
  13512. },{}],55:[function(require,module,exports){
  13513. 'use strict';
  13514. // Note: we can't get significant speed boost here.
  13515. // So write code to minimize size - no pregenerated tables
  13516. // and array tools dependencies.
  13517. // Use ordinary array, since untyped makes no boost here
  13518. function makeTable() {
  13519. var c, table = [];
  13520. for (var n =0; n < 256; n++) {
  13521. c = n;
  13522. for (var k =0; k < 8; k++) {
  13523. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  13524. }
  13525. table[n] = c;
  13526. }
  13527. return table;
  13528. }
  13529. // Create table on load. Just 255 signed longs. Not a problem.
  13530. var crcTable = makeTable();
  13531. function crc32(crc, buf, len, pos) {
  13532. var t = crcTable,
  13533. end = pos + len;
  13534. crc = crc ^ (-1);
  13535. for (var i = pos; i < end; i++) {
  13536. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  13537. }
  13538. return (crc ^ (-1)); // >>> 0;
  13539. }
  13540. module.exports = crc32;
  13541. },{}],56:[function(require,module,exports){
  13542. 'use strict';
  13543. var utils = require('../utils/common');
  13544. var trees = require('./trees');
  13545. var adler32 = require('./adler32');
  13546. var crc32 = require('./crc32');
  13547. var msg = require('./messages');
  13548. /* Public constants ==========================================================*/
  13549. /* ===========================================================================*/
  13550. /* Allowed flush values; see deflate() and inflate() below for details */
  13551. var Z_NO_FLUSH = 0;
  13552. var Z_PARTIAL_FLUSH = 1;
  13553. //var Z_SYNC_FLUSH = 2;
  13554. var Z_FULL_FLUSH = 3;
  13555. var Z_FINISH = 4;
  13556. var Z_BLOCK = 5;
  13557. //var Z_TREES = 6;
  13558. /* Return codes for the compression/decompression functions. Negative values
  13559. * are errors, positive values are used for special but normal events.
  13560. */
  13561. var Z_OK = 0;
  13562. var Z_STREAM_END = 1;
  13563. //var Z_NEED_DICT = 2;
  13564. //var Z_ERRNO = -1;
  13565. var Z_STREAM_ERROR = -2;
  13566. var Z_DATA_ERROR = -3;
  13567. //var Z_MEM_ERROR = -4;
  13568. var Z_BUF_ERROR = -5;
  13569. //var Z_VERSION_ERROR = -6;
  13570. /* compression levels */
  13571. //var Z_NO_COMPRESSION = 0;
  13572. //var Z_BEST_SPEED = 1;
  13573. //var Z_BEST_COMPRESSION = 9;
  13574. var Z_DEFAULT_COMPRESSION = -1;
  13575. var Z_FILTERED = 1;
  13576. var Z_HUFFMAN_ONLY = 2;
  13577. var Z_RLE = 3;
  13578. var Z_FIXED = 4;
  13579. var Z_DEFAULT_STRATEGY = 0;
  13580. /* Possible values of the data_type field (though see inflate()) */
  13581. //var Z_BINARY = 0;
  13582. //var Z_TEXT = 1;
  13583. //var Z_ASCII = 1; // = Z_TEXT
  13584. var Z_UNKNOWN = 2;
  13585. /* The deflate compression method */
  13586. var Z_DEFLATED = 8;
  13587. /*============================================================================*/
  13588. var MAX_MEM_LEVEL = 9;
  13589. /* Maximum value for memLevel in deflateInit2 */
  13590. var MAX_WBITS = 15;
  13591. /* 32K LZ77 window */
  13592. var DEF_MEM_LEVEL = 8;
  13593. var LENGTH_CODES = 29;
  13594. /* number of length codes, not counting the special END_BLOCK code */
  13595. var LITERALS = 256;
  13596. /* number of literal bytes 0..255 */
  13597. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  13598. /* number of Literal or Length codes, including the END_BLOCK code */
  13599. var D_CODES = 30;
  13600. /* number of distance codes */
  13601. var BL_CODES = 19;
  13602. /* number of codes used to transfer the bit lengths */
  13603. var HEAP_SIZE = 2*L_CODES + 1;
  13604. /* maximum heap size */
  13605. var MAX_BITS = 15;
  13606. /* All codes must not exceed MAX_BITS bits */
  13607. var MIN_MATCH = 3;
  13608. var MAX_MATCH = 258;
  13609. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  13610. var PRESET_DICT = 0x20;
  13611. var INIT_STATE = 42;
  13612. var EXTRA_STATE = 69;
  13613. var NAME_STATE = 73;
  13614. var COMMENT_STATE = 91;
  13615. var HCRC_STATE = 103;
  13616. var BUSY_STATE = 113;
  13617. var FINISH_STATE = 666;
  13618. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  13619. var BS_BLOCK_DONE = 2; /* block flush performed */
  13620. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  13621. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  13622. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  13623. function err(strm, errorCode) {
  13624. strm.msg = msg[errorCode];
  13625. return errorCode;
  13626. }
  13627. function rank(f) {
  13628. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  13629. }
  13630. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  13631. /* =========================================================================
  13632. * Flush as much pending output as possible. All deflate() output goes
  13633. * through this function so some applications may wish to modify it
  13634. * to avoid allocating a large strm->output buffer and copying into it.
  13635. * (See also read_buf()).
  13636. */
  13637. function flush_pending(strm) {
  13638. var s = strm.state;
  13639. //_tr_flush_bits(s);
  13640. var len = s.pending;
  13641. if (len > strm.avail_out) {
  13642. len = strm.avail_out;
  13643. }
  13644. if (len === 0) { return; }
  13645. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  13646. strm.next_out += len;
  13647. s.pending_out += len;
  13648. strm.total_out += len;
  13649. strm.avail_out -= len;
  13650. s.pending -= len;
  13651. if (s.pending === 0) {
  13652. s.pending_out = 0;
  13653. }
  13654. }
  13655. function flush_block_only (s, last) {
  13656. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  13657. s.block_start = s.strstart;
  13658. flush_pending(s.strm);
  13659. }
  13660. function put_byte(s, b) {
  13661. s.pending_buf[s.pending++] = b;
  13662. }
  13663. /* =========================================================================
  13664. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  13665. * IN assertion: the stream state is correct and there is enough room in
  13666. * pending_buf.
  13667. */
  13668. function putShortMSB(s, b) {
  13669. // put_byte(s, (Byte)(b >> 8));
  13670. // put_byte(s, (Byte)(b & 0xff));
  13671. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  13672. s.pending_buf[s.pending++] = b & 0xff;
  13673. }
  13674. /* ===========================================================================
  13675. * Read a new buffer from the current input stream, update the adler32
  13676. * and total number of bytes read. All deflate() input goes through
  13677. * this function so some applications may wish to modify it to avoid
  13678. * allocating a large strm->input buffer and copying from it.
  13679. * (See also flush_pending()).
  13680. */
  13681. function read_buf(strm, buf, start, size) {
  13682. var len = strm.avail_in;
  13683. if (len > size) { len = size; }
  13684. if (len === 0) { return 0; }
  13685. strm.avail_in -= len;
  13686. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  13687. if (strm.state.wrap === 1) {
  13688. strm.adler = adler32(strm.adler, buf, len, start);
  13689. }
  13690. else if (strm.state.wrap === 2) {
  13691. strm.adler = crc32(strm.adler, buf, len, start);
  13692. }
  13693. strm.next_in += len;
  13694. strm.total_in += len;
  13695. return len;
  13696. }
  13697. /* ===========================================================================
  13698. * Set match_start to the longest match starting at the given string and
  13699. * return its length. Matches shorter or equal to prev_length are discarded,
  13700. * in which case the result is equal to prev_length and match_start is
  13701. * garbage.
  13702. * IN assertions: cur_match is the head of the hash chain for the current
  13703. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  13704. * OUT assertion: the match length is not greater than s->lookahead.
  13705. */
  13706. function longest_match(s, cur_match) {
  13707. var chain_length = s.max_chain_length; /* max hash chain length */
  13708. var scan = s.strstart; /* current string */
  13709. var match; /* matched string */
  13710. var len; /* length of current match */
  13711. var best_len = s.prev_length; /* best match length so far */
  13712. var nice_match = s.nice_match; /* stop if match long enough */
  13713. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  13714. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  13715. var _win = s.window; // shortcut
  13716. var wmask = s.w_mask;
  13717. var prev = s.prev;
  13718. /* Stop when cur_match becomes <= limit. To simplify the code,
  13719. * we prevent matches with the string of window index 0.
  13720. */
  13721. var strend = s.strstart + MAX_MATCH;
  13722. var scan_end1 = _win[scan + best_len - 1];
  13723. var scan_end = _win[scan + best_len];
  13724. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  13725. * It is easy to get rid of this optimization if necessary.
  13726. */
  13727. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  13728. /* Do not waste too much time if we already have a good match: */
  13729. if (s.prev_length >= s.good_match) {
  13730. chain_length >>= 2;
  13731. }
  13732. /* Do not look for matches beyond the end of the input. This is necessary
  13733. * to make deflate deterministic.
  13734. */
  13735. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  13736. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  13737. do {
  13738. // Assert(cur_match < s->strstart, "no future");
  13739. match = cur_match;
  13740. /* Skip to next match if the match length cannot increase
  13741. * or if the match length is less than 2. Note that the checks below
  13742. * for insufficient lookahead only occur occasionally for performance
  13743. * reasons. Therefore uninitialized memory will be accessed, and
  13744. * conditional jumps will be made that depend on those values.
  13745. * However the length of the match is limited to the lookahead, so
  13746. * the output of deflate is not affected by the uninitialized values.
  13747. */
  13748. if (_win[match + best_len] !== scan_end ||
  13749. _win[match + best_len - 1] !== scan_end1 ||
  13750. _win[match] !== _win[scan] ||
  13751. _win[++match] !== _win[scan + 1]) {
  13752. continue;
  13753. }
  13754. /* The check at best_len-1 can be removed because it will be made
  13755. * again later. (This heuristic is not always a win.)
  13756. * It is not necessary to compare scan[2] and match[2] since they
  13757. * are always equal when the other bytes match, given that
  13758. * the hash keys are equal and that HASH_BITS >= 8.
  13759. */
  13760. scan += 2;
  13761. match++;
  13762. // Assert(*scan == *match, "match[2]?");
  13763. /* We check for insufficient lookahead only every 8th comparison;
  13764. * the 256th check will be made at strstart+258.
  13765. */
  13766. do {
  13767. /*jshint noempty:false*/
  13768. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13769. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13770. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13771. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13772. scan < strend);
  13773. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  13774. len = MAX_MATCH - (strend - scan);
  13775. scan = strend - MAX_MATCH;
  13776. if (len > best_len) {
  13777. s.match_start = cur_match;
  13778. best_len = len;
  13779. if (len >= nice_match) {
  13780. break;
  13781. }
  13782. scan_end1 = _win[scan + best_len - 1];
  13783. scan_end = _win[scan + best_len];
  13784. }
  13785. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  13786. if (best_len <= s.lookahead) {
  13787. return best_len;
  13788. }
  13789. return s.lookahead;
  13790. }
  13791. /* ===========================================================================
  13792. * Fill the window when the lookahead becomes insufficient.
  13793. * Updates strstart and lookahead.
  13794. *
  13795. * IN assertion: lookahead < MIN_LOOKAHEAD
  13796. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  13797. * At least one byte has been read, or avail_in == 0; reads are
  13798. * performed for at least two bytes (required for the zip translate_eol
  13799. * option -- not supported here).
  13800. */
  13801. function fill_window(s) {
  13802. var _w_size = s.w_size;
  13803. var p, n, m, more, str;
  13804. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  13805. do {
  13806. more = s.window_size - s.lookahead - s.strstart;
  13807. // JS ints have 32 bit, block below not needed
  13808. /* Deal with !@#$% 64K limit: */
  13809. //if (sizeof(int) <= 2) {
  13810. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  13811. // more = wsize;
  13812. //
  13813. // } else if (more == (unsigned)(-1)) {
  13814. // /* Very unlikely, but possible on 16 bit machine if
  13815. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  13816. // */
  13817. // more--;
  13818. // }
  13819. //}
  13820. /* If the window is almost full and there is insufficient lookahead,
  13821. * move the upper half to the lower one to make room in the upper half.
  13822. */
  13823. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  13824. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  13825. s.match_start -= _w_size;
  13826. s.strstart -= _w_size;
  13827. /* we now have strstart >= MAX_DIST */
  13828. s.block_start -= _w_size;
  13829. /* Slide the hash table (could be avoided with 32 bit values
  13830. at the expense of memory usage). We slide even when level == 0
  13831. to keep the hash table consistent if we switch back to level > 0
  13832. later. (Using level 0 permanently is not an optimal usage of
  13833. zlib, so we don't care about this pathological case.)
  13834. */
  13835. n = s.hash_size;
  13836. p = n;
  13837. do {
  13838. m = s.head[--p];
  13839. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  13840. } while (--n);
  13841. n = _w_size;
  13842. p = n;
  13843. do {
  13844. m = s.prev[--p];
  13845. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  13846. /* If n is not on any hash chain, prev[n] is garbage but
  13847. * its value will never be used.
  13848. */
  13849. } while (--n);
  13850. more += _w_size;
  13851. }
  13852. if (s.strm.avail_in === 0) {
  13853. break;
  13854. }
  13855. /* If there was no sliding:
  13856. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  13857. * more == window_size - lookahead - strstart
  13858. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  13859. * => more >= window_size - 2*WSIZE + 2
  13860. * In the BIG_MEM or MMAP case (not yet supported),
  13861. * window_size == input_size + MIN_LOOKAHEAD &&
  13862. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  13863. * Otherwise, window_size == 2*WSIZE so more >= 2.
  13864. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  13865. */
  13866. //Assert(more >= 2, "more < 2");
  13867. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  13868. s.lookahead += n;
  13869. /* Initialize the hash value now that we have some input: */
  13870. if (s.lookahead + s.insert >= MIN_MATCH) {
  13871. str = s.strstart - s.insert;
  13872. s.ins_h = s.window[str];
  13873. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  13874. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  13875. //#if MIN_MATCH != 3
  13876. // Call update_hash() MIN_MATCH-3 more times
  13877. //#endif
  13878. while (s.insert) {
  13879. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  13880. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  13881. s.prev[str & s.w_mask] = s.head[s.ins_h];
  13882. s.head[s.ins_h] = str;
  13883. str++;
  13884. s.insert--;
  13885. if (s.lookahead + s.insert < MIN_MATCH) {
  13886. break;
  13887. }
  13888. }
  13889. }
  13890. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  13891. * but this is not important since only literal bytes will be emitted.
  13892. */
  13893. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  13894. /* If the WIN_INIT bytes after the end of the current data have never been
  13895. * written, then zero those bytes in order to avoid memory check reports of
  13896. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  13897. * the longest match routines. Update the high water mark for the next
  13898. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  13899. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  13900. */
  13901. // if (s.high_water < s.window_size) {
  13902. // var curr = s.strstart + s.lookahead;
  13903. // var init = 0;
  13904. //
  13905. // if (s.high_water < curr) {
  13906. // /* Previous high water mark below current data -- zero WIN_INIT
  13907. // * bytes or up to end of window, whichever is less.
  13908. // */
  13909. // init = s.window_size - curr;
  13910. // if (init > WIN_INIT)
  13911. // init = WIN_INIT;
  13912. // zmemzero(s->window + curr, (unsigned)init);
  13913. // s->high_water = curr + init;
  13914. // }
  13915. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  13916. // /* High water mark at or above current data, but below current data
  13917. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  13918. // * to end of window, whichever is less.
  13919. // */
  13920. // init = (ulg)curr + WIN_INIT - s->high_water;
  13921. // if (init > s->window_size - s->high_water)
  13922. // init = s->window_size - s->high_water;
  13923. // zmemzero(s->window + s->high_water, (unsigned)init);
  13924. // s->high_water += init;
  13925. // }
  13926. // }
  13927. //
  13928. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  13929. // "not enough room for search");
  13930. }
  13931. /* ===========================================================================
  13932. * Copy without compression as much as possible from the input stream, return
  13933. * the current block state.
  13934. * This function does not insert new strings in the dictionary since
  13935. * uncompressible data is probably not useful. This function is used
  13936. * only for the level=0 compression option.
  13937. * NOTE: this function should be optimized to avoid extra copying from
  13938. * window to pending_buf.
  13939. */
  13940. function deflate_stored(s, flush) {
  13941. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  13942. * to pending_buf_size, and each stored block has a 5 byte header:
  13943. */
  13944. var max_block_size = 0xffff;
  13945. if (max_block_size > s.pending_buf_size - 5) {
  13946. max_block_size = s.pending_buf_size - 5;
  13947. }
  13948. /* Copy as much as possible from input to output: */
  13949. for (;;) {
  13950. /* Fill the window as much as possible: */
  13951. if (s.lookahead <= 1) {
  13952. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  13953. // s->block_start >= (long)s->w_size, "slide too late");
  13954. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  13955. // s.block_start >= s.w_size)) {
  13956. // throw new Error("slide too late");
  13957. // }
  13958. fill_window(s);
  13959. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  13960. return BS_NEED_MORE;
  13961. }
  13962. if (s.lookahead === 0) {
  13963. break;
  13964. }
  13965. /* flush the current block */
  13966. }
  13967. //Assert(s->block_start >= 0L, "block gone");
  13968. // if (s.block_start < 0) throw new Error("block gone");
  13969. s.strstart += s.lookahead;
  13970. s.lookahead = 0;
  13971. /* Emit a stored block if pending_buf will be full: */
  13972. var max_start = s.block_start + max_block_size;
  13973. if (s.strstart === 0 || s.strstart >= max_start) {
  13974. /* strstart == 0 is possible when wraparound on 16-bit machine */
  13975. s.lookahead = s.strstart - max_start;
  13976. s.strstart = max_start;
  13977. /*** FLUSH_BLOCK(s, 0); ***/
  13978. flush_block_only(s, false);
  13979. if (s.strm.avail_out === 0) {
  13980. return BS_NEED_MORE;
  13981. }
  13982. /***/
  13983. }
  13984. /* Flush if we may have to slide, otherwise block_start may become
  13985. * negative and the data will be gone:
  13986. */
  13987. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  13988. /*** FLUSH_BLOCK(s, 0); ***/
  13989. flush_block_only(s, false);
  13990. if (s.strm.avail_out === 0) {
  13991. return BS_NEED_MORE;
  13992. }
  13993. /***/
  13994. }
  13995. }
  13996. s.insert = 0;
  13997. if (flush === Z_FINISH) {
  13998. /*** FLUSH_BLOCK(s, 1); ***/
  13999. flush_block_only(s, true);
  14000. if (s.strm.avail_out === 0) {
  14001. return BS_FINISH_STARTED;
  14002. }
  14003. /***/
  14004. return BS_FINISH_DONE;
  14005. }
  14006. if (s.strstart > s.block_start) {
  14007. /*** FLUSH_BLOCK(s, 0); ***/
  14008. flush_block_only(s, false);
  14009. if (s.strm.avail_out === 0) {
  14010. return BS_NEED_MORE;
  14011. }
  14012. /***/
  14013. }
  14014. return BS_NEED_MORE;
  14015. }
  14016. /* ===========================================================================
  14017. * Compress as much as possible from the input stream, return the current
  14018. * block state.
  14019. * This function does not perform lazy evaluation of matches and inserts
  14020. * new strings in the dictionary only for unmatched strings or for short
  14021. * matches. It is used only for the fast compression options.
  14022. */
  14023. function deflate_fast(s, flush) {
  14024. var hash_head; /* head of the hash chain */
  14025. var bflush; /* set if current block must be flushed */
  14026. for (;;) {
  14027. /* Make sure that we always have enough lookahead, except
  14028. * at the end of the input file. We need MAX_MATCH bytes
  14029. * for the next match, plus MIN_MATCH bytes to insert the
  14030. * string following the next match.
  14031. */
  14032. if (s.lookahead < MIN_LOOKAHEAD) {
  14033. fill_window(s);
  14034. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  14035. return BS_NEED_MORE;
  14036. }
  14037. if (s.lookahead === 0) {
  14038. break; /* flush the current block */
  14039. }
  14040. }
  14041. /* Insert the string window[strstart .. strstart+2] in the
  14042. * dictionary, and set hash_head to the head of the hash chain:
  14043. */
  14044. hash_head = 0/*NIL*/;
  14045. if (s.lookahead >= MIN_MATCH) {
  14046. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14047. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14048. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14049. s.head[s.ins_h] = s.strstart;
  14050. /***/
  14051. }
  14052. /* Find the longest match, discarding those <= prev_length.
  14053. * At this point we have always match_length < MIN_MATCH
  14054. */
  14055. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  14056. /* To simplify the code, we prevent matches with the string
  14057. * of window index 0 (in particular we have to avoid a match
  14058. * of the string with itself at the start of the input file).
  14059. */
  14060. s.match_length = longest_match(s, hash_head);
  14061. /* longest_match() sets match_start */
  14062. }
  14063. if (s.match_length >= MIN_MATCH) {
  14064. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  14065. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  14066. s.match_length - MIN_MATCH, bflush); ***/
  14067. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  14068. s.lookahead -= s.match_length;
  14069. /* Insert new strings in the hash table only if the match length
  14070. * is not too large. This saves time but degrades compression.
  14071. */
  14072. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  14073. s.match_length--; /* string at strstart already in table */
  14074. do {
  14075. s.strstart++;
  14076. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14077. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14078. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14079. s.head[s.ins_h] = s.strstart;
  14080. /***/
  14081. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  14082. * always MIN_MATCH bytes ahead.
  14083. */
  14084. } while (--s.match_length !== 0);
  14085. s.strstart++;
  14086. } else
  14087. {
  14088. s.strstart += s.match_length;
  14089. s.match_length = 0;
  14090. s.ins_h = s.window[s.strstart];
  14091. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  14092. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  14093. //#if MIN_MATCH != 3
  14094. // Call UPDATE_HASH() MIN_MATCH-3 more times
  14095. //#endif
  14096. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  14097. * matter since it will be recomputed at next deflate call.
  14098. */
  14099. }
  14100. } else {
  14101. /* No match, output a literal byte */
  14102. //Tracevv((stderr,"%c", s.window[s.strstart]));
  14103. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14104. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14105. s.lookahead--;
  14106. s.strstart++;
  14107. }
  14108. if (bflush) {
  14109. /*** FLUSH_BLOCK(s, 0); ***/
  14110. flush_block_only(s, false);
  14111. if (s.strm.avail_out === 0) {
  14112. return BS_NEED_MORE;
  14113. }
  14114. /***/
  14115. }
  14116. }
  14117. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  14118. if (flush === Z_FINISH) {
  14119. /*** FLUSH_BLOCK(s, 1); ***/
  14120. flush_block_only(s, true);
  14121. if (s.strm.avail_out === 0) {
  14122. return BS_FINISH_STARTED;
  14123. }
  14124. /***/
  14125. return BS_FINISH_DONE;
  14126. }
  14127. if (s.last_lit) {
  14128. /*** FLUSH_BLOCK(s, 0); ***/
  14129. flush_block_only(s, false);
  14130. if (s.strm.avail_out === 0) {
  14131. return BS_NEED_MORE;
  14132. }
  14133. /***/
  14134. }
  14135. return BS_BLOCK_DONE;
  14136. }
  14137. /* ===========================================================================
  14138. * Same as above, but achieves better compression. We use a lazy
  14139. * evaluation for matches: a match is finally adopted only if there is
  14140. * no better match at the next window position.
  14141. */
  14142. function deflate_slow(s, flush) {
  14143. var hash_head; /* head of hash chain */
  14144. var bflush; /* set if current block must be flushed */
  14145. var max_insert;
  14146. /* Process the input block. */
  14147. for (;;) {
  14148. /* Make sure that we always have enough lookahead, except
  14149. * at the end of the input file. We need MAX_MATCH bytes
  14150. * for the next match, plus MIN_MATCH bytes to insert the
  14151. * string following the next match.
  14152. */
  14153. if (s.lookahead < MIN_LOOKAHEAD) {
  14154. fill_window(s);
  14155. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  14156. return BS_NEED_MORE;
  14157. }
  14158. if (s.lookahead === 0) { break; } /* flush the current block */
  14159. }
  14160. /* Insert the string window[strstart .. strstart+2] in the
  14161. * dictionary, and set hash_head to the head of the hash chain:
  14162. */
  14163. hash_head = 0/*NIL*/;
  14164. if (s.lookahead >= MIN_MATCH) {
  14165. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14166. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14167. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14168. s.head[s.ins_h] = s.strstart;
  14169. /***/
  14170. }
  14171. /* Find the longest match, discarding those <= prev_length.
  14172. */
  14173. s.prev_length = s.match_length;
  14174. s.prev_match = s.match_start;
  14175. s.match_length = MIN_MATCH-1;
  14176. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  14177. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  14178. /* To simplify the code, we prevent matches with the string
  14179. * of window index 0 (in particular we have to avoid a match
  14180. * of the string with itself at the start of the input file).
  14181. */
  14182. s.match_length = longest_match(s, hash_head);
  14183. /* longest_match() sets match_start */
  14184. if (s.match_length <= 5 &&
  14185. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  14186. /* If prev_match is also MIN_MATCH, match_start is garbage
  14187. * but we will ignore the current match anyway.
  14188. */
  14189. s.match_length = MIN_MATCH-1;
  14190. }
  14191. }
  14192. /* If there was a match at the previous step and the current
  14193. * match is not better, output the previous match:
  14194. */
  14195. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  14196. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  14197. /* Do not insert strings in hash table beyond this. */
  14198. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  14199. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  14200. s.prev_length - MIN_MATCH, bflush);***/
  14201. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  14202. /* Insert in hash table all strings up to the end of the match.
  14203. * strstart-1 and strstart are already inserted. If there is not
  14204. * enough lookahead, the last two strings are not inserted in
  14205. * the hash table.
  14206. */
  14207. s.lookahead -= s.prev_length-1;
  14208. s.prev_length -= 2;
  14209. do {
  14210. if (++s.strstart <= max_insert) {
  14211. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14212. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14213. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14214. s.head[s.ins_h] = s.strstart;
  14215. /***/
  14216. }
  14217. } while (--s.prev_length !== 0);
  14218. s.match_available = 0;
  14219. s.match_length = MIN_MATCH-1;
  14220. s.strstart++;
  14221. if (bflush) {
  14222. /*** FLUSH_BLOCK(s, 0); ***/
  14223. flush_block_only(s, false);
  14224. if (s.strm.avail_out === 0) {
  14225. return BS_NEED_MORE;
  14226. }
  14227. /***/
  14228. }
  14229. } else if (s.match_available) {
  14230. /* If there was no match at the previous position, output a
  14231. * single literal. If there was a match but the current match
  14232. * is longer, truncate the previous match to a single literal.
  14233. */
  14234. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  14235. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  14236. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  14237. if (bflush) {
  14238. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  14239. flush_block_only(s, false);
  14240. /***/
  14241. }
  14242. s.strstart++;
  14243. s.lookahead--;
  14244. if (s.strm.avail_out === 0) {
  14245. return BS_NEED_MORE;
  14246. }
  14247. } else {
  14248. /* There is no previous match to compare with, wait for
  14249. * the next step to decide.
  14250. */
  14251. s.match_available = 1;
  14252. s.strstart++;
  14253. s.lookahead--;
  14254. }
  14255. }
  14256. //Assert (flush != Z_NO_FLUSH, "no flush?");
  14257. if (s.match_available) {
  14258. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  14259. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  14260. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  14261. s.match_available = 0;
  14262. }
  14263. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  14264. if (flush === Z_FINISH) {
  14265. /*** FLUSH_BLOCK(s, 1); ***/
  14266. flush_block_only(s, true);
  14267. if (s.strm.avail_out === 0) {
  14268. return BS_FINISH_STARTED;
  14269. }
  14270. /***/
  14271. return BS_FINISH_DONE;
  14272. }
  14273. if (s.last_lit) {
  14274. /*** FLUSH_BLOCK(s, 0); ***/
  14275. flush_block_only(s, false);
  14276. if (s.strm.avail_out === 0) {
  14277. return BS_NEED_MORE;
  14278. }
  14279. /***/
  14280. }
  14281. return BS_BLOCK_DONE;
  14282. }
  14283. /* ===========================================================================
  14284. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  14285. * one. Do not maintain a hash table. (It will be regenerated if this run of
  14286. * deflate switches away from Z_RLE.)
  14287. */
  14288. function deflate_rle(s, flush) {
  14289. var bflush; /* set if current block must be flushed */
  14290. var prev; /* byte at distance one to match */
  14291. var scan, strend; /* scan goes up to strend for length of run */
  14292. var _win = s.window;
  14293. for (;;) {
  14294. /* Make sure that we always have enough lookahead, except
  14295. * at the end of the input file. We need MAX_MATCH bytes
  14296. * for the longest run, plus one for the unrolled loop.
  14297. */
  14298. if (s.lookahead <= MAX_MATCH) {
  14299. fill_window(s);
  14300. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  14301. return BS_NEED_MORE;
  14302. }
  14303. if (s.lookahead === 0) { break; } /* flush the current block */
  14304. }
  14305. /* See how many times the previous byte repeats */
  14306. s.match_length = 0;
  14307. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  14308. scan = s.strstart - 1;
  14309. prev = _win[scan];
  14310. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  14311. strend = s.strstart + MAX_MATCH;
  14312. do {
  14313. /*jshint noempty:false*/
  14314. } while (prev === _win[++scan] && prev === _win[++scan] &&
  14315. prev === _win[++scan] && prev === _win[++scan] &&
  14316. prev === _win[++scan] && prev === _win[++scan] &&
  14317. prev === _win[++scan] && prev === _win[++scan] &&
  14318. scan < strend);
  14319. s.match_length = MAX_MATCH - (strend - scan);
  14320. if (s.match_length > s.lookahead) {
  14321. s.match_length = s.lookahead;
  14322. }
  14323. }
  14324. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  14325. }
  14326. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  14327. if (s.match_length >= MIN_MATCH) {
  14328. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  14329. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  14330. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  14331. s.lookahead -= s.match_length;
  14332. s.strstart += s.match_length;
  14333. s.match_length = 0;
  14334. } else {
  14335. /* No match, output a literal byte */
  14336. //Tracevv((stderr,"%c", s->window[s->strstart]));
  14337. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14338. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14339. s.lookahead--;
  14340. s.strstart++;
  14341. }
  14342. if (bflush) {
  14343. /*** FLUSH_BLOCK(s, 0); ***/
  14344. flush_block_only(s, false);
  14345. if (s.strm.avail_out === 0) {
  14346. return BS_NEED_MORE;
  14347. }
  14348. /***/
  14349. }
  14350. }
  14351. s.insert = 0;
  14352. if (flush === Z_FINISH) {
  14353. /*** FLUSH_BLOCK(s, 1); ***/
  14354. flush_block_only(s, true);
  14355. if (s.strm.avail_out === 0) {
  14356. return BS_FINISH_STARTED;
  14357. }
  14358. /***/
  14359. return BS_FINISH_DONE;
  14360. }
  14361. if (s.last_lit) {
  14362. /*** FLUSH_BLOCK(s, 0); ***/
  14363. flush_block_only(s, false);
  14364. if (s.strm.avail_out === 0) {
  14365. return BS_NEED_MORE;
  14366. }
  14367. /***/
  14368. }
  14369. return BS_BLOCK_DONE;
  14370. }
  14371. /* ===========================================================================
  14372. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  14373. * (It will be regenerated if this run of deflate switches away from Huffman.)
  14374. */
  14375. function deflate_huff(s, flush) {
  14376. var bflush; /* set if current block must be flushed */
  14377. for (;;) {
  14378. /* Make sure that we have a literal to write. */
  14379. if (s.lookahead === 0) {
  14380. fill_window(s);
  14381. if (s.lookahead === 0) {
  14382. if (flush === Z_NO_FLUSH) {
  14383. return BS_NEED_MORE;
  14384. }
  14385. break; /* flush the current block */
  14386. }
  14387. }
  14388. /* Output a literal byte */
  14389. s.match_length = 0;
  14390. //Tracevv((stderr,"%c", s->window[s->strstart]));
  14391. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14392. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14393. s.lookahead--;
  14394. s.strstart++;
  14395. if (bflush) {
  14396. /*** FLUSH_BLOCK(s, 0); ***/
  14397. flush_block_only(s, false);
  14398. if (s.strm.avail_out === 0) {
  14399. return BS_NEED_MORE;
  14400. }
  14401. /***/
  14402. }
  14403. }
  14404. s.insert = 0;
  14405. if (flush === Z_FINISH) {
  14406. /*** FLUSH_BLOCK(s, 1); ***/
  14407. flush_block_only(s, true);
  14408. if (s.strm.avail_out === 0) {
  14409. return BS_FINISH_STARTED;
  14410. }
  14411. /***/
  14412. return BS_FINISH_DONE;
  14413. }
  14414. if (s.last_lit) {
  14415. /*** FLUSH_BLOCK(s, 0); ***/
  14416. flush_block_only(s, false);
  14417. if (s.strm.avail_out === 0) {
  14418. return BS_NEED_MORE;
  14419. }
  14420. /***/
  14421. }
  14422. return BS_BLOCK_DONE;
  14423. }
  14424. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  14425. * the desired pack level (0..9). The values given below have been tuned to
  14426. * exclude worst case performance for pathological files. Better values may be
  14427. * found for specific files.
  14428. */
  14429. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  14430. this.good_length = good_length;
  14431. this.max_lazy = max_lazy;
  14432. this.nice_length = nice_length;
  14433. this.max_chain = max_chain;
  14434. this.func = func;
  14435. };
  14436. var configuration_table;
  14437. configuration_table = [
  14438. /* good lazy nice chain */
  14439. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  14440. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  14441. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  14442. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  14443. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  14444. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  14445. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  14446. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  14447. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  14448. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  14449. ];
  14450. /* ===========================================================================
  14451. * Initialize the "longest match" routines for a new zlib stream
  14452. */
  14453. function lm_init(s) {
  14454. s.window_size = 2 * s.w_size;
  14455. /*** CLEAR_HASH(s); ***/
  14456. zero(s.head); // Fill with NIL (= 0);
  14457. /* Set the default configuration parameters:
  14458. */
  14459. s.max_lazy_match = configuration_table[s.level].max_lazy;
  14460. s.good_match = configuration_table[s.level].good_length;
  14461. s.nice_match = configuration_table[s.level].nice_length;
  14462. s.max_chain_length = configuration_table[s.level].max_chain;
  14463. s.strstart = 0;
  14464. s.block_start = 0;
  14465. s.lookahead = 0;
  14466. s.insert = 0;
  14467. s.match_length = s.prev_length = MIN_MATCH - 1;
  14468. s.match_available = 0;
  14469. s.ins_h = 0;
  14470. }
  14471. function DeflateState() {
  14472. this.strm = null; /* pointer back to this zlib stream */
  14473. this.status = 0; /* as the name implies */
  14474. this.pending_buf = null; /* output still pending */
  14475. this.pending_buf_size = 0; /* size of pending_buf */
  14476. this.pending_out = 0; /* next pending byte to output to the stream */
  14477. this.pending = 0; /* nb of bytes in the pending buffer */
  14478. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  14479. this.gzhead = null; /* gzip header information to write */
  14480. this.gzindex = 0; /* where in extra, name, or comment */
  14481. this.method = Z_DEFLATED; /* can only be DEFLATED */
  14482. this.last_flush = -1; /* value of flush param for previous deflate call */
  14483. this.w_size = 0; /* LZ77 window size (32K by default) */
  14484. this.w_bits = 0; /* log2(w_size) (8..16) */
  14485. this.w_mask = 0; /* w_size - 1 */
  14486. this.window = null;
  14487. /* Sliding window. Input bytes are read into the second half of the window,
  14488. * and move to the first half later to keep a dictionary of at least wSize
  14489. * bytes. With this organization, matches are limited to a distance of
  14490. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  14491. * performed with a length multiple of the block size.
  14492. */
  14493. this.window_size = 0;
  14494. /* Actual size of window: 2*wSize, except when the user input buffer
  14495. * is directly used as sliding window.
  14496. */
  14497. this.prev = null;
  14498. /* Link to older string with same hash index. To limit the size of this
  14499. * array to 64K, this link is maintained only for the last 32K strings.
  14500. * An index in this array is thus a window index modulo 32K.
  14501. */
  14502. this.head = null; /* Heads of the hash chains or NIL. */
  14503. this.ins_h = 0; /* hash index of string to be inserted */
  14504. this.hash_size = 0; /* number of elements in hash table */
  14505. this.hash_bits = 0; /* log2(hash_size) */
  14506. this.hash_mask = 0; /* hash_size-1 */
  14507. this.hash_shift = 0;
  14508. /* Number of bits by which ins_h must be shifted at each input
  14509. * step. It must be such that after MIN_MATCH steps, the oldest
  14510. * byte no longer takes part in the hash key, that is:
  14511. * hash_shift * MIN_MATCH >= hash_bits
  14512. */
  14513. this.block_start = 0;
  14514. /* Window position at the beginning of the current output block. Gets
  14515. * negative when the window is moved backwards.
  14516. */
  14517. this.match_length = 0; /* length of best match */
  14518. this.prev_match = 0; /* previous match */
  14519. this.match_available = 0; /* set if previous match exists */
  14520. this.strstart = 0; /* start of string to insert */
  14521. this.match_start = 0; /* start of matching string */
  14522. this.lookahead = 0; /* number of valid bytes ahead in window */
  14523. this.prev_length = 0;
  14524. /* Length of the best match at previous step. Matches not greater than this
  14525. * are discarded. This is used in the lazy match evaluation.
  14526. */
  14527. this.max_chain_length = 0;
  14528. /* To speed up deflation, hash chains are never searched beyond this
  14529. * length. A higher limit improves compression ratio but degrades the
  14530. * speed.
  14531. */
  14532. this.max_lazy_match = 0;
  14533. /* Attempt to find a better match only when the current match is strictly
  14534. * smaller than this value. This mechanism is used only for compression
  14535. * levels >= 4.
  14536. */
  14537. // That's alias to max_lazy_match, don't use directly
  14538. //this.max_insert_length = 0;
  14539. /* Insert new strings in the hash table only if the match length is not
  14540. * greater than this length. This saves time but degrades compression.
  14541. * max_insert_length is used only for compression levels <= 3.
  14542. */
  14543. this.level = 0; /* compression level (1..9) */
  14544. this.strategy = 0; /* favor or force Huffman coding*/
  14545. this.good_match = 0;
  14546. /* Use a faster search when the previous match is longer than this */
  14547. this.nice_match = 0; /* Stop searching when current match exceeds this */
  14548. /* used by trees.c: */
  14549. /* Didn't use ct_data typedef below to suppress compiler warning */
  14550. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  14551. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  14552. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  14553. // Use flat array of DOUBLE size, with interleaved fata,
  14554. // because JS does not support effective
  14555. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  14556. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  14557. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  14558. zero(this.dyn_ltree);
  14559. zero(this.dyn_dtree);
  14560. zero(this.bl_tree);
  14561. this.l_desc = null; /* desc. for literal tree */
  14562. this.d_desc = null; /* desc. for distance tree */
  14563. this.bl_desc = null; /* desc. for bit length tree */
  14564. //ush bl_count[MAX_BITS+1];
  14565. this.bl_count = new utils.Buf16(MAX_BITS+1);
  14566. /* number of codes at each bit length for an optimal tree */
  14567. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  14568. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  14569. zero(this.heap);
  14570. this.heap_len = 0; /* number of elements in the heap */
  14571. this.heap_max = 0; /* element of largest frequency */
  14572. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  14573. * The same heap array is used to build all trees.
  14574. */
  14575. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  14576. zero(this.depth);
  14577. /* Depth of each subtree used as tie breaker for trees of equal frequency
  14578. */
  14579. this.l_buf = 0; /* buffer index for literals or lengths */
  14580. this.lit_bufsize = 0;
  14581. /* Size of match buffer for literals/lengths. There are 4 reasons for
  14582. * limiting lit_bufsize to 64K:
  14583. * - frequencies can be kept in 16 bit counters
  14584. * - if compression is not successful for the first block, all input
  14585. * data is still in the window so we can still emit a stored block even
  14586. * when input comes from standard input. (This can also be done for
  14587. * all blocks if lit_bufsize is not greater than 32K.)
  14588. * - if compression is not successful for a file smaller than 64K, we can
  14589. * even emit a stored file instead of a stored block (saving 5 bytes).
  14590. * This is applicable only for zip (not gzip or zlib).
  14591. * - creating new Huffman trees less frequently may not provide fast
  14592. * adaptation to changes in the input data statistics. (Take for
  14593. * example a binary file with poorly compressible code followed by
  14594. * a highly compressible string table.) Smaller buffer sizes give
  14595. * fast adaptation but have of course the overhead of transmitting
  14596. * trees more frequently.
  14597. * - I can't count above 4
  14598. */
  14599. this.last_lit = 0; /* running index in l_buf */
  14600. this.d_buf = 0;
  14601. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  14602. * the same number of elements. To use different lengths, an extra flag
  14603. * array would be necessary.
  14604. */
  14605. this.opt_len = 0; /* bit length of current block with optimal trees */
  14606. this.static_len = 0; /* bit length of current block with static trees */
  14607. this.matches = 0; /* number of string matches in current block */
  14608. this.insert = 0; /* bytes at end of window left to insert */
  14609. this.bi_buf = 0;
  14610. /* Output buffer. bits are inserted starting at the bottom (least
  14611. * significant bits).
  14612. */
  14613. this.bi_valid = 0;
  14614. /* Number of valid bits in bi_buf. All bits above the last valid bit
  14615. * are always zero.
  14616. */
  14617. // Used for window memory init. We safely ignore it for JS. That makes
  14618. // sense only for pointers and memory check tools.
  14619. //this.high_water = 0;
  14620. /* High water mark offset in window for initialized bytes -- bytes above
  14621. * this are set to zero in order to avoid memory check warnings when
  14622. * longest match routines access bytes past the input. This is then
  14623. * updated to the new high water mark.
  14624. */
  14625. }
  14626. function deflateResetKeep(strm) {
  14627. var s;
  14628. if (!strm || !strm.state) {
  14629. return err(strm, Z_STREAM_ERROR);
  14630. }
  14631. strm.total_in = strm.total_out = 0;
  14632. strm.data_type = Z_UNKNOWN;
  14633. s = strm.state;
  14634. s.pending = 0;
  14635. s.pending_out = 0;
  14636. if (s.wrap < 0) {
  14637. s.wrap = -s.wrap;
  14638. /* was made negative by deflate(..., Z_FINISH); */
  14639. }
  14640. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  14641. strm.adler = (s.wrap === 2) ?
  14642. 0 // crc32(0, Z_NULL, 0)
  14643. :
  14644. 1; // adler32(0, Z_NULL, 0)
  14645. s.last_flush = Z_NO_FLUSH;
  14646. trees._tr_init(s);
  14647. return Z_OK;
  14648. }
  14649. function deflateReset(strm) {
  14650. var ret = deflateResetKeep(strm);
  14651. if (ret === Z_OK) {
  14652. lm_init(strm.state);
  14653. }
  14654. return ret;
  14655. }
  14656. function deflateSetHeader(strm, head) {
  14657. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  14658. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  14659. strm.state.gzhead = head;
  14660. return Z_OK;
  14661. }
  14662. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  14663. if (!strm) { // === Z_NULL
  14664. return Z_STREAM_ERROR;
  14665. }
  14666. var wrap = 1;
  14667. if (level === Z_DEFAULT_COMPRESSION) {
  14668. level = 6;
  14669. }
  14670. if (windowBits < 0) { /* suppress zlib wrapper */
  14671. wrap = 0;
  14672. windowBits = -windowBits;
  14673. }
  14674. else if (windowBits > 15) {
  14675. wrap = 2; /* write gzip wrapper instead */
  14676. windowBits -= 16;
  14677. }
  14678. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  14679. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  14680. strategy < 0 || strategy > Z_FIXED) {
  14681. return err(strm, Z_STREAM_ERROR);
  14682. }
  14683. if (windowBits === 8) {
  14684. windowBits = 9;
  14685. }
  14686. /* until 256-byte window bug fixed */
  14687. var s = new DeflateState();
  14688. strm.state = s;
  14689. s.strm = strm;
  14690. s.wrap = wrap;
  14691. s.gzhead = null;
  14692. s.w_bits = windowBits;
  14693. s.w_size = 1 << s.w_bits;
  14694. s.w_mask = s.w_size - 1;
  14695. s.hash_bits = memLevel + 7;
  14696. s.hash_size = 1 << s.hash_bits;
  14697. s.hash_mask = s.hash_size - 1;
  14698. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  14699. s.window = new utils.Buf8(s.w_size * 2);
  14700. s.head = new utils.Buf16(s.hash_size);
  14701. s.prev = new utils.Buf16(s.w_size);
  14702. // Don't need mem init magic for JS.
  14703. //s.high_water = 0; /* nothing written to s->window yet */
  14704. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  14705. s.pending_buf_size = s.lit_bufsize * 4;
  14706. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  14707. s.d_buf = s.lit_bufsize >> 1;
  14708. s.l_buf = (1 + 2) * s.lit_bufsize;
  14709. s.level = level;
  14710. s.strategy = strategy;
  14711. s.method = method;
  14712. return deflateReset(strm);
  14713. }
  14714. function deflateInit(strm, level) {
  14715. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  14716. }
  14717. function deflate(strm, flush) {
  14718. var old_flush, s;
  14719. var beg, val; // for gzip header write only
  14720. if (!strm || !strm.state ||
  14721. flush > Z_BLOCK || flush < 0) {
  14722. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  14723. }
  14724. s = strm.state;
  14725. if (!strm.output ||
  14726. (!strm.input && strm.avail_in !== 0) ||
  14727. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  14728. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  14729. }
  14730. s.strm = strm; /* just in case */
  14731. old_flush = s.last_flush;
  14732. s.last_flush = flush;
  14733. /* Write the header */
  14734. if (s.status === INIT_STATE) {
  14735. if (s.wrap === 2) { // GZIP header
  14736. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  14737. put_byte(s, 31);
  14738. put_byte(s, 139);
  14739. put_byte(s, 8);
  14740. if (!s.gzhead) { // s->gzhead == Z_NULL
  14741. put_byte(s, 0);
  14742. put_byte(s, 0);
  14743. put_byte(s, 0);
  14744. put_byte(s, 0);
  14745. put_byte(s, 0);
  14746. put_byte(s, s.level === 9 ? 2 :
  14747. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  14748. 4 : 0));
  14749. put_byte(s, OS_CODE);
  14750. s.status = BUSY_STATE;
  14751. }
  14752. else {
  14753. put_byte(s, (s.gzhead.text ? 1 : 0) +
  14754. (s.gzhead.hcrc ? 2 : 0) +
  14755. (!s.gzhead.extra ? 0 : 4) +
  14756. (!s.gzhead.name ? 0 : 8) +
  14757. (!s.gzhead.comment ? 0 : 16)
  14758. );
  14759. put_byte(s, s.gzhead.time & 0xff);
  14760. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  14761. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  14762. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  14763. put_byte(s, s.level === 9 ? 2 :
  14764. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  14765. 4 : 0));
  14766. put_byte(s, s.gzhead.os & 0xff);
  14767. if (s.gzhead.extra && s.gzhead.extra.length) {
  14768. put_byte(s, s.gzhead.extra.length & 0xff);
  14769. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  14770. }
  14771. if (s.gzhead.hcrc) {
  14772. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  14773. }
  14774. s.gzindex = 0;
  14775. s.status = EXTRA_STATE;
  14776. }
  14777. }
  14778. else // DEFLATE header
  14779. {
  14780. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  14781. var level_flags = -1;
  14782. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  14783. level_flags = 0;
  14784. } else if (s.level < 6) {
  14785. level_flags = 1;
  14786. } else if (s.level === 6) {
  14787. level_flags = 2;
  14788. } else {
  14789. level_flags = 3;
  14790. }
  14791. header |= (level_flags << 6);
  14792. if (s.strstart !== 0) { header |= PRESET_DICT; }
  14793. header += 31 - (header % 31);
  14794. s.status = BUSY_STATE;
  14795. putShortMSB(s, header);
  14796. /* Save the adler32 of the preset dictionary: */
  14797. if (s.strstart !== 0) {
  14798. putShortMSB(s, strm.adler >>> 16);
  14799. putShortMSB(s, strm.adler & 0xffff);
  14800. }
  14801. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  14802. }
  14803. }
  14804. //#ifdef GZIP
  14805. if (s.status === EXTRA_STATE) {
  14806. if (s.gzhead.extra/* != Z_NULL*/) {
  14807. beg = s.pending; /* start of bytes to update crc */
  14808. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  14809. if (s.pending === s.pending_buf_size) {
  14810. if (s.gzhead.hcrc && s.pending > beg) {
  14811. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14812. }
  14813. flush_pending(strm);
  14814. beg = s.pending;
  14815. if (s.pending === s.pending_buf_size) {
  14816. break;
  14817. }
  14818. }
  14819. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  14820. s.gzindex++;
  14821. }
  14822. if (s.gzhead.hcrc && s.pending > beg) {
  14823. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14824. }
  14825. if (s.gzindex === s.gzhead.extra.length) {
  14826. s.gzindex = 0;
  14827. s.status = NAME_STATE;
  14828. }
  14829. }
  14830. else {
  14831. s.status = NAME_STATE;
  14832. }
  14833. }
  14834. if (s.status === NAME_STATE) {
  14835. if (s.gzhead.name/* != Z_NULL*/) {
  14836. beg = s.pending; /* start of bytes to update crc */
  14837. //int val;
  14838. do {
  14839. if (s.pending === s.pending_buf_size) {
  14840. if (s.gzhead.hcrc && s.pending > beg) {
  14841. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14842. }
  14843. flush_pending(strm);
  14844. beg = s.pending;
  14845. if (s.pending === s.pending_buf_size) {
  14846. val = 1;
  14847. break;
  14848. }
  14849. }
  14850. // JS specific: little magic to add zero terminator to end of string
  14851. if (s.gzindex < s.gzhead.name.length) {
  14852. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  14853. } else {
  14854. val = 0;
  14855. }
  14856. put_byte(s, val);
  14857. } while (val !== 0);
  14858. if (s.gzhead.hcrc && s.pending > beg) {
  14859. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14860. }
  14861. if (val === 0) {
  14862. s.gzindex = 0;
  14863. s.status = COMMENT_STATE;
  14864. }
  14865. }
  14866. else {
  14867. s.status = COMMENT_STATE;
  14868. }
  14869. }
  14870. if (s.status === COMMENT_STATE) {
  14871. if (s.gzhead.comment/* != Z_NULL*/) {
  14872. beg = s.pending; /* start of bytes to update crc */
  14873. //int val;
  14874. do {
  14875. if (s.pending === s.pending_buf_size) {
  14876. if (s.gzhead.hcrc && s.pending > beg) {
  14877. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14878. }
  14879. flush_pending(strm);
  14880. beg = s.pending;
  14881. if (s.pending === s.pending_buf_size) {
  14882. val = 1;
  14883. break;
  14884. }
  14885. }
  14886. // JS specific: little magic to add zero terminator to end of string
  14887. if (s.gzindex < s.gzhead.comment.length) {
  14888. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  14889. } else {
  14890. val = 0;
  14891. }
  14892. put_byte(s, val);
  14893. } while (val !== 0);
  14894. if (s.gzhead.hcrc && s.pending > beg) {
  14895. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14896. }
  14897. if (val === 0) {
  14898. s.status = HCRC_STATE;
  14899. }
  14900. }
  14901. else {
  14902. s.status = HCRC_STATE;
  14903. }
  14904. }
  14905. if (s.status === HCRC_STATE) {
  14906. if (s.gzhead.hcrc) {
  14907. if (s.pending + 2 > s.pending_buf_size) {
  14908. flush_pending(strm);
  14909. }
  14910. if (s.pending + 2 <= s.pending_buf_size) {
  14911. put_byte(s, strm.adler & 0xff);
  14912. put_byte(s, (strm.adler >> 8) & 0xff);
  14913. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  14914. s.status = BUSY_STATE;
  14915. }
  14916. }
  14917. else {
  14918. s.status = BUSY_STATE;
  14919. }
  14920. }
  14921. //#endif
  14922. /* Flush as much pending output as possible */
  14923. if (s.pending !== 0) {
  14924. flush_pending(strm);
  14925. if (strm.avail_out === 0) {
  14926. /* Since avail_out is 0, deflate will be called again with
  14927. * more output space, but possibly with both pending and
  14928. * avail_in equal to zero. There won't be anything to do,
  14929. * but this is not an error situation so make sure we
  14930. * return OK instead of BUF_ERROR at next call of deflate:
  14931. */
  14932. s.last_flush = -1;
  14933. return Z_OK;
  14934. }
  14935. /* Make sure there is something to do and avoid duplicate consecutive
  14936. * flushes. For repeated and useless calls with Z_FINISH, we keep
  14937. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  14938. */
  14939. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  14940. flush !== Z_FINISH) {
  14941. return err(strm, Z_BUF_ERROR);
  14942. }
  14943. /* User must not provide more input after the first FINISH: */
  14944. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  14945. return err(strm, Z_BUF_ERROR);
  14946. }
  14947. /* Start a new block or continue the current one.
  14948. */
  14949. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  14950. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  14951. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  14952. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  14953. configuration_table[s.level].func(s, flush));
  14954. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  14955. s.status = FINISH_STATE;
  14956. }
  14957. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  14958. if (strm.avail_out === 0) {
  14959. s.last_flush = -1;
  14960. /* avoid BUF_ERROR next call, see above */
  14961. }
  14962. return Z_OK;
  14963. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  14964. * of deflate should use the same flush parameter to make sure
  14965. * that the flush is complete. So we don't have to output an
  14966. * empty block here, this will be done at next call. This also
  14967. * ensures that for a very small output buffer, we emit at most
  14968. * one empty block.
  14969. */
  14970. }
  14971. if (bstate === BS_BLOCK_DONE) {
  14972. if (flush === Z_PARTIAL_FLUSH) {
  14973. trees._tr_align(s);
  14974. }
  14975. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  14976. trees._tr_stored_block(s, 0, 0, false);
  14977. /* For a full flush, this empty block will be recognized
  14978. * as a special marker by inflate_sync().
  14979. */
  14980. if (flush === Z_FULL_FLUSH) {
  14981. /*** CLEAR_HASH(s); ***/ /* forget history */
  14982. zero(s.head); // Fill with NIL (= 0);
  14983. if (s.lookahead === 0) {
  14984. s.strstart = 0;
  14985. s.block_start = 0;
  14986. s.insert = 0;
  14987. }
  14988. }
  14989. }
  14990. flush_pending(strm);
  14991. if (strm.avail_out === 0) {
  14992. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  14993. return Z_OK;
  14994. }
  14995. }
  14996. }
  14997. //Assert(strm->avail_out > 0, "bug2");
  14998. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  14999. if (flush !== Z_FINISH) { return Z_OK; }
  15000. if (s.wrap <= 0) { return Z_STREAM_END; }
  15001. /* Write the trailer */
  15002. if (s.wrap === 2) {
  15003. put_byte(s, strm.adler & 0xff);
  15004. put_byte(s, (strm.adler >> 8) & 0xff);
  15005. put_byte(s, (strm.adler >> 16) & 0xff);
  15006. put_byte(s, (strm.adler >> 24) & 0xff);
  15007. put_byte(s, strm.total_in & 0xff);
  15008. put_byte(s, (strm.total_in >> 8) & 0xff);
  15009. put_byte(s, (strm.total_in >> 16) & 0xff);
  15010. put_byte(s, (strm.total_in >> 24) & 0xff);
  15011. }
  15012. else
  15013. {
  15014. putShortMSB(s, strm.adler >>> 16);
  15015. putShortMSB(s, strm.adler & 0xffff);
  15016. }
  15017. flush_pending(strm);
  15018. /* If avail_out is zero, the application will call deflate again
  15019. * to flush the rest.
  15020. */
  15021. if (s.wrap > 0) { s.wrap = -s.wrap; }
  15022. /* write the trailer only once! */
  15023. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  15024. }
  15025. function deflateEnd(strm) {
  15026. var status;
  15027. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  15028. return Z_STREAM_ERROR;
  15029. }
  15030. status = strm.state.status;
  15031. if (status !== INIT_STATE &&
  15032. status !== EXTRA_STATE &&
  15033. status !== NAME_STATE &&
  15034. status !== COMMENT_STATE &&
  15035. status !== HCRC_STATE &&
  15036. status !== BUSY_STATE &&
  15037. status !== FINISH_STATE
  15038. ) {
  15039. return err(strm, Z_STREAM_ERROR);
  15040. }
  15041. strm.state = null;
  15042. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  15043. }
  15044. /* =========================================================================
  15045. * Copy the source state to the destination state
  15046. */
  15047. //function deflateCopy(dest, source) {
  15048. //
  15049. //}
  15050. exports.deflateInit = deflateInit;
  15051. exports.deflateInit2 = deflateInit2;
  15052. exports.deflateReset = deflateReset;
  15053. exports.deflateResetKeep = deflateResetKeep;
  15054. exports.deflateSetHeader = deflateSetHeader;
  15055. exports.deflate = deflate;
  15056. exports.deflateEnd = deflateEnd;
  15057. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  15058. /* Not implemented
  15059. exports.deflateBound = deflateBound;
  15060. exports.deflateCopy = deflateCopy;
  15061. exports.deflateSetDictionary = deflateSetDictionary;
  15062. exports.deflateParams = deflateParams;
  15063. exports.deflatePending = deflatePending;
  15064. exports.deflatePrime = deflatePrime;
  15065. exports.deflateTune = deflateTune;
  15066. */
  15067. },{"../utils/common":51,"./adler32":53,"./crc32":55,"./messages":61,"./trees":62}],57:[function(require,module,exports){
  15068. 'use strict';
  15069. function GZheader() {
  15070. /* true if compressed data believed to be text */
  15071. this.text = 0;
  15072. /* modification time */
  15073. this.time = 0;
  15074. /* extra flags (not used when writing a gzip file) */
  15075. this.xflags = 0;
  15076. /* operating system */
  15077. this.os = 0;
  15078. /* pointer to extra field or Z_NULL if none */
  15079. this.extra = null;
  15080. /* extra field length (valid if extra != Z_NULL) */
  15081. this.extra_len = 0; // Actually, we don't need it in JS,
  15082. // but leave for few code modifications
  15083. //
  15084. // Setup limits is not necessary because in js we should not preallocate memory
  15085. // for inflate use constant limit in 65536 bytes
  15086. //
  15087. /* space at extra (only when reading header) */
  15088. // this.extra_max = 0;
  15089. /* pointer to zero-terminated file name or Z_NULL */
  15090. this.name = '';
  15091. /* space at name (only when reading header) */
  15092. // this.name_max = 0;
  15093. /* pointer to zero-terminated comment or Z_NULL */
  15094. this.comment = '';
  15095. /* space at comment (only when reading header) */
  15096. // this.comm_max = 0;
  15097. /* true if there was or will be a header crc */
  15098. this.hcrc = 0;
  15099. /* true when done reading gzip header (not used when writing a gzip file) */
  15100. this.done = false;
  15101. }
  15102. module.exports = GZheader;
  15103. },{}],58:[function(require,module,exports){
  15104. 'use strict';
  15105. // See state defs from inflate.js
  15106. var BAD = 30; /* got a data error -- remain here until reset */
  15107. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  15108. /*
  15109. Decode literal, length, and distance codes and write out the resulting
  15110. literal and match bytes until either not enough input or output is
  15111. available, an end-of-block is encountered, or a data error is encountered.
  15112. When large enough input and output buffers are supplied to inflate(), for
  15113. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  15114. inflate execution time is spent in this routine.
  15115. Entry assumptions:
  15116. state.mode === LEN
  15117. strm.avail_in >= 6
  15118. strm.avail_out >= 258
  15119. start >= strm.avail_out
  15120. state.bits < 8
  15121. On return, state.mode is one of:
  15122. LEN -- ran out of enough output space or enough available input
  15123. TYPE -- reached end of block code, inflate() to interpret next block
  15124. BAD -- error in block data
  15125. Notes:
  15126. - The maximum input bits used by a length/distance pair is 15 bits for the
  15127. length code, 5 bits for the length extra, 15 bits for the distance code,
  15128. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  15129. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  15130. checking for available input while decoding.
  15131. - The maximum bytes that a single length/distance pair can output is 258
  15132. bytes, which is the maximum length that can be coded. inflate_fast()
  15133. requires strm.avail_out >= 258 for each loop to avoid checking for
  15134. output space.
  15135. */
  15136. module.exports = function inflate_fast(strm, start) {
  15137. var state;
  15138. var _in; /* local strm.input */
  15139. var last; /* have enough input while in < last */
  15140. var _out; /* local strm.output */
  15141. var beg; /* inflate()'s initial strm.output */
  15142. var end; /* while out < end, enough space available */
  15143. //#ifdef INFLATE_STRICT
  15144. var dmax; /* maximum distance from zlib header */
  15145. //#endif
  15146. var wsize; /* window size or zero if not using window */
  15147. var whave; /* valid bytes in the window */
  15148. var wnext; /* window write index */
  15149. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  15150. var s_window; /* allocated sliding window, if wsize != 0 */
  15151. var hold; /* local strm.hold */
  15152. var bits; /* local strm.bits */
  15153. var lcode; /* local strm.lencode */
  15154. var dcode; /* local strm.distcode */
  15155. var lmask; /* mask for first level of length codes */
  15156. var dmask; /* mask for first level of distance codes */
  15157. var here; /* retrieved table entry */
  15158. var op; /* code bits, operation, extra bits, or */
  15159. /* window position, window bytes to copy */
  15160. var len; /* match length, unused bytes */
  15161. var dist; /* match distance */
  15162. var from; /* where to copy match from */
  15163. var from_source;
  15164. var input, output; // JS specific, because we have no pointers
  15165. /* copy state to local variables */
  15166. state = strm.state;
  15167. //here = state.here;
  15168. _in = strm.next_in;
  15169. input = strm.input;
  15170. last = _in + (strm.avail_in - 5);
  15171. _out = strm.next_out;
  15172. output = strm.output;
  15173. beg = _out - (start - strm.avail_out);
  15174. end = _out + (strm.avail_out - 257);
  15175. //#ifdef INFLATE_STRICT
  15176. dmax = state.dmax;
  15177. //#endif
  15178. wsize = state.wsize;
  15179. whave = state.whave;
  15180. wnext = state.wnext;
  15181. s_window = state.window;
  15182. hold = state.hold;
  15183. bits = state.bits;
  15184. lcode = state.lencode;
  15185. dcode = state.distcode;
  15186. lmask = (1 << state.lenbits) - 1;
  15187. dmask = (1 << state.distbits) - 1;
  15188. /* decode literals and length/distances until end-of-block or not enough
  15189. input data or output space */
  15190. top:
  15191. do {
  15192. if (bits < 15) {
  15193. hold += input[_in++] << bits;
  15194. bits += 8;
  15195. hold += input[_in++] << bits;
  15196. bits += 8;
  15197. }
  15198. here = lcode[hold & lmask];
  15199. dolen:
  15200. for (;;) { // Goto emulation
  15201. op = here >>> 24/*here.bits*/;
  15202. hold >>>= op;
  15203. bits -= op;
  15204. op = (here >>> 16) & 0xff/*here.op*/;
  15205. if (op === 0) { /* literal */
  15206. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  15207. // "inflate: literal '%c'\n" :
  15208. // "inflate: literal 0x%02x\n", here.val));
  15209. output[_out++] = here & 0xffff/*here.val*/;
  15210. }
  15211. else if (op & 16) { /* length base */
  15212. len = here & 0xffff/*here.val*/;
  15213. op &= 15; /* number of extra bits */
  15214. if (op) {
  15215. if (bits < op) {
  15216. hold += input[_in++] << bits;
  15217. bits += 8;
  15218. }
  15219. len += hold & ((1 << op) - 1);
  15220. hold >>>= op;
  15221. bits -= op;
  15222. }
  15223. //Tracevv((stderr, "inflate: length %u\n", len));
  15224. if (bits < 15) {
  15225. hold += input[_in++] << bits;
  15226. bits += 8;
  15227. hold += input[_in++] << bits;
  15228. bits += 8;
  15229. }
  15230. here = dcode[hold & dmask];
  15231. dodist:
  15232. for (;;) { // goto emulation
  15233. op = here >>> 24/*here.bits*/;
  15234. hold >>>= op;
  15235. bits -= op;
  15236. op = (here >>> 16) & 0xff/*here.op*/;
  15237. if (op & 16) { /* distance base */
  15238. dist = here & 0xffff/*here.val*/;
  15239. op &= 15; /* number of extra bits */
  15240. if (bits < op) {
  15241. hold += input[_in++] << bits;
  15242. bits += 8;
  15243. if (bits < op) {
  15244. hold += input[_in++] << bits;
  15245. bits += 8;
  15246. }
  15247. }
  15248. dist += hold & ((1 << op) - 1);
  15249. //#ifdef INFLATE_STRICT
  15250. if (dist > dmax) {
  15251. strm.msg = 'invalid distance too far back';
  15252. state.mode = BAD;
  15253. break top;
  15254. }
  15255. //#endif
  15256. hold >>>= op;
  15257. bits -= op;
  15258. //Tracevv((stderr, "inflate: distance %u\n", dist));
  15259. op = _out - beg; /* max distance in output */
  15260. if (dist > op) { /* see if copy from window */
  15261. op = dist - op; /* distance back in window */
  15262. if (op > whave) {
  15263. if (state.sane) {
  15264. strm.msg = 'invalid distance too far back';
  15265. state.mode = BAD;
  15266. break top;
  15267. }
  15268. // (!) This block is disabled in zlib defailts,
  15269. // don't enable it for binary compatibility
  15270. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  15271. // if (len <= op - whave) {
  15272. // do {
  15273. // output[_out++] = 0;
  15274. // } while (--len);
  15275. // continue top;
  15276. // }
  15277. // len -= op - whave;
  15278. // do {
  15279. // output[_out++] = 0;
  15280. // } while (--op > whave);
  15281. // if (op === 0) {
  15282. // from = _out - dist;
  15283. // do {
  15284. // output[_out++] = output[from++];
  15285. // } while (--len);
  15286. // continue top;
  15287. // }
  15288. //#endif
  15289. }
  15290. from = 0; // window index
  15291. from_source = s_window;
  15292. if (wnext === 0) { /* very common case */
  15293. from += wsize - op;
  15294. if (op < len) { /* some from window */
  15295. len -= op;
  15296. do {
  15297. output[_out++] = s_window[from++];
  15298. } while (--op);
  15299. from = _out - dist; /* rest from output */
  15300. from_source = output;
  15301. }
  15302. }
  15303. else if (wnext < op) { /* wrap around window */
  15304. from += wsize + wnext - op;
  15305. op -= wnext;
  15306. if (op < len) { /* some from end of window */
  15307. len -= op;
  15308. do {
  15309. output[_out++] = s_window[from++];
  15310. } while (--op);
  15311. from = 0;
  15312. if (wnext < len) { /* some from start of window */
  15313. op = wnext;
  15314. len -= op;
  15315. do {
  15316. output[_out++] = s_window[from++];
  15317. } while (--op);
  15318. from = _out - dist; /* rest from output */
  15319. from_source = output;
  15320. }
  15321. }
  15322. }
  15323. else { /* contiguous in window */
  15324. from += wnext - op;
  15325. if (op < len) { /* some from window */
  15326. len -= op;
  15327. do {
  15328. output[_out++] = s_window[from++];
  15329. } while (--op);
  15330. from = _out - dist; /* rest from output */
  15331. from_source = output;
  15332. }
  15333. }
  15334. while (len > 2) {
  15335. output[_out++] = from_source[from++];
  15336. output[_out++] = from_source[from++];
  15337. output[_out++] = from_source[from++];
  15338. len -= 3;
  15339. }
  15340. if (len) {
  15341. output[_out++] = from_source[from++];
  15342. if (len > 1) {
  15343. output[_out++] = from_source[from++];
  15344. }
  15345. }
  15346. }
  15347. else {
  15348. from = _out - dist; /* copy direct from output */
  15349. do { /* minimum length is three */
  15350. output[_out++] = output[from++];
  15351. output[_out++] = output[from++];
  15352. output[_out++] = output[from++];
  15353. len -= 3;
  15354. } while (len > 2);
  15355. if (len) {
  15356. output[_out++] = output[from++];
  15357. if (len > 1) {
  15358. output[_out++] = output[from++];
  15359. }
  15360. }
  15361. }
  15362. }
  15363. else if ((op & 64) === 0) { /* 2nd level distance code */
  15364. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  15365. continue dodist;
  15366. }
  15367. else {
  15368. strm.msg = 'invalid distance code';
  15369. state.mode = BAD;
  15370. break top;
  15371. }
  15372. break; // need to emulate goto via "continue"
  15373. }
  15374. }
  15375. else if ((op & 64) === 0) { /* 2nd level length code */
  15376. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  15377. continue dolen;
  15378. }
  15379. else if (op & 32) { /* end-of-block */
  15380. //Tracevv((stderr, "inflate: end of block\n"));
  15381. state.mode = TYPE;
  15382. break top;
  15383. }
  15384. else {
  15385. strm.msg = 'invalid literal/length code';
  15386. state.mode = BAD;
  15387. break top;
  15388. }
  15389. break; // need to emulate goto via "continue"
  15390. }
  15391. } while (_in < last && _out < end);
  15392. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  15393. len = bits >> 3;
  15394. _in -= len;
  15395. bits -= len << 3;
  15396. hold &= (1 << bits) - 1;
  15397. /* update state and return */
  15398. strm.next_in = _in;
  15399. strm.next_out = _out;
  15400. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  15401. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  15402. state.hold = hold;
  15403. state.bits = bits;
  15404. return;
  15405. };
  15406. },{}],59:[function(require,module,exports){
  15407. 'use strict';
  15408. var utils = require('../utils/common');
  15409. var adler32 = require('./adler32');
  15410. var crc32 = require('./crc32');
  15411. var inflate_fast = require('./inffast');
  15412. var inflate_table = require('./inftrees');
  15413. var CODES = 0;
  15414. var LENS = 1;
  15415. var DISTS = 2;
  15416. /* Public constants ==========================================================*/
  15417. /* ===========================================================================*/
  15418. /* Allowed flush values; see deflate() and inflate() below for details */
  15419. //var Z_NO_FLUSH = 0;
  15420. //var Z_PARTIAL_FLUSH = 1;
  15421. //var Z_SYNC_FLUSH = 2;
  15422. //var Z_FULL_FLUSH = 3;
  15423. var Z_FINISH = 4;
  15424. var Z_BLOCK = 5;
  15425. var Z_TREES = 6;
  15426. /* Return codes for the compression/decompression functions. Negative values
  15427. * are errors, positive values are used for special but normal events.
  15428. */
  15429. var Z_OK = 0;
  15430. var Z_STREAM_END = 1;
  15431. var Z_NEED_DICT = 2;
  15432. //var Z_ERRNO = -1;
  15433. var Z_STREAM_ERROR = -2;
  15434. var Z_DATA_ERROR = -3;
  15435. var Z_MEM_ERROR = -4;
  15436. var Z_BUF_ERROR = -5;
  15437. //var Z_VERSION_ERROR = -6;
  15438. /* The deflate compression method */
  15439. var Z_DEFLATED = 8;
  15440. /* STATES ====================================================================*/
  15441. /* ===========================================================================*/
  15442. var HEAD = 1; /* i: waiting for magic header */
  15443. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  15444. var TIME = 3; /* i: waiting for modification time (gzip) */
  15445. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  15446. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  15447. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  15448. var NAME = 7; /* i: waiting for end of file name (gzip) */
  15449. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  15450. var HCRC = 9; /* i: waiting for header crc (gzip) */
  15451. var DICTID = 10; /* i: waiting for dictionary check value */
  15452. var DICT = 11; /* waiting for inflateSetDictionary() call */
  15453. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  15454. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  15455. var STORED = 14; /* i: waiting for stored size (length and complement) */
  15456. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  15457. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  15458. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  15459. var LENLENS = 18; /* i: waiting for code length code lengths */
  15460. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  15461. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  15462. var LEN = 21; /* i: waiting for length/lit/eob code */
  15463. var LENEXT = 22; /* i: waiting for length extra bits */
  15464. var DIST = 23; /* i: waiting for distance code */
  15465. var DISTEXT = 24; /* i: waiting for distance extra bits */
  15466. var MATCH = 25; /* o: waiting for output space to copy string */
  15467. var LIT = 26; /* o: waiting for output space to write literal */
  15468. var CHECK = 27; /* i: waiting for 32-bit check value */
  15469. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  15470. var DONE = 29; /* finished check, done -- remain here until reset */
  15471. var BAD = 30; /* got a data error -- remain here until reset */
  15472. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  15473. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  15474. /* ===========================================================================*/
  15475. var ENOUGH_LENS = 852;
  15476. var ENOUGH_DISTS = 592;
  15477. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  15478. var MAX_WBITS = 15;
  15479. /* 32K LZ77 window */
  15480. var DEF_WBITS = MAX_WBITS;
  15481. function ZSWAP32(q) {
  15482. return (((q >>> 24) & 0xff) +
  15483. ((q >>> 8) & 0xff00) +
  15484. ((q & 0xff00) << 8) +
  15485. ((q & 0xff) << 24));
  15486. }
  15487. function InflateState() {
  15488. this.mode = 0; /* current inflate mode */
  15489. this.last = false; /* true if processing last block */
  15490. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  15491. this.havedict = false; /* true if dictionary provided */
  15492. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  15493. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  15494. this.check = 0; /* protected copy of check value */
  15495. this.total = 0; /* protected copy of output count */
  15496. // TODO: may be {}
  15497. this.head = null; /* where to save gzip header information */
  15498. /* sliding window */
  15499. this.wbits = 0; /* log base 2 of requested window size */
  15500. this.wsize = 0; /* window size or zero if not using window */
  15501. this.whave = 0; /* valid bytes in the window */
  15502. this.wnext = 0; /* window write index */
  15503. this.window = null; /* allocated sliding window, if needed */
  15504. /* bit accumulator */
  15505. this.hold = 0; /* input bit accumulator */
  15506. this.bits = 0; /* number of bits in "in" */
  15507. /* for string and stored block copying */
  15508. this.length = 0; /* literal or length of data to copy */
  15509. this.offset = 0; /* distance back to copy string from */
  15510. /* for table and code decoding */
  15511. this.extra = 0; /* extra bits needed */
  15512. /* fixed and dynamic code tables */
  15513. this.lencode = null; /* starting table for length/literal codes */
  15514. this.distcode = null; /* starting table for distance codes */
  15515. this.lenbits = 0; /* index bits for lencode */
  15516. this.distbits = 0; /* index bits for distcode */
  15517. /* dynamic table building */
  15518. this.ncode = 0; /* number of code length code lengths */
  15519. this.nlen = 0; /* number of length code lengths */
  15520. this.ndist = 0; /* number of distance code lengths */
  15521. this.have = 0; /* number of code lengths in lens[] */
  15522. this.next = null; /* next available space in codes[] */
  15523. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  15524. this.work = new utils.Buf16(288); /* work area for code table building */
  15525. /*
  15526. because we don't have pointers in js, we use lencode and distcode directly
  15527. as buffers so we don't need codes
  15528. */
  15529. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  15530. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  15531. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  15532. this.sane = 0; /* if false, allow invalid distance too far */
  15533. this.back = 0; /* bits back of last unprocessed length/lit */
  15534. this.was = 0; /* initial length of match */
  15535. }
  15536. function inflateResetKeep(strm) {
  15537. var state;
  15538. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15539. state = strm.state;
  15540. strm.total_in = strm.total_out = state.total = 0;
  15541. strm.msg = ''; /*Z_NULL*/
  15542. if (state.wrap) { /* to support ill-conceived Java test suite */
  15543. strm.adler = state.wrap & 1;
  15544. }
  15545. state.mode = HEAD;
  15546. state.last = 0;
  15547. state.havedict = 0;
  15548. state.dmax = 32768;
  15549. state.head = null/*Z_NULL*/;
  15550. state.hold = 0;
  15551. state.bits = 0;
  15552. //state.lencode = state.distcode = state.next = state.codes;
  15553. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  15554. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  15555. state.sane = 1;
  15556. state.back = -1;
  15557. //Tracev((stderr, "inflate: reset\n"));
  15558. return Z_OK;
  15559. }
  15560. function inflateReset(strm) {
  15561. var state;
  15562. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15563. state = strm.state;
  15564. state.wsize = 0;
  15565. state.whave = 0;
  15566. state.wnext = 0;
  15567. return inflateResetKeep(strm);
  15568. }
  15569. function inflateReset2(strm, windowBits) {
  15570. var wrap;
  15571. var state;
  15572. /* get the state */
  15573. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15574. state = strm.state;
  15575. /* extract wrap request from windowBits parameter */
  15576. if (windowBits < 0) {
  15577. wrap = 0;
  15578. windowBits = -windowBits;
  15579. }
  15580. else {
  15581. wrap = (windowBits >> 4) + 1;
  15582. if (windowBits < 48) {
  15583. windowBits &= 15;
  15584. }
  15585. }
  15586. /* set number of window bits, free window if different */
  15587. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  15588. return Z_STREAM_ERROR;
  15589. }
  15590. if (state.window !== null && state.wbits !== windowBits) {
  15591. state.window = null;
  15592. }
  15593. /* update state and reset the rest of it */
  15594. state.wrap = wrap;
  15595. state.wbits = windowBits;
  15596. return inflateReset(strm);
  15597. }
  15598. function inflateInit2(strm, windowBits) {
  15599. var ret;
  15600. var state;
  15601. if (!strm) { return Z_STREAM_ERROR; }
  15602. //strm.msg = Z_NULL; /* in case we return an error */
  15603. state = new InflateState();
  15604. //if (state === Z_NULL) return Z_MEM_ERROR;
  15605. //Tracev((stderr, "inflate: allocated\n"));
  15606. strm.state = state;
  15607. state.window = null/*Z_NULL*/;
  15608. ret = inflateReset2(strm, windowBits);
  15609. if (ret !== Z_OK) {
  15610. strm.state = null/*Z_NULL*/;
  15611. }
  15612. return ret;
  15613. }
  15614. function inflateInit(strm) {
  15615. return inflateInit2(strm, DEF_WBITS);
  15616. }
  15617. /*
  15618. Return state with length and distance decoding tables and index sizes set to
  15619. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  15620. If BUILDFIXED is defined, then instead this routine builds the tables the
  15621. first time it's called, and returns those tables the first time and
  15622. thereafter. This reduces the size of the code by about 2K bytes, in
  15623. exchange for a little execution time. However, BUILDFIXED should not be
  15624. used for threaded applications, since the rewriting of the tables and virgin
  15625. may not be thread-safe.
  15626. */
  15627. var virgin = true;
  15628. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  15629. function fixedtables(state) {
  15630. /* build fixed huffman tables if first call (may not be thread safe) */
  15631. if (virgin) {
  15632. var sym;
  15633. lenfix = new utils.Buf32(512);
  15634. distfix = new utils.Buf32(32);
  15635. /* literal/length table */
  15636. sym = 0;
  15637. while (sym < 144) { state.lens[sym++] = 8; }
  15638. while (sym < 256) { state.lens[sym++] = 9; }
  15639. while (sym < 280) { state.lens[sym++] = 7; }
  15640. while (sym < 288) { state.lens[sym++] = 8; }
  15641. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  15642. /* distance table */
  15643. sym = 0;
  15644. while (sym < 32) { state.lens[sym++] = 5; }
  15645. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  15646. /* do this just once */
  15647. virgin = false;
  15648. }
  15649. state.lencode = lenfix;
  15650. state.lenbits = 9;
  15651. state.distcode = distfix;
  15652. state.distbits = 5;
  15653. }
  15654. /*
  15655. Update the window with the last wsize (normally 32K) bytes written before
  15656. returning. If window does not exist yet, create it. This is only called
  15657. when a window is already in use, or when output has been written during this
  15658. inflate call, but the end of the deflate stream has not been reached yet.
  15659. It is also called to create a window for dictionary data when a dictionary
  15660. is loaded.
  15661. Providing output buffers larger than 32K to inflate() should provide a speed
  15662. advantage, since only the last 32K of output is copied to the sliding window
  15663. upon return from inflate(), and since all distances after the first 32K of
  15664. output will fall in the output data, making match copies simpler and faster.
  15665. The advantage may be dependent on the size of the processor's data caches.
  15666. */
  15667. function updatewindow(strm, src, end, copy) {
  15668. var dist;
  15669. var state = strm.state;
  15670. /* if it hasn't been done already, allocate space for the window */
  15671. if (state.window === null) {
  15672. state.wsize = 1 << state.wbits;
  15673. state.wnext = 0;
  15674. state.whave = 0;
  15675. state.window = new utils.Buf8(state.wsize);
  15676. }
  15677. /* copy state->wsize or less output bytes into the circular window */
  15678. if (copy >= state.wsize) {
  15679. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  15680. state.wnext = 0;
  15681. state.whave = state.wsize;
  15682. }
  15683. else {
  15684. dist = state.wsize - state.wnext;
  15685. if (dist > copy) {
  15686. dist = copy;
  15687. }
  15688. //zmemcpy(state->window + state->wnext, end - copy, dist);
  15689. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  15690. copy -= dist;
  15691. if (copy) {
  15692. //zmemcpy(state->window, end - copy, copy);
  15693. utils.arraySet(state.window,src, end - copy, copy, 0);
  15694. state.wnext = copy;
  15695. state.whave = state.wsize;
  15696. }
  15697. else {
  15698. state.wnext += dist;
  15699. if (state.wnext === state.wsize) { state.wnext = 0; }
  15700. if (state.whave < state.wsize) { state.whave += dist; }
  15701. }
  15702. }
  15703. return 0;
  15704. }
  15705. function inflate(strm, flush) {
  15706. var state;
  15707. var input, output; // input/output buffers
  15708. var next; /* next input INDEX */
  15709. var put; /* next output INDEX */
  15710. var have, left; /* available input and output */
  15711. var hold; /* bit buffer */
  15712. var bits; /* bits in bit buffer */
  15713. var _in, _out; /* save starting available input and output */
  15714. var copy; /* number of stored or match bytes to copy */
  15715. var from; /* where to copy match bytes from */
  15716. var from_source;
  15717. var here = 0; /* current decoding table entry */
  15718. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  15719. //var last; /* parent table entry */
  15720. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  15721. var len; /* length to copy for repeats, bits to drop */
  15722. var ret; /* return code */
  15723. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  15724. var opts;
  15725. var n; // temporary var for NEED_BITS
  15726. var order = /* permutation of code lengths */
  15727. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  15728. if (!strm || !strm.state || !strm.output ||
  15729. (!strm.input && strm.avail_in !== 0)) {
  15730. return Z_STREAM_ERROR;
  15731. }
  15732. state = strm.state;
  15733. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  15734. //--- LOAD() ---
  15735. put = strm.next_out;
  15736. output = strm.output;
  15737. left = strm.avail_out;
  15738. next = strm.next_in;
  15739. input = strm.input;
  15740. have = strm.avail_in;
  15741. hold = state.hold;
  15742. bits = state.bits;
  15743. //---
  15744. _in = have;
  15745. _out = left;
  15746. ret = Z_OK;
  15747. inf_leave: // goto emulation
  15748. for (;;) {
  15749. switch (state.mode) {
  15750. case HEAD:
  15751. if (state.wrap === 0) {
  15752. state.mode = TYPEDO;
  15753. break;
  15754. }
  15755. //=== NEEDBITS(16);
  15756. while (bits < 16) {
  15757. if (have === 0) { break inf_leave; }
  15758. have--;
  15759. hold += input[next++] << bits;
  15760. bits += 8;
  15761. }
  15762. //===//
  15763. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  15764. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  15765. //=== CRC2(state.check, hold);
  15766. hbuf[0] = hold & 0xff;
  15767. hbuf[1] = (hold >>> 8) & 0xff;
  15768. state.check = crc32(state.check, hbuf, 2, 0);
  15769. //===//
  15770. //=== INITBITS();
  15771. hold = 0;
  15772. bits = 0;
  15773. //===//
  15774. state.mode = FLAGS;
  15775. break;
  15776. }
  15777. state.flags = 0; /* expect zlib header */
  15778. if (state.head) {
  15779. state.head.done = false;
  15780. }
  15781. if (!(state.wrap & 1) || /* check if zlib header allowed */
  15782. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  15783. strm.msg = 'incorrect header check';
  15784. state.mode = BAD;
  15785. break;
  15786. }
  15787. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  15788. strm.msg = 'unknown compression method';
  15789. state.mode = BAD;
  15790. break;
  15791. }
  15792. //--- DROPBITS(4) ---//
  15793. hold >>>= 4;
  15794. bits -= 4;
  15795. //---//
  15796. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  15797. if (state.wbits === 0) {
  15798. state.wbits = len;
  15799. }
  15800. else if (len > state.wbits) {
  15801. strm.msg = 'invalid window size';
  15802. state.mode = BAD;
  15803. break;
  15804. }
  15805. state.dmax = 1 << len;
  15806. //Tracev((stderr, "inflate: zlib header ok\n"));
  15807. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  15808. state.mode = hold & 0x200 ? DICTID : TYPE;
  15809. //=== INITBITS();
  15810. hold = 0;
  15811. bits = 0;
  15812. //===//
  15813. break;
  15814. case FLAGS:
  15815. //=== NEEDBITS(16); */
  15816. while (bits < 16) {
  15817. if (have === 0) { break inf_leave; }
  15818. have--;
  15819. hold += input[next++] << bits;
  15820. bits += 8;
  15821. }
  15822. //===//
  15823. state.flags = hold;
  15824. if ((state.flags & 0xff) !== Z_DEFLATED) {
  15825. strm.msg = 'unknown compression method';
  15826. state.mode = BAD;
  15827. break;
  15828. }
  15829. if (state.flags & 0xe000) {
  15830. strm.msg = 'unknown header flags set';
  15831. state.mode = BAD;
  15832. break;
  15833. }
  15834. if (state.head) {
  15835. state.head.text = ((hold >> 8) & 1);
  15836. }
  15837. if (state.flags & 0x0200) {
  15838. //=== CRC2(state.check, hold);
  15839. hbuf[0] = hold & 0xff;
  15840. hbuf[1] = (hold >>> 8) & 0xff;
  15841. state.check = crc32(state.check, hbuf, 2, 0);
  15842. //===//
  15843. }
  15844. //=== INITBITS();
  15845. hold = 0;
  15846. bits = 0;
  15847. //===//
  15848. state.mode = TIME;
  15849. /* falls through */
  15850. case TIME:
  15851. //=== NEEDBITS(32); */
  15852. while (bits < 32) {
  15853. if (have === 0) { break inf_leave; }
  15854. have--;
  15855. hold += input[next++] << bits;
  15856. bits += 8;
  15857. }
  15858. //===//
  15859. if (state.head) {
  15860. state.head.time = hold;
  15861. }
  15862. if (state.flags & 0x0200) {
  15863. //=== CRC4(state.check, hold)
  15864. hbuf[0] = hold & 0xff;
  15865. hbuf[1] = (hold >>> 8) & 0xff;
  15866. hbuf[2] = (hold >>> 16) & 0xff;
  15867. hbuf[3] = (hold >>> 24) & 0xff;
  15868. state.check = crc32(state.check, hbuf, 4, 0);
  15869. //===
  15870. }
  15871. //=== INITBITS();
  15872. hold = 0;
  15873. bits = 0;
  15874. //===//
  15875. state.mode = OS;
  15876. /* falls through */
  15877. case OS:
  15878. //=== NEEDBITS(16); */
  15879. while (bits < 16) {
  15880. if (have === 0) { break inf_leave; }
  15881. have--;
  15882. hold += input[next++] << bits;
  15883. bits += 8;
  15884. }
  15885. //===//
  15886. if (state.head) {
  15887. state.head.xflags = (hold & 0xff);
  15888. state.head.os = (hold >> 8);
  15889. }
  15890. if (state.flags & 0x0200) {
  15891. //=== CRC2(state.check, hold);
  15892. hbuf[0] = hold & 0xff;
  15893. hbuf[1] = (hold >>> 8) & 0xff;
  15894. state.check = crc32(state.check, hbuf, 2, 0);
  15895. //===//
  15896. }
  15897. //=== INITBITS();
  15898. hold = 0;
  15899. bits = 0;
  15900. //===//
  15901. state.mode = EXLEN;
  15902. /* falls through */
  15903. case EXLEN:
  15904. if (state.flags & 0x0400) {
  15905. //=== NEEDBITS(16); */
  15906. while (bits < 16) {
  15907. if (have === 0) { break inf_leave; }
  15908. have--;
  15909. hold += input[next++] << bits;
  15910. bits += 8;
  15911. }
  15912. //===//
  15913. state.length = hold;
  15914. if (state.head) {
  15915. state.head.extra_len = hold;
  15916. }
  15917. if (state.flags & 0x0200) {
  15918. //=== CRC2(state.check, hold);
  15919. hbuf[0] = hold & 0xff;
  15920. hbuf[1] = (hold >>> 8) & 0xff;
  15921. state.check = crc32(state.check, hbuf, 2, 0);
  15922. //===//
  15923. }
  15924. //=== INITBITS();
  15925. hold = 0;
  15926. bits = 0;
  15927. //===//
  15928. }
  15929. else if (state.head) {
  15930. state.head.extra = null/*Z_NULL*/;
  15931. }
  15932. state.mode = EXTRA;
  15933. /* falls through */
  15934. case EXTRA:
  15935. if (state.flags & 0x0400) {
  15936. copy = state.length;
  15937. if (copy > have) { copy = have; }
  15938. if (copy) {
  15939. if (state.head) {
  15940. len = state.head.extra_len - state.length;
  15941. if (!state.head.extra) {
  15942. // Use untyped array for more conveniend processing later
  15943. state.head.extra = new Array(state.head.extra_len);
  15944. }
  15945. utils.arraySet(
  15946. state.head.extra,
  15947. input,
  15948. next,
  15949. // extra field is limited to 65536 bytes
  15950. // - no need for additional size check
  15951. copy,
  15952. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  15953. len
  15954. );
  15955. //zmemcpy(state.head.extra + len, next,
  15956. // len + copy > state.head.extra_max ?
  15957. // state.head.extra_max - len : copy);
  15958. }
  15959. if (state.flags & 0x0200) {
  15960. state.check = crc32(state.check, input, copy, next);
  15961. }
  15962. have -= copy;
  15963. next += copy;
  15964. state.length -= copy;
  15965. }
  15966. if (state.length) { break inf_leave; }
  15967. }
  15968. state.length = 0;
  15969. state.mode = NAME;
  15970. /* falls through */
  15971. case NAME:
  15972. if (state.flags & 0x0800) {
  15973. if (have === 0) { break inf_leave; }
  15974. copy = 0;
  15975. do {
  15976. // TODO: 2 or 1 bytes?
  15977. len = input[next + copy++];
  15978. /* use constant limit because in js we should not preallocate memory */
  15979. if (state.head && len &&
  15980. (state.length < 65536 /*state.head.name_max*/)) {
  15981. state.head.name += String.fromCharCode(len);
  15982. }
  15983. } while (len && copy < have);
  15984. if (state.flags & 0x0200) {
  15985. state.check = crc32(state.check, input, copy, next);
  15986. }
  15987. have -= copy;
  15988. next += copy;
  15989. if (len) { break inf_leave; }
  15990. }
  15991. else if (state.head) {
  15992. state.head.name = null;
  15993. }
  15994. state.length = 0;
  15995. state.mode = COMMENT;
  15996. /* falls through */
  15997. case COMMENT:
  15998. if (state.flags & 0x1000) {
  15999. if (have === 0) { break inf_leave; }
  16000. copy = 0;
  16001. do {
  16002. len = input[next + copy++];
  16003. /* use constant limit because in js we should not preallocate memory */
  16004. if (state.head && len &&
  16005. (state.length < 65536 /*state.head.comm_max*/)) {
  16006. state.head.comment += String.fromCharCode(len);
  16007. }
  16008. } while (len && copy < have);
  16009. if (state.flags & 0x0200) {
  16010. state.check = crc32(state.check, input, copy, next);
  16011. }
  16012. have -= copy;
  16013. next += copy;
  16014. if (len) { break inf_leave; }
  16015. }
  16016. else if (state.head) {
  16017. state.head.comment = null;
  16018. }
  16019. state.mode = HCRC;
  16020. /* falls through */
  16021. case HCRC:
  16022. if (state.flags & 0x0200) {
  16023. //=== NEEDBITS(16); */
  16024. while (bits < 16) {
  16025. if (have === 0) { break inf_leave; }
  16026. have--;
  16027. hold += input[next++] << bits;
  16028. bits += 8;
  16029. }
  16030. //===//
  16031. if (hold !== (state.check & 0xffff)) {
  16032. strm.msg = 'header crc mismatch';
  16033. state.mode = BAD;
  16034. break;
  16035. }
  16036. //=== INITBITS();
  16037. hold = 0;
  16038. bits = 0;
  16039. //===//
  16040. }
  16041. if (state.head) {
  16042. state.head.hcrc = ((state.flags >> 9) & 1);
  16043. state.head.done = true;
  16044. }
  16045. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  16046. state.mode = TYPE;
  16047. break;
  16048. case DICTID:
  16049. //=== NEEDBITS(32); */
  16050. while (bits < 32) {
  16051. if (have === 0) { break inf_leave; }
  16052. have--;
  16053. hold += input[next++] << bits;
  16054. bits += 8;
  16055. }
  16056. //===//
  16057. strm.adler = state.check = ZSWAP32(hold);
  16058. //=== INITBITS();
  16059. hold = 0;
  16060. bits = 0;
  16061. //===//
  16062. state.mode = DICT;
  16063. /* falls through */
  16064. case DICT:
  16065. if (state.havedict === 0) {
  16066. //--- RESTORE() ---
  16067. strm.next_out = put;
  16068. strm.avail_out = left;
  16069. strm.next_in = next;
  16070. strm.avail_in = have;
  16071. state.hold = hold;
  16072. state.bits = bits;
  16073. //---
  16074. return Z_NEED_DICT;
  16075. }
  16076. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  16077. state.mode = TYPE;
  16078. /* falls through */
  16079. case TYPE:
  16080. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  16081. /* falls through */
  16082. case TYPEDO:
  16083. if (state.last) {
  16084. //--- BYTEBITS() ---//
  16085. hold >>>= bits & 7;
  16086. bits -= bits & 7;
  16087. //---//
  16088. state.mode = CHECK;
  16089. break;
  16090. }
  16091. //=== NEEDBITS(3); */
  16092. while (bits < 3) {
  16093. if (have === 0) { break inf_leave; }
  16094. have--;
  16095. hold += input[next++] << bits;
  16096. bits += 8;
  16097. }
  16098. //===//
  16099. state.last = (hold & 0x01)/*BITS(1)*/;
  16100. //--- DROPBITS(1) ---//
  16101. hold >>>= 1;
  16102. bits -= 1;
  16103. //---//
  16104. switch ((hold & 0x03)/*BITS(2)*/) {
  16105. case 0: /* stored block */
  16106. //Tracev((stderr, "inflate: stored block%s\n",
  16107. // state.last ? " (last)" : ""));
  16108. state.mode = STORED;
  16109. break;
  16110. case 1: /* fixed block */
  16111. fixedtables(state);
  16112. //Tracev((stderr, "inflate: fixed codes block%s\n",
  16113. // state.last ? " (last)" : ""));
  16114. state.mode = LEN_; /* decode codes */
  16115. if (flush === Z_TREES) {
  16116. //--- DROPBITS(2) ---//
  16117. hold >>>= 2;
  16118. bits -= 2;
  16119. //---//
  16120. break inf_leave;
  16121. }
  16122. break;
  16123. case 2: /* dynamic block */
  16124. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  16125. // state.last ? " (last)" : ""));
  16126. state.mode = TABLE;
  16127. break;
  16128. case 3:
  16129. strm.msg = 'invalid block type';
  16130. state.mode = BAD;
  16131. }
  16132. //--- DROPBITS(2) ---//
  16133. hold >>>= 2;
  16134. bits -= 2;
  16135. //---//
  16136. break;
  16137. case STORED:
  16138. //--- BYTEBITS() ---// /* go to byte boundary */
  16139. hold >>>= bits & 7;
  16140. bits -= bits & 7;
  16141. //---//
  16142. //=== NEEDBITS(32); */
  16143. while (bits < 32) {
  16144. if (have === 0) { break inf_leave; }
  16145. have--;
  16146. hold += input[next++] << bits;
  16147. bits += 8;
  16148. }
  16149. //===//
  16150. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  16151. strm.msg = 'invalid stored block lengths';
  16152. state.mode = BAD;
  16153. break;
  16154. }
  16155. state.length = hold & 0xffff;
  16156. //Tracev((stderr, "inflate: stored length %u\n",
  16157. // state.length));
  16158. //=== INITBITS();
  16159. hold = 0;
  16160. bits = 0;
  16161. //===//
  16162. state.mode = COPY_;
  16163. if (flush === Z_TREES) { break inf_leave; }
  16164. /* falls through */
  16165. case COPY_:
  16166. state.mode = COPY;
  16167. /* falls through */
  16168. case COPY:
  16169. copy = state.length;
  16170. if (copy) {
  16171. if (copy > have) { copy = have; }
  16172. if (copy > left) { copy = left; }
  16173. if (copy === 0) { break inf_leave; }
  16174. //--- zmemcpy(put, next, copy); ---
  16175. utils.arraySet(output, input, next, copy, put);
  16176. //---//
  16177. have -= copy;
  16178. next += copy;
  16179. left -= copy;
  16180. put += copy;
  16181. state.length -= copy;
  16182. break;
  16183. }
  16184. //Tracev((stderr, "inflate: stored end\n"));
  16185. state.mode = TYPE;
  16186. break;
  16187. case TABLE:
  16188. //=== NEEDBITS(14); */
  16189. while (bits < 14) {
  16190. if (have === 0) { break inf_leave; }
  16191. have--;
  16192. hold += input[next++] << bits;
  16193. bits += 8;
  16194. }
  16195. //===//
  16196. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  16197. //--- DROPBITS(5) ---//
  16198. hold >>>= 5;
  16199. bits -= 5;
  16200. //---//
  16201. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  16202. //--- DROPBITS(5) ---//
  16203. hold >>>= 5;
  16204. bits -= 5;
  16205. //---//
  16206. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  16207. //--- DROPBITS(4) ---//
  16208. hold >>>= 4;
  16209. bits -= 4;
  16210. //---//
  16211. //#ifndef PKZIP_BUG_WORKAROUND
  16212. if (state.nlen > 286 || state.ndist > 30) {
  16213. strm.msg = 'too many length or distance symbols';
  16214. state.mode = BAD;
  16215. break;
  16216. }
  16217. //#endif
  16218. //Tracev((stderr, "inflate: table sizes ok\n"));
  16219. state.have = 0;
  16220. state.mode = LENLENS;
  16221. /* falls through */
  16222. case LENLENS:
  16223. while (state.have < state.ncode) {
  16224. //=== NEEDBITS(3);
  16225. while (bits < 3) {
  16226. if (have === 0) { break inf_leave; }
  16227. have--;
  16228. hold += input[next++] << bits;
  16229. bits += 8;
  16230. }
  16231. //===//
  16232. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  16233. //--- DROPBITS(3) ---//
  16234. hold >>>= 3;
  16235. bits -= 3;
  16236. //---//
  16237. }
  16238. while (state.have < 19) {
  16239. state.lens[order[state.have++]] = 0;
  16240. }
  16241. // We have separate tables & no pointers. 2 commented lines below not needed.
  16242. //state.next = state.codes;
  16243. //state.lencode = state.next;
  16244. // Switch to use dynamic table
  16245. state.lencode = state.lendyn;
  16246. state.lenbits = 7;
  16247. opts = {bits: state.lenbits};
  16248. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  16249. state.lenbits = opts.bits;
  16250. if (ret) {
  16251. strm.msg = 'invalid code lengths set';
  16252. state.mode = BAD;
  16253. break;
  16254. }
  16255. //Tracev((stderr, "inflate: code lengths ok\n"));
  16256. state.have = 0;
  16257. state.mode = CODELENS;
  16258. /* falls through */
  16259. case CODELENS:
  16260. while (state.have < state.nlen + state.ndist) {
  16261. for (;;) {
  16262. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  16263. here_bits = here >>> 24;
  16264. here_op = (here >>> 16) & 0xff;
  16265. here_val = here & 0xffff;
  16266. if ((here_bits) <= bits) { break; }
  16267. //--- PULLBYTE() ---//
  16268. if (have === 0) { break inf_leave; }
  16269. have--;
  16270. hold += input[next++] << bits;
  16271. bits += 8;
  16272. //---//
  16273. }
  16274. if (here_val < 16) {
  16275. //--- DROPBITS(here.bits) ---//
  16276. hold >>>= here_bits;
  16277. bits -= here_bits;
  16278. //---//
  16279. state.lens[state.have++] = here_val;
  16280. }
  16281. else {
  16282. if (here_val === 16) {
  16283. //=== NEEDBITS(here.bits + 2);
  16284. n = here_bits + 2;
  16285. while (bits < n) {
  16286. if (have === 0) { break inf_leave; }
  16287. have--;
  16288. hold += input[next++] << bits;
  16289. bits += 8;
  16290. }
  16291. //===//
  16292. //--- DROPBITS(here.bits) ---//
  16293. hold >>>= here_bits;
  16294. bits -= here_bits;
  16295. //---//
  16296. if (state.have === 0) {
  16297. strm.msg = 'invalid bit length repeat';
  16298. state.mode = BAD;
  16299. break;
  16300. }
  16301. len = state.lens[state.have - 1];
  16302. copy = 3 + (hold & 0x03);//BITS(2);
  16303. //--- DROPBITS(2) ---//
  16304. hold >>>= 2;
  16305. bits -= 2;
  16306. //---//
  16307. }
  16308. else if (here_val === 17) {
  16309. //=== NEEDBITS(here.bits + 3);
  16310. n = here_bits + 3;
  16311. while (bits < n) {
  16312. if (have === 0) { break inf_leave; }
  16313. have--;
  16314. hold += input[next++] << bits;
  16315. bits += 8;
  16316. }
  16317. //===//
  16318. //--- DROPBITS(here.bits) ---//
  16319. hold >>>= here_bits;
  16320. bits -= here_bits;
  16321. //---//
  16322. len = 0;
  16323. copy = 3 + (hold & 0x07);//BITS(3);
  16324. //--- DROPBITS(3) ---//
  16325. hold >>>= 3;
  16326. bits -= 3;
  16327. //---//
  16328. }
  16329. else {
  16330. //=== NEEDBITS(here.bits + 7);
  16331. n = here_bits + 7;
  16332. while (bits < n) {
  16333. if (have === 0) { break inf_leave; }
  16334. have--;
  16335. hold += input[next++] << bits;
  16336. bits += 8;
  16337. }
  16338. //===//
  16339. //--- DROPBITS(here.bits) ---//
  16340. hold >>>= here_bits;
  16341. bits -= here_bits;
  16342. //---//
  16343. len = 0;
  16344. copy = 11 + (hold & 0x7f);//BITS(7);
  16345. //--- DROPBITS(7) ---//
  16346. hold >>>= 7;
  16347. bits -= 7;
  16348. //---//
  16349. }
  16350. if (state.have + copy > state.nlen + state.ndist) {
  16351. strm.msg = 'invalid bit length repeat';
  16352. state.mode = BAD;
  16353. break;
  16354. }
  16355. while (copy--) {
  16356. state.lens[state.have++] = len;
  16357. }
  16358. }
  16359. }
  16360. /* handle error breaks in while */
  16361. if (state.mode === BAD) { break; }
  16362. /* check for end-of-block code (better have one) */
  16363. if (state.lens[256] === 0) {
  16364. strm.msg = 'invalid code -- missing end-of-block';
  16365. state.mode = BAD;
  16366. break;
  16367. }
  16368. /* build code tables -- note: do not change the lenbits or distbits
  16369. values here (9 and 6) without reading the comments in inftrees.h
  16370. concerning the ENOUGH constants, which depend on those values */
  16371. state.lenbits = 9;
  16372. opts = {bits: state.lenbits};
  16373. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  16374. // We have separate tables & no pointers. 2 commented lines below not needed.
  16375. // state.next_index = opts.table_index;
  16376. state.lenbits = opts.bits;
  16377. // state.lencode = state.next;
  16378. if (ret) {
  16379. strm.msg = 'invalid literal/lengths set';
  16380. state.mode = BAD;
  16381. break;
  16382. }
  16383. state.distbits = 6;
  16384. //state.distcode.copy(state.codes);
  16385. // Switch to use dynamic table
  16386. state.distcode = state.distdyn;
  16387. opts = {bits: state.distbits};
  16388. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  16389. // We have separate tables & no pointers. 2 commented lines below not needed.
  16390. // state.next_index = opts.table_index;
  16391. state.distbits = opts.bits;
  16392. // state.distcode = state.next;
  16393. if (ret) {
  16394. strm.msg = 'invalid distances set';
  16395. state.mode = BAD;
  16396. break;
  16397. }
  16398. //Tracev((stderr, 'inflate: codes ok\n'));
  16399. state.mode = LEN_;
  16400. if (flush === Z_TREES) { break inf_leave; }
  16401. /* falls through */
  16402. case LEN_:
  16403. state.mode = LEN;
  16404. /* falls through */
  16405. case LEN:
  16406. if (have >= 6 && left >= 258) {
  16407. //--- RESTORE() ---
  16408. strm.next_out = put;
  16409. strm.avail_out = left;
  16410. strm.next_in = next;
  16411. strm.avail_in = have;
  16412. state.hold = hold;
  16413. state.bits = bits;
  16414. //---
  16415. inflate_fast(strm, _out);
  16416. //--- LOAD() ---
  16417. put = strm.next_out;
  16418. output = strm.output;
  16419. left = strm.avail_out;
  16420. next = strm.next_in;
  16421. input = strm.input;
  16422. have = strm.avail_in;
  16423. hold = state.hold;
  16424. bits = state.bits;
  16425. //---
  16426. if (state.mode === TYPE) {
  16427. state.back = -1;
  16428. }
  16429. break;
  16430. }
  16431. state.back = 0;
  16432. for (;;) {
  16433. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  16434. here_bits = here >>> 24;
  16435. here_op = (here >>> 16) & 0xff;
  16436. here_val = here & 0xffff;
  16437. if (here_bits <= bits) { break; }
  16438. //--- PULLBYTE() ---//
  16439. if (have === 0) { break inf_leave; }
  16440. have--;
  16441. hold += input[next++] << bits;
  16442. bits += 8;
  16443. //---//
  16444. }
  16445. if (here_op && (here_op & 0xf0) === 0) {
  16446. last_bits = here_bits;
  16447. last_op = here_op;
  16448. last_val = here_val;
  16449. for (;;) {
  16450. here = state.lencode[last_val +
  16451. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  16452. here_bits = here >>> 24;
  16453. here_op = (here >>> 16) & 0xff;
  16454. here_val = here & 0xffff;
  16455. if ((last_bits + here_bits) <= bits) { break; }
  16456. //--- PULLBYTE() ---//
  16457. if (have === 0) { break inf_leave; }
  16458. have--;
  16459. hold += input[next++] << bits;
  16460. bits += 8;
  16461. //---//
  16462. }
  16463. //--- DROPBITS(last.bits) ---//
  16464. hold >>>= last_bits;
  16465. bits -= last_bits;
  16466. //---//
  16467. state.back += last_bits;
  16468. }
  16469. //--- DROPBITS(here.bits) ---//
  16470. hold >>>= here_bits;
  16471. bits -= here_bits;
  16472. //---//
  16473. state.back += here_bits;
  16474. state.length = here_val;
  16475. if (here_op === 0) {
  16476. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  16477. // "inflate: literal '%c'\n" :
  16478. // "inflate: literal 0x%02x\n", here.val));
  16479. state.mode = LIT;
  16480. break;
  16481. }
  16482. if (here_op & 32) {
  16483. //Tracevv((stderr, "inflate: end of block\n"));
  16484. state.back = -1;
  16485. state.mode = TYPE;
  16486. break;
  16487. }
  16488. if (here_op & 64) {
  16489. strm.msg = 'invalid literal/length code';
  16490. state.mode = BAD;
  16491. break;
  16492. }
  16493. state.extra = here_op & 15;
  16494. state.mode = LENEXT;
  16495. /* falls through */
  16496. case LENEXT:
  16497. if (state.extra) {
  16498. //=== NEEDBITS(state.extra);
  16499. n = state.extra;
  16500. while (bits < n) {
  16501. if (have === 0) { break inf_leave; }
  16502. have--;
  16503. hold += input[next++] << bits;
  16504. bits += 8;
  16505. }
  16506. //===//
  16507. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  16508. //--- DROPBITS(state.extra) ---//
  16509. hold >>>= state.extra;
  16510. bits -= state.extra;
  16511. //---//
  16512. state.back += state.extra;
  16513. }
  16514. //Tracevv((stderr, "inflate: length %u\n", state.length));
  16515. state.was = state.length;
  16516. state.mode = DIST;
  16517. /* falls through */
  16518. case DIST:
  16519. for (;;) {
  16520. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  16521. here_bits = here >>> 24;
  16522. here_op = (here >>> 16) & 0xff;
  16523. here_val = here & 0xffff;
  16524. if ((here_bits) <= bits) { break; }
  16525. //--- PULLBYTE() ---//
  16526. if (have === 0) { break inf_leave; }
  16527. have--;
  16528. hold += input[next++] << bits;
  16529. bits += 8;
  16530. //---//
  16531. }
  16532. if ((here_op & 0xf0) === 0) {
  16533. last_bits = here_bits;
  16534. last_op = here_op;
  16535. last_val = here_val;
  16536. for (;;) {
  16537. here = state.distcode[last_val +
  16538. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  16539. here_bits = here >>> 24;
  16540. here_op = (here >>> 16) & 0xff;
  16541. here_val = here & 0xffff;
  16542. if ((last_bits + here_bits) <= bits) { break; }
  16543. //--- PULLBYTE() ---//
  16544. if (have === 0) { break inf_leave; }
  16545. have--;
  16546. hold += input[next++] << bits;
  16547. bits += 8;
  16548. //---//
  16549. }
  16550. //--- DROPBITS(last.bits) ---//
  16551. hold >>>= last_bits;
  16552. bits -= last_bits;
  16553. //---//
  16554. state.back += last_bits;
  16555. }
  16556. //--- DROPBITS(here.bits) ---//
  16557. hold >>>= here_bits;
  16558. bits -= here_bits;
  16559. //---//
  16560. state.back += here_bits;
  16561. if (here_op & 64) {
  16562. strm.msg = 'invalid distance code';
  16563. state.mode = BAD;
  16564. break;
  16565. }
  16566. state.offset = here_val;
  16567. state.extra = (here_op) & 15;
  16568. state.mode = DISTEXT;
  16569. /* falls through */
  16570. case DISTEXT:
  16571. if (state.extra) {
  16572. //=== NEEDBITS(state.extra);
  16573. n = state.extra;
  16574. while (bits < n) {
  16575. if (have === 0) { break inf_leave; }
  16576. have--;
  16577. hold += input[next++] << bits;
  16578. bits += 8;
  16579. }
  16580. //===//
  16581. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  16582. //--- DROPBITS(state.extra) ---//
  16583. hold >>>= state.extra;
  16584. bits -= state.extra;
  16585. //---//
  16586. state.back += state.extra;
  16587. }
  16588. //#ifdef INFLATE_STRICT
  16589. if (state.offset > state.dmax) {
  16590. strm.msg = 'invalid distance too far back';
  16591. state.mode = BAD;
  16592. break;
  16593. }
  16594. //#endif
  16595. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  16596. state.mode = MATCH;
  16597. /* falls through */
  16598. case MATCH:
  16599. if (left === 0) { break inf_leave; }
  16600. copy = _out - left;
  16601. if (state.offset > copy) { /* copy from window */
  16602. copy = state.offset - copy;
  16603. if (copy > state.whave) {
  16604. if (state.sane) {
  16605. strm.msg = 'invalid distance too far back';
  16606. state.mode = BAD;
  16607. break;
  16608. }
  16609. // (!) This block is disabled in zlib defailts,
  16610. // don't enable it for binary compatibility
  16611. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  16612. // Trace((stderr, "inflate.c too far\n"));
  16613. // copy -= state.whave;
  16614. // if (copy > state.length) { copy = state.length; }
  16615. // if (copy > left) { copy = left; }
  16616. // left -= copy;
  16617. // state.length -= copy;
  16618. // do {
  16619. // output[put++] = 0;
  16620. // } while (--copy);
  16621. // if (state.length === 0) { state.mode = LEN; }
  16622. // break;
  16623. //#endif
  16624. }
  16625. if (copy > state.wnext) {
  16626. copy -= state.wnext;
  16627. from = state.wsize - copy;
  16628. }
  16629. else {
  16630. from = state.wnext - copy;
  16631. }
  16632. if (copy > state.length) { copy = state.length; }
  16633. from_source = state.window;
  16634. }
  16635. else { /* copy from output */
  16636. from_source = output;
  16637. from = put - state.offset;
  16638. copy = state.length;
  16639. }
  16640. if (copy > left) { copy = left; }
  16641. left -= copy;
  16642. state.length -= copy;
  16643. do {
  16644. output[put++] = from_source[from++];
  16645. } while (--copy);
  16646. if (state.length === 0) { state.mode = LEN; }
  16647. break;
  16648. case LIT:
  16649. if (left === 0) { break inf_leave; }
  16650. output[put++] = state.length;
  16651. left--;
  16652. state.mode = LEN;
  16653. break;
  16654. case CHECK:
  16655. if (state.wrap) {
  16656. //=== NEEDBITS(32);
  16657. while (bits < 32) {
  16658. if (have === 0) { break inf_leave; }
  16659. have--;
  16660. // Use '|' insdead of '+' to make sure that result is signed
  16661. hold |= input[next++] << bits;
  16662. bits += 8;
  16663. }
  16664. //===//
  16665. _out -= left;
  16666. strm.total_out += _out;
  16667. state.total += _out;
  16668. if (_out) {
  16669. strm.adler = state.check =
  16670. /*UPDATE(state.check, put - _out, _out);*/
  16671. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  16672. }
  16673. _out = left;
  16674. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  16675. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  16676. strm.msg = 'incorrect data check';
  16677. state.mode = BAD;
  16678. break;
  16679. }
  16680. //=== INITBITS();
  16681. hold = 0;
  16682. bits = 0;
  16683. //===//
  16684. //Tracev((stderr, "inflate: check matches trailer\n"));
  16685. }
  16686. state.mode = LENGTH;
  16687. /* falls through */
  16688. case LENGTH:
  16689. if (state.wrap && state.flags) {
  16690. //=== NEEDBITS(32);
  16691. while (bits < 32) {
  16692. if (have === 0) { break inf_leave; }
  16693. have--;
  16694. hold += input[next++] << bits;
  16695. bits += 8;
  16696. }
  16697. //===//
  16698. if (hold !== (state.total & 0xffffffff)) {
  16699. strm.msg = 'incorrect length check';
  16700. state.mode = BAD;
  16701. break;
  16702. }
  16703. //=== INITBITS();
  16704. hold = 0;
  16705. bits = 0;
  16706. //===//
  16707. //Tracev((stderr, "inflate: length matches trailer\n"));
  16708. }
  16709. state.mode = DONE;
  16710. /* falls through */
  16711. case DONE:
  16712. ret = Z_STREAM_END;
  16713. break inf_leave;
  16714. case BAD:
  16715. ret = Z_DATA_ERROR;
  16716. break inf_leave;
  16717. case MEM:
  16718. return Z_MEM_ERROR;
  16719. case SYNC:
  16720. /* falls through */
  16721. default:
  16722. return Z_STREAM_ERROR;
  16723. }
  16724. }
  16725. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  16726. /*
  16727. Return from inflate(), updating the total counts and the check value.
  16728. If there was no progress during the inflate() call, return a buffer
  16729. error. Call updatewindow() to create and/or update the window state.
  16730. Note: a memory error from inflate() is non-recoverable.
  16731. */
  16732. //--- RESTORE() ---
  16733. strm.next_out = put;
  16734. strm.avail_out = left;
  16735. strm.next_in = next;
  16736. strm.avail_in = have;
  16737. state.hold = hold;
  16738. state.bits = bits;
  16739. //---
  16740. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  16741. (state.mode < CHECK || flush !== Z_FINISH))) {
  16742. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  16743. state.mode = MEM;
  16744. return Z_MEM_ERROR;
  16745. }
  16746. }
  16747. _in -= strm.avail_in;
  16748. _out -= strm.avail_out;
  16749. strm.total_in += _in;
  16750. strm.total_out += _out;
  16751. state.total += _out;
  16752. if (state.wrap && _out) {
  16753. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  16754. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  16755. }
  16756. strm.data_type = state.bits + (state.last ? 64 : 0) +
  16757. (state.mode === TYPE ? 128 : 0) +
  16758. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  16759. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  16760. ret = Z_BUF_ERROR;
  16761. }
  16762. return ret;
  16763. }
  16764. function inflateEnd(strm) {
  16765. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  16766. return Z_STREAM_ERROR;
  16767. }
  16768. var state = strm.state;
  16769. if (state.window) {
  16770. state.window = null;
  16771. }
  16772. strm.state = null;
  16773. return Z_OK;
  16774. }
  16775. function inflateGetHeader(strm, head) {
  16776. var state;
  16777. /* check state */
  16778. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16779. state = strm.state;
  16780. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  16781. /* save header structure */
  16782. state.head = head;
  16783. head.done = false;
  16784. return Z_OK;
  16785. }
  16786. exports.inflateReset = inflateReset;
  16787. exports.inflateReset2 = inflateReset2;
  16788. exports.inflateResetKeep = inflateResetKeep;
  16789. exports.inflateInit = inflateInit;
  16790. exports.inflateInit2 = inflateInit2;
  16791. exports.inflate = inflate;
  16792. exports.inflateEnd = inflateEnd;
  16793. exports.inflateGetHeader = inflateGetHeader;
  16794. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  16795. /* Not implemented
  16796. exports.inflateCopy = inflateCopy;
  16797. exports.inflateGetDictionary = inflateGetDictionary;
  16798. exports.inflateMark = inflateMark;
  16799. exports.inflatePrime = inflatePrime;
  16800. exports.inflateSetDictionary = inflateSetDictionary;
  16801. exports.inflateSync = inflateSync;
  16802. exports.inflateSyncPoint = inflateSyncPoint;
  16803. exports.inflateUndermine = inflateUndermine;
  16804. */
  16805. },{"../utils/common":51,"./adler32":53,"./crc32":55,"./inffast":58,"./inftrees":60}],60:[function(require,module,exports){
  16806. 'use strict';
  16807. var utils = require('../utils/common');
  16808. var MAXBITS = 15;
  16809. var ENOUGH_LENS = 852;
  16810. var ENOUGH_DISTS = 592;
  16811. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  16812. var CODES = 0;
  16813. var LENS = 1;
  16814. var DISTS = 2;
  16815. var lbase = [ /* Length codes 257..285 base */
  16816. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  16817. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  16818. ];
  16819. var lext = [ /* Length codes 257..285 extra */
  16820. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  16821. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  16822. ];
  16823. var dbase = [ /* Distance codes 0..29 base */
  16824. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  16825. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  16826. 8193, 12289, 16385, 24577, 0, 0
  16827. ];
  16828. var dext = [ /* Distance codes 0..29 extra */
  16829. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  16830. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  16831. 28, 28, 29, 29, 64, 64
  16832. ];
  16833. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  16834. {
  16835. var bits = opts.bits;
  16836. //here = opts.here; /* table entry for duplication */
  16837. var len = 0; /* a code's length in bits */
  16838. var sym = 0; /* index of code symbols */
  16839. var min = 0, max = 0; /* minimum and maximum code lengths */
  16840. var root = 0; /* number of index bits for root table */
  16841. var curr = 0; /* number of index bits for current table */
  16842. var drop = 0; /* code bits to drop for sub-table */
  16843. var left = 0; /* number of prefix codes available */
  16844. var used = 0; /* code entries in table used */
  16845. var huff = 0; /* Huffman code */
  16846. var incr; /* for incrementing code, index */
  16847. var fill; /* index for replicating entries */
  16848. var low; /* low bits for current root entry */
  16849. var mask; /* mask for low root bits */
  16850. var next; /* next available space in table */
  16851. var base = null; /* base value table to use */
  16852. var base_index = 0;
  16853. // var shoextra; /* extra bits table to use */
  16854. var end; /* use base and extra for symbol > end */
  16855. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  16856. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  16857. var extra = null;
  16858. var extra_index = 0;
  16859. var here_bits, here_op, here_val;
  16860. /*
  16861. Process a set of code lengths to create a canonical Huffman code. The
  16862. code lengths are lens[0..codes-1]. Each length corresponds to the
  16863. symbols 0..codes-1. The Huffman code is generated by first sorting the
  16864. symbols by length from short to long, and retaining the symbol order
  16865. for codes with equal lengths. Then the code starts with all zero bits
  16866. for the first code of the shortest length, and the codes are integer
  16867. increments for the same length, and zeros are appended as the length
  16868. increases. For the deflate format, these bits are stored backwards
  16869. from their more natural integer increment ordering, and so when the
  16870. decoding tables are built in the large loop below, the integer codes
  16871. are incremented backwards.
  16872. This routine assumes, but does not check, that all of the entries in
  16873. lens[] are in the range 0..MAXBITS. The caller must assure this.
  16874. 1..MAXBITS is interpreted as that code length. zero means that that
  16875. symbol does not occur in this code.
  16876. The codes are sorted by computing a count of codes for each length,
  16877. creating from that a table of starting indices for each length in the
  16878. sorted table, and then entering the symbols in order in the sorted
  16879. table. The sorted table is work[], with that space being provided by
  16880. the caller.
  16881. The length counts are used for other purposes as well, i.e. finding
  16882. the minimum and maximum length codes, determining if there are any
  16883. codes at all, checking for a valid set of lengths, and looking ahead
  16884. at length counts to determine sub-table sizes when building the
  16885. decoding tables.
  16886. */
  16887. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  16888. for (len = 0; len <= MAXBITS; len++) {
  16889. count[len] = 0;
  16890. }
  16891. for (sym = 0; sym < codes; sym++) {
  16892. count[lens[lens_index + sym]]++;
  16893. }
  16894. /* bound code lengths, force root to be within code lengths */
  16895. root = bits;
  16896. for (max = MAXBITS; max >= 1; max--) {
  16897. if (count[max] !== 0) { break; }
  16898. }
  16899. if (root > max) {
  16900. root = max;
  16901. }
  16902. if (max === 0) { /* no symbols to code at all */
  16903. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  16904. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  16905. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  16906. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  16907. //table.op[opts.table_index] = 64;
  16908. //table.bits[opts.table_index] = 1;
  16909. //table.val[opts.table_index++] = 0;
  16910. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  16911. opts.bits = 1;
  16912. return 0; /* no symbols, but wait for decoding to report error */
  16913. }
  16914. for (min = 1; min < max; min++) {
  16915. if (count[min] !== 0) { break; }
  16916. }
  16917. if (root < min) {
  16918. root = min;
  16919. }
  16920. /* check for an over-subscribed or incomplete set of lengths */
  16921. left = 1;
  16922. for (len = 1; len <= MAXBITS; len++) {
  16923. left <<= 1;
  16924. left -= count[len];
  16925. if (left < 0) {
  16926. return -1;
  16927. } /* over-subscribed */
  16928. }
  16929. if (left > 0 && (type === CODES || max !== 1)) {
  16930. return -1; /* incomplete set */
  16931. }
  16932. /* generate offsets into symbol table for each length for sorting */
  16933. offs[1] = 0;
  16934. for (len = 1; len < MAXBITS; len++) {
  16935. offs[len + 1] = offs[len] + count[len];
  16936. }
  16937. /* sort symbols by length, by symbol order within each length */
  16938. for (sym = 0; sym < codes; sym++) {
  16939. if (lens[lens_index + sym] !== 0) {
  16940. work[offs[lens[lens_index + sym]]++] = sym;
  16941. }
  16942. }
  16943. /*
  16944. Create and fill in decoding tables. In this loop, the table being
  16945. filled is at next and has curr index bits. The code being used is huff
  16946. with length len. That code is converted to an index by dropping drop
  16947. bits off of the bottom. For codes where len is less than drop + curr,
  16948. those top drop + curr - len bits are incremented through all values to
  16949. fill the table with replicated entries.
  16950. root is the number of index bits for the root table. When len exceeds
  16951. root, sub-tables are created pointed to by the root entry with an index
  16952. of the low root bits of huff. This is saved in low to check for when a
  16953. new sub-table should be started. drop is zero when the root table is
  16954. being filled, and drop is root when sub-tables are being filled.
  16955. When a new sub-table is needed, it is necessary to look ahead in the
  16956. code lengths to determine what size sub-table is needed. The length
  16957. counts are used for this, and so count[] is decremented as codes are
  16958. entered in the tables.
  16959. used keeps track of how many table entries have been allocated from the
  16960. provided *table space. It is checked for LENS and DIST tables against
  16961. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  16962. the initial root table size constants. See the comments in inftrees.h
  16963. for more information.
  16964. sym increments through all symbols, and the loop terminates when
  16965. all codes of length max, i.e. all codes, have been processed. This
  16966. routine permits incomplete codes, so another loop after this one fills
  16967. in the rest of the decoding tables with invalid code markers.
  16968. */
  16969. /* set up for code type */
  16970. // poor man optimization - use if-else instead of switch,
  16971. // to avoid deopts in old v8
  16972. if (type === CODES) {
  16973. base = extra = work; /* dummy value--not used */
  16974. end = 19;
  16975. } else if (type === LENS) {
  16976. base = lbase;
  16977. base_index -= 257;
  16978. extra = lext;
  16979. extra_index -= 257;
  16980. end = 256;
  16981. } else { /* DISTS */
  16982. base = dbase;
  16983. extra = dext;
  16984. end = -1;
  16985. }
  16986. /* initialize opts for loop */
  16987. huff = 0; /* starting code */
  16988. sym = 0; /* starting code symbol */
  16989. len = min; /* starting code length */
  16990. next = table_index; /* current table to fill in */
  16991. curr = root; /* current table index bits */
  16992. drop = 0; /* current bits to drop from code for index */
  16993. low = -1; /* trigger new sub-table when len > root */
  16994. used = 1 << root; /* use root table entries */
  16995. mask = used - 1; /* mask for comparing low */
  16996. /* check available table space */
  16997. if ((type === LENS && used > ENOUGH_LENS) ||
  16998. (type === DISTS && used > ENOUGH_DISTS)) {
  16999. return 1;
  17000. }
  17001. var i=0;
  17002. /* process all codes and make table entries */
  17003. for (;;) {
  17004. i++;
  17005. /* create table entry */
  17006. here_bits = len - drop;
  17007. if (work[sym] < end) {
  17008. here_op = 0;
  17009. here_val = work[sym];
  17010. }
  17011. else if (work[sym] > end) {
  17012. here_op = extra[extra_index + work[sym]];
  17013. here_val = base[base_index + work[sym]];
  17014. }
  17015. else {
  17016. here_op = 32 + 64; /* end of block */
  17017. here_val = 0;
  17018. }
  17019. /* replicate for those indices with low len bits equal to huff */
  17020. incr = 1 << (len - drop);
  17021. fill = 1 << curr;
  17022. min = fill; /* save offset to next table */
  17023. do {
  17024. fill -= incr;
  17025. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  17026. } while (fill !== 0);
  17027. /* backwards increment the len-bit code huff */
  17028. incr = 1 << (len - 1);
  17029. while (huff & incr) {
  17030. incr >>= 1;
  17031. }
  17032. if (incr !== 0) {
  17033. huff &= incr - 1;
  17034. huff += incr;
  17035. } else {
  17036. huff = 0;
  17037. }
  17038. /* go to next symbol, update count, len */
  17039. sym++;
  17040. if (--count[len] === 0) {
  17041. if (len === max) { break; }
  17042. len = lens[lens_index + work[sym]];
  17043. }
  17044. /* create new sub-table if needed */
  17045. if (len > root && (huff & mask) !== low) {
  17046. /* if first time, transition to sub-tables */
  17047. if (drop === 0) {
  17048. drop = root;
  17049. }
  17050. /* increment past last table */
  17051. next += min; /* here min is 1 << curr */
  17052. /* determine length of next table */
  17053. curr = len - drop;
  17054. left = 1 << curr;
  17055. while (curr + drop < max) {
  17056. left -= count[curr + drop];
  17057. if (left <= 0) { break; }
  17058. curr++;
  17059. left <<= 1;
  17060. }
  17061. /* check for enough space */
  17062. used += 1 << curr;
  17063. if ((type === LENS && used > ENOUGH_LENS) ||
  17064. (type === DISTS && used > ENOUGH_DISTS)) {
  17065. return 1;
  17066. }
  17067. /* point entry in root table to sub-table */
  17068. low = huff & mask;
  17069. /*table.op[low] = curr;
  17070. table.bits[low] = root;
  17071. table.val[low] = next - opts.table_index;*/
  17072. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  17073. }
  17074. }
  17075. /* fill in remaining table entry if code is incomplete (guaranteed to have
  17076. at most one remaining entry, since if the code is incomplete, the
  17077. maximum code length that was allowed to get this far is one bit) */
  17078. if (huff !== 0) {
  17079. //table.op[next + huff] = 64; /* invalid code marker */
  17080. //table.bits[next + huff] = len - drop;
  17081. //table.val[next + huff] = 0;
  17082. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  17083. }
  17084. /* set return parameters */
  17085. //opts.table_index += used;
  17086. opts.bits = root;
  17087. return 0;
  17088. };
  17089. },{"../utils/common":51}],61:[function(require,module,exports){
  17090. 'use strict';
  17091. module.exports = {
  17092. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  17093. '1': 'stream end', /* Z_STREAM_END 1 */
  17094. '0': '', /* Z_OK 0 */
  17095. '-1': 'file error', /* Z_ERRNO (-1) */
  17096. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  17097. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  17098. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  17099. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  17100. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  17101. };
  17102. },{}],62:[function(require,module,exports){
  17103. 'use strict';
  17104. var utils = require('../utils/common');
  17105. /* Public constants ==========================================================*/
  17106. /* ===========================================================================*/
  17107. //var Z_FILTERED = 1;
  17108. //var Z_HUFFMAN_ONLY = 2;
  17109. //var Z_RLE = 3;
  17110. var Z_FIXED = 4;
  17111. //var Z_DEFAULT_STRATEGY = 0;
  17112. /* Possible values of the data_type field (though see inflate()) */
  17113. var Z_BINARY = 0;
  17114. var Z_TEXT = 1;
  17115. //var Z_ASCII = 1; // = Z_TEXT
  17116. var Z_UNKNOWN = 2;
  17117. /*============================================================================*/
  17118. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  17119. // From zutil.h
  17120. var STORED_BLOCK = 0;
  17121. var STATIC_TREES = 1;
  17122. var DYN_TREES = 2;
  17123. /* The three kinds of block type */
  17124. var MIN_MATCH = 3;
  17125. var MAX_MATCH = 258;
  17126. /* The minimum and maximum match lengths */
  17127. // From deflate.h
  17128. /* ===========================================================================
  17129. * Internal compression state.
  17130. */
  17131. var LENGTH_CODES = 29;
  17132. /* number of length codes, not counting the special END_BLOCK code */
  17133. var LITERALS = 256;
  17134. /* number of literal bytes 0..255 */
  17135. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  17136. /* number of Literal or Length codes, including the END_BLOCK code */
  17137. var D_CODES = 30;
  17138. /* number of distance codes */
  17139. var BL_CODES = 19;
  17140. /* number of codes used to transfer the bit lengths */
  17141. var HEAP_SIZE = 2*L_CODES + 1;
  17142. /* maximum heap size */
  17143. var MAX_BITS = 15;
  17144. /* All codes must not exceed MAX_BITS bits */
  17145. var Buf_size = 16;
  17146. /* size of bit buffer in bi_buf */
  17147. /* ===========================================================================
  17148. * Constants
  17149. */
  17150. var MAX_BL_BITS = 7;
  17151. /* Bit length codes must not exceed MAX_BL_BITS bits */
  17152. var END_BLOCK = 256;
  17153. /* end of block literal code */
  17154. var REP_3_6 = 16;
  17155. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  17156. var REPZ_3_10 = 17;
  17157. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  17158. var REPZ_11_138 = 18;
  17159. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  17160. var extra_lbits = /* extra bits for each length code */
  17161. [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];
  17162. var extra_dbits = /* extra bits for each distance code */
  17163. [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];
  17164. var extra_blbits = /* extra bits for each bit length code */
  17165. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  17166. var bl_order =
  17167. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  17168. /* The lengths of the bit length codes are sent in order of decreasing
  17169. * probability, to avoid transmitting the lengths for unused bit length codes.
  17170. */
  17171. /* ===========================================================================
  17172. * Local data. These are initialized only once.
  17173. */
  17174. // We pre-fill arrays with 0 to avoid uninitialized gaps
  17175. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  17176. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  17177. var static_ltree = new Array((L_CODES+2) * 2);
  17178. zero(static_ltree);
  17179. /* The static literal tree. Since the bit lengths are imposed, there is no
  17180. * need for the L_CODES extra codes used during heap construction. However
  17181. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  17182. * below).
  17183. */
  17184. var static_dtree = new Array(D_CODES * 2);
  17185. zero(static_dtree);
  17186. /* The static distance tree. (Actually a trivial tree since all codes use
  17187. * 5 bits.)
  17188. */
  17189. var _dist_code = new Array(DIST_CODE_LEN);
  17190. zero(_dist_code);
  17191. /* Distance codes. The first 256 values correspond to the distances
  17192. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  17193. * the 15 bit distances.
  17194. */
  17195. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  17196. zero(_length_code);
  17197. /* length code for each normalized match length (0 == MIN_MATCH) */
  17198. var base_length = new Array(LENGTH_CODES);
  17199. zero(base_length);
  17200. /* First normalized length for each code (0 = MIN_MATCH) */
  17201. var base_dist = new Array(D_CODES);
  17202. zero(base_dist);
  17203. /* First normalized distance for each code (0 = distance of 1) */
  17204. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  17205. this.static_tree = static_tree; /* static tree or NULL */
  17206. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  17207. this.extra_base = extra_base; /* base index for extra_bits */
  17208. this.elems = elems; /* max number of elements in the tree */
  17209. this.max_length = max_length; /* max bit length for the codes */
  17210. // show if `static_tree` has data or dummy - needed for monomorphic objects
  17211. this.has_stree = static_tree && static_tree.length;
  17212. };
  17213. var static_l_desc;
  17214. var static_d_desc;
  17215. var static_bl_desc;
  17216. var TreeDesc = function(dyn_tree, stat_desc) {
  17217. this.dyn_tree = dyn_tree; /* the dynamic tree */
  17218. this.max_code = 0; /* largest code with non zero frequency */
  17219. this.stat_desc = stat_desc; /* the corresponding static tree */
  17220. };
  17221. function d_code(dist) {
  17222. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  17223. }
  17224. /* ===========================================================================
  17225. * Output a short LSB first on the stream.
  17226. * IN assertion: there is enough room in pendingBuf.
  17227. */
  17228. function put_short (s, w) {
  17229. // put_byte(s, (uch)((w) & 0xff));
  17230. // put_byte(s, (uch)((ush)(w) >> 8));
  17231. s.pending_buf[s.pending++] = (w) & 0xff;
  17232. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  17233. }
  17234. /* ===========================================================================
  17235. * Send a value on a given number of bits.
  17236. * IN assertion: length <= 16 and value fits in length bits.
  17237. */
  17238. function send_bits(s, value, length) {
  17239. if (s.bi_valid > (Buf_size - length)) {
  17240. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  17241. put_short(s, s.bi_buf);
  17242. s.bi_buf = value >> (Buf_size - s.bi_valid);
  17243. s.bi_valid += length - Buf_size;
  17244. } else {
  17245. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  17246. s.bi_valid += length;
  17247. }
  17248. }
  17249. function send_code(s, c, tree) {
  17250. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  17251. }
  17252. /* ===========================================================================
  17253. * Reverse the first len bits of a code, using straightforward code (a faster
  17254. * method would use a table)
  17255. * IN assertion: 1 <= len <= 15
  17256. */
  17257. function bi_reverse(code, len) {
  17258. var res = 0;
  17259. do {
  17260. res |= code & 1;
  17261. code >>>= 1;
  17262. res <<= 1;
  17263. } while (--len > 0);
  17264. return res >>> 1;
  17265. }
  17266. /* ===========================================================================
  17267. * Flush the bit buffer, keeping at most 7 bits in it.
  17268. */
  17269. function bi_flush(s) {
  17270. if (s.bi_valid === 16) {
  17271. put_short(s, s.bi_buf);
  17272. s.bi_buf = 0;
  17273. s.bi_valid = 0;
  17274. } else if (s.bi_valid >= 8) {
  17275. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  17276. s.bi_buf >>= 8;
  17277. s.bi_valid -= 8;
  17278. }
  17279. }
  17280. /* ===========================================================================
  17281. * Compute the optimal bit lengths for a tree and update the total bit length
  17282. * for the current block.
  17283. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  17284. * above are the tree nodes sorted by increasing frequency.
  17285. * OUT assertions: the field len is set to the optimal bit length, the
  17286. * array bl_count contains the frequencies for each bit length.
  17287. * The length opt_len is updated; static_len is also updated if stree is
  17288. * not null.
  17289. */
  17290. function gen_bitlen(s, desc)
  17291. // deflate_state *s;
  17292. // tree_desc *desc; /* the tree descriptor */
  17293. {
  17294. var tree = desc.dyn_tree;
  17295. var max_code = desc.max_code;
  17296. var stree = desc.stat_desc.static_tree;
  17297. var has_stree = desc.stat_desc.has_stree;
  17298. var extra = desc.stat_desc.extra_bits;
  17299. var base = desc.stat_desc.extra_base;
  17300. var max_length = desc.stat_desc.max_length;
  17301. var h; /* heap index */
  17302. var n, m; /* iterate over the tree elements */
  17303. var bits; /* bit length */
  17304. var xbits; /* extra bits */
  17305. var f; /* frequency */
  17306. var overflow = 0; /* number of elements with bit length too large */
  17307. for (bits = 0; bits <= MAX_BITS; bits++) {
  17308. s.bl_count[bits] = 0;
  17309. }
  17310. /* In a first pass, compute the optimal bit lengths (which may
  17311. * overflow in the case of the bit length tree).
  17312. */
  17313. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  17314. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  17315. n = s.heap[h];
  17316. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  17317. if (bits > max_length) {
  17318. bits = max_length;
  17319. overflow++;
  17320. }
  17321. tree[n*2 + 1]/*.Len*/ = bits;
  17322. /* We overwrite tree[n].Dad which is no longer needed */
  17323. if (n > max_code) { continue; } /* not a leaf node */
  17324. s.bl_count[bits]++;
  17325. xbits = 0;
  17326. if (n >= base) {
  17327. xbits = extra[n-base];
  17328. }
  17329. f = tree[n * 2]/*.Freq*/;
  17330. s.opt_len += f * (bits + xbits);
  17331. if (has_stree) {
  17332. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  17333. }
  17334. }
  17335. if (overflow === 0) { return; }
  17336. // Trace((stderr,"\nbit length overflow\n"));
  17337. /* This happens for example on obj2 and pic of the Calgary corpus */
  17338. /* Find the first bit length which could increase: */
  17339. do {
  17340. bits = max_length-1;
  17341. while (s.bl_count[bits] === 0) { bits--; }
  17342. s.bl_count[bits]--; /* move one leaf down the tree */
  17343. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  17344. s.bl_count[max_length]--;
  17345. /* The brother of the overflow item also moves one step up,
  17346. * but this does not affect bl_count[max_length]
  17347. */
  17348. overflow -= 2;
  17349. } while (overflow > 0);
  17350. /* Now recompute all bit lengths, scanning in increasing frequency.
  17351. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  17352. * lengths instead of fixing only the wrong ones. This idea is taken
  17353. * from 'ar' written by Haruhiko Okumura.)
  17354. */
  17355. for (bits = max_length; bits !== 0; bits--) {
  17356. n = s.bl_count[bits];
  17357. while (n !== 0) {
  17358. m = s.heap[--h];
  17359. if (m > max_code) { continue; }
  17360. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  17361. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  17362. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  17363. tree[m*2 + 1]/*.Len*/ = bits;
  17364. }
  17365. n--;
  17366. }
  17367. }
  17368. }
  17369. /* ===========================================================================
  17370. * Generate the codes for a given tree and bit counts (which need not be
  17371. * optimal).
  17372. * IN assertion: the array bl_count contains the bit length statistics for
  17373. * the given tree and the field len is set for all tree elements.
  17374. * OUT assertion: the field code is set for all tree elements of non
  17375. * zero code length.
  17376. */
  17377. function gen_codes(tree, max_code, bl_count)
  17378. // ct_data *tree; /* the tree to decorate */
  17379. // int max_code; /* largest code with non zero frequency */
  17380. // ushf *bl_count; /* number of codes at each bit length */
  17381. {
  17382. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  17383. var code = 0; /* running code value */
  17384. var bits; /* bit index */
  17385. var n; /* code index */
  17386. /* The distribution counts are first used to generate the code values
  17387. * without bit reversal.
  17388. */
  17389. for (bits = 1; bits <= MAX_BITS; bits++) {
  17390. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  17391. }
  17392. /* Check that the bit counts in bl_count are consistent. The last code
  17393. * must be all ones.
  17394. */
  17395. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  17396. // "inconsistent bit counts");
  17397. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  17398. for (n = 0; n <= max_code; n++) {
  17399. var len = tree[n*2 + 1]/*.Len*/;
  17400. if (len === 0) { continue; }
  17401. /* Now reverse the bits */
  17402. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  17403. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  17404. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  17405. }
  17406. }
  17407. /* ===========================================================================
  17408. * Initialize the various 'constant' tables.
  17409. */
  17410. function tr_static_init() {
  17411. var n; /* iterates over tree elements */
  17412. var bits; /* bit counter */
  17413. var length; /* length value */
  17414. var code; /* code value */
  17415. var dist; /* distance index */
  17416. var bl_count = new Array(MAX_BITS+1);
  17417. /* number of codes at each bit length for an optimal tree */
  17418. // do check in _tr_init()
  17419. //if (static_init_done) return;
  17420. /* For some embedded targets, global variables are not initialized: */
  17421. /*#ifdef NO_INIT_GLOBAL_POINTERS
  17422. static_l_desc.static_tree = static_ltree;
  17423. static_l_desc.extra_bits = extra_lbits;
  17424. static_d_desc.static_tree = static_dtree;
  17425. static_d_desc.extra_bits = extra_dbits;
  17426. static_bl_desc.extra_bits = extra_blbits;
  17427. #endif*/
  17428. /* Initialize the mapping length (0..255) -> length code (0..28) */
  17429. length = 0;
  17430. for (code = 0; code < LENGTH_CODES-1; code++) {
  17431. base_length[code] = length;
  17432. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  17433. _length_code[length++] = code;
  17434. }
  17435. }
  17436. //Assert (length == 256, "tr_static_init: length != 256");
  17437. /* Note that the length 255 (match length 258) can be represented
  17438. * in two different ways: code 284 + 5 bits or code 285, so we
  17439. * overwrite length_code[255] to use the best encoding:
  17440. */
  17441. _length_code[length-1] = code;
  17442. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  17443. dist = 0;
  17444. for (code = 0 ; code < 16; code++) {
  17445. base_dist[code] = dist;
  17446. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  17447. _dist_code[dist++] = code;
  17448. }
  17449. }
  17450. //Assert (dist == 256, "tr_static_init: dist != 256");
  17451. dist >>= 7; /* from now on, all distances are divided by 128 */
  17452. for (; code < D_CODES; code++) {
  17453. base_dist[code] = dist << 7;
  17454. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  17455. _dist_code[256 + dist++] = code;
  17456. }
  17457. }
  17458. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  17459. /* Construct the codes of the static literal tree */
  17460. for (bits = 0; bits <= MAX_BITS; bits++) {
  17461. bl_count[bits] = 0;
  17462. }
  17463. n = 0;
  17464. while (n <= 143) {
  17465. static_ltree[n*2 + 1]/*.Len*/ = 8;
  17466. n++;
  17467. bl_count[8]++;
  17468. }
  17469. while (n <= 255) {
  17470. static_ltree[n*2 + 1]/*.Len*/ = 9;
  17471. n++;
  17472. bl_count[9]++;
  17473. }
  17474. while (n <= 279) {
  17475. static_ltree[n*2 + 1]/*.Len*/ = 7;
  17476. n++;
  17477. bl_count[7]++;
  17478. }
  17479. while (n <= 287) {
  17480. static_ltree[n*2 + 1]/*.Len*/ = 8;
  17481. n++;
  17482. bl_count[8]++;
  17483. }
  17484. /* Codes 286 and 287 do not exist, but we must include them in the
  17485. * tree construction to get a canonical Huffman tree (longest code
  17486. * all ones)
  17487. */
  17488. gen_codes(static_ltree, L_CODES+1, bl_count);
  17489. /* The static distance tree is trivial: */
  17490. for (n = 0; n < D_CODES; n++) {
  17491. static_dtree[n*2 + 1]/*.Len*/ = 5;
  17492. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  17493. }
  17494. // Now data ready and we can init static trees
  17495. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  17496. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  17497. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  17498. //static_init_done = true;
  17499. }
  17500. /* ===========================================================================
  17501. * Initialize a new block.
  17502. */
  17503. function init_block(s) {
  17504. var n; /* iterates over tree elements */
  17505. /* Initialize the trees. */
  17506. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  17507. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  17508. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  17509. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  17510. s.opt_len = s.static_len = 0;
  17511. s.last_lit = s.matches = 0;
  17512. }
  17513. /* ===========================================================================
  17514. * Flush the bit buffer and align the output on a byte boundary
  17515. */
  17516. function bi_windup(s)
  17517. {
  17518. if (s.bi_valid > 8) {
  17519. put_short(s, s.bi_buf);
  17520. } else if (s.bi_valid > 0) {
  17521. //put_byte(s, (Byte)s->bi_buf);
  17522. s.pending_buf[s.pending++] = s.bi_buf;
  17523. }
  17524. s.bi_buf = 0;
  17525. s.bi_valid = 0;
  17526. }
  17527. /* ===========================================================================
  17528. * Copy a stored block, storing first the length and its
  17529. * one's complement if requested.
  17530. */
  17531. function copy_block(s, buf, len, header)
  17532. //DeflateState *s;
  17533. //charf *buf; /* the input data */
  17534. //unsigned len; /* its length */
  17535. //int header; /* true if block header must be written */
  17536. {
  17537. bi_windup(s); /* align on byte boundary */
  17538. if (header) {
  17539. put_short(s, len);
  17540. put_short(s, ~len);
  17541. }
  17542. // while (len--) {
  17543. // put_byte(s, *buf++);
  17544. // }
  17545. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  17546. s.pending += len;
  17547. }
  17548. /* ===========================================================================
  17549. * Compares to subtrees, using the tree depth as tie breaker when
  17550. * the subtrees have equal frequency. This minimizes the worst case length.
  17551. */
  17552. function smaller(tree, n, m, depth) {
  17553. var _n2 = n*2;
  17554. var _m2 = m*2;
  17555. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  17556. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  17557. }
  17558. /* ===========================================================================
  17559. * Restore the heap property by moving down the tree starting at node k,
  17560. * exchanging a node with the smallest of its two sons if necessary, stopping
  17561. * when the heap property is re-established (each father smaller than its
  17562. * two sons).
  17563. */
  17564. function pqdownheap(s, tree, k)
  17565. // deflate_state *s;
  17566. // ct_data *tree; /* the tree to restore */
  17567. // int k; /* node to move down */
  17568. {
  17569. var v = s.heap[k];
  17570. var j = k << 1; /* left son of k */
  17571. while (j <= s.heap_len) {
  17572. /* Set j to the smallest of the two sons: */
  17573. if (j < s.heap_len &&
  17574. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  17575. j++;
  17576. }
  17577. /* Exit if v is smaller than both sons */
  17578. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  17579. /* Exchange v with the smallest son */
  17580. s.heap[k] = s.heap[j];
  17581. k = j;
  17582. /* And continue down the tree, setting j to the left son of k */
  17583. j <<= 1;
  17584. }
  17585. s.heap[k] = v;
  17586. }
  17587. // inlined manually
  17588. // var SMALLEST = 1;
  17589. /* ===========================================================================
  17590. * Send the block data compressed using the given Huffman trees
  17591. */
  17592. function compress_block(s, ltree, dtree)
  17593. // deflate_state *s;
  17594. // const ct_data *ltree; /* literal tree */
  17595. // const ct_data *dtree; /* distance tree */
  17596. {
  17597. var dist; /* distance of matched string */
  17598. var lc; /* match length or unmatched char (if dist == 0) */
  17599. var lx = 0; /* running index in l_buf */
  17600. var code; /* the code to send */
  17601. var extra; /* number of extra bits to send */
  17602. if (s.last_lit !== 0) {
  17603. do {
  17604. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  17605. lc = s.pending_buf[s.l_buf + lx];
  17606. lx++;
  17607. if (dist === 0) {
  17608. send_code(s, lc, ltree); /* send a literal byte */
  17609. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  17610. } else {
  17611. /* Here, lc is the match length - MIN_MATCH */
  17612. code = _length_code[lc];
  17613. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  17614. extra = extra_lbits[code];
  17615. if (extra !== 0) {
  17616. lc -= base_length[code];
  17617. send_bits(s, lc, extra); /* send the extra length bits */
  17618. }
  17619. dist--; /* dist is now the match distance - 1 */
  17620. code = d_code(dist);
  17621. //Assert (code < D_CODES, "bad d_code");
  17622. send_code(s, code, dtree); /* send the distance code */
  17623. extra = extra_dbits[code];
  17624. if (extra !== 0) {
  17625. dist -= base_dist[code];
  17626. send_bits(s, dist, extra); /* send the extra distance bits */
  17627. }
  17628. } /* literal or match pair ? */
  17629. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  17630. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  17631. // "pendingBuf overflow");
  17632. } while (lx < s.last_lit);
  17633. }
  17634. send_code(s, END_BLOCK, ltree);
  17635. }
  17636. /* ===========================================================================
  17637. * Construct one Huffman tree and assigns the code bit strings and lengths.
  17638. * Update the total bit length for the current block.
  17639. * IN assertion: the field freq is set for all tree elements.
  17640. * OUT assertions: the fields len and code are set to the optimal bit length
  17641. * and corresponding code. The length opt_len is updated; static_len is
  17642. * also updated if stree is not null. The field max_code is set.
  17643. */
  17644. function build_tree(s, desc)
  17645. // deflate_state *s;
  17646. // tree_desc *desc; /* the tree descriptor */
  17647. {
  17648. var tree = desc.dyn_tree;
  17649. var stree = desc.stat_desc.static_tree;
  17650. var has_stree = desc.stat_desc.has_stree;
  17651. var elems = desc.stat_desc.elems;
  17652. var n, m; /* iterate over heap elements */
  17653. var max_code = -1; /* largest code with non zero frequency */
  17654. var node; /* new node being created */
  17655. /* Construct the initial heap, with least frequent element in
  17656. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  17657. * heap[0] is not used.
  17658. */
  17659. s.heap_len = 0;
  17660. s.heap_max = HEAP_SIZE;
  17661. for (n = 0; n < elems; n++) {
  17662. if (tree[n * 2]/*.Freq*/ !== 0) {
  17663. s.heap[++s.heap_len] = max_code = n;
  17664. s.depth[n] = 0;
  17665. } else {
  17666. tree[n*2 + 1]/*.Len*/ = 0;
  17667. }
  17668. }
  17669. /* The pkzip format requires that at least one distance code exists,
  17670. * and that at least one bit should be sent even if there is only one
  17671. * possible code. So to avoid special checks later on we force at least
  17672. * two codes of non zero frequency.
  17673. */
  17674. while (s.heap_len < 2) {
  17675. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  17676. tree[node * 2]/*.Freq*/ = 1;
  17677. s.depth[node] = 0;
  17678. s.opt_len--;
  17679. if (has_stree) {
  17680. s.static_len -= stree[node*2 + 1]/*.Len*/;
  17681. }
  17682. /* node is 0 or 1 so it does not have extra bits */
  17683. }
  17684. desc.max_code = max_code;
  17685. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  17686. * establish sub-heaps of increasing lengths:
  17687. */
  17688. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  17689. /* Construct the Huffman tree by repeatedly combining the least two
  17690. * frequent nodes.
  17691. */
  17692. node = elems; /* next internal node of the tree */
  17693. do {
  17694. //pqremove(s, tree, n); /* n = node of least frequency */
  17695. /*** pqremove ***/
  17696. n = s.heap[1/*SMALLEST*/];
  17697. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  17698. pqdownheap(s, tree, 1/*SMALLEST*/);
  17699. /***/
  17700. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  17701. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  17702. s.heap[--s.heap_max] = m;
  17703. /* Create a new node father of n and m */
  17704. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  17705. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  17706. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  17707. /* and insert the new node in the heap */
  17708. s.heap[1/*SMALLEST*/] = node++;
  17709. pqdownheap(s, tree, 1/*SMALLEST*/);
  17710. } while (s.heap_len >= 2);
  17711. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  17712. /* At this point, the fields freq and dad are set. We can now
  17713. * generate the bit lengths.
  17714. */
  17715. gen_bitlen(s, desc);
  17716. /* The field len is now set, we can generate the bit codes */
  17717. gen_codes(tree, max_code, s.bl_count);
  17718. }
  17719. /* ===========================================================================
  17720. * Scan a literal or distance tree to determine the frequencies of the codes
  17721. * in the bit length tree.
  17722. */
  17723. function scan_tree(s, tree, max_code)
  17724. // deflate_state *s;
  17725. // ct_data *tree; /* the tree to be scanned */
  17726. // int max_code; /* and its largest code of non zero frequency */
  17727. {
  17728. var n; /* iterates over all tree elements */
  17729. var prevlen = -1; /* last emitted length */
  17730. var curlen; /* length of current code */
  17731. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  17732. var count = 0; /* repeat count of the current code */
  17733. var max_count = 7; /* max repeat count */
  17734. var min_count = 4; /* min repeat count */
  17735. if (nextlen === 0) {
  17736. max_count = 138;
  17737. min_count = 3;
  17738. }
  17739. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  17740. for (n = 0; n <= max_code; n++) {
  17741. curlen = nextlen;
  17742. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  17743. if (++count < max_count && curlen === nextlen) {
  17744. continue;
  17745. } else if (count < min_count) {
  17746. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  17747. } else if (curlen !== 0) {
  17748. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  17749. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  17750. } else if (count <= 10) {
  17751. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  17752. } else {
  17753. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  17754. }
  17755. count = 0;
  17756. prevlen = curlen;
  17757. if (nextlen === 0) {
  17758. max_count = 138;
  17759. min_count = 3;
  17760. } else if (curlen === nextlen) {
  17761. max_count = 6;
  17762. min_count = 3;
  17763. } else {
  17764. max_count = 7;
  17765. min_count = 4;
  17766. }
  17767. }
  17768. }
  17769. /* ===========================================================================
  17770. * Send a literal or distance tree in compressed form, using the codes in
  17771. * bl_tree.
  17772. */
  17773. function send_tree(s, tree, max_code)
  17774. // deflate_state *s;
  17775. // ct_data *tree; /* the tree to be scanned */
  17776. // int max_code; /* and its largest code of non zero frequency */
  17777. {
  17778. var n; /* iterates over all tree elements */
  17779. var prevlen = -1; /* last emitted length */
  17780. var curlen; /* length of current code */
  17781. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  17782. var count = 0; /* repeat count of the current code */
  17783. var max_count = 7; /* max repeat count */
  17784. var min_count = 4; /* min repeat count */
  17785. /* tree[max_code+1].Len = -1; */ /* guard already set */
  17786. if (nextlen === 0) {
  17787. max_count = 138;
  17788. min_count = 3;
  17789. }
  17790. for (n = 0; n <= max_code; n++) {
  17791. curlen = nextlen;
  17792. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  17793. if (++count < max_count && curlen === nextlen) {
  17794. continue;
  17795. } else if (count < min_count) {
  17796. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  17797. } else if (curlen !== 0) {
  17798. if (curlen !== prevlen) {
  17799. send_code(s, curlen, s.bl_tree);
  17800. count--;
  17801. }
  17802. //Assert(count >= 3 && count <= 6, " 3_6?");
  17803. send_code(s, REP_3_6, s.bl_tree);
  17804. send_bits(s, count-3, 2);
  17805. } else if (count <= 10) {
  17806. send_code(s, REPZ_3_10, s.bl_tree);
  17807. send_bits(s, count-3, 3);
  17808. } else {
  17809. send_code(s, REPZ_11_138, s.bl_tree);
  17810. send_bits(s, count-11, 7);
  17811. }
  17812. count = 0;
  17813. prevlen = curlen;
  17814. if (nextlen === 0) {
  17815. max_count = 138;
  17816. min_count = 3;
  17817. } else if (curlen === nextlen) {
  17818. max_count = 6;
  17819. min_count = 3;
  17820. } else {
  17821. max_count = 7;
  17822. min_count = 4;
  17823. }
  17824. }
  17825. }
  17826. /* ===========================================================================
  17827. * Construct the Huffman tree for the bit lengths and return the index in
  17828. * bl_order of the last bit length code to send.
  17829. */
  17830. function build_bl_tree(s) {
  17831. var max_blindex; /* index of last bit length code of non zero freq */
  17832. /* Determine the bit length frequencies for literal and distance trees */
  17833. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  17834. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  17835. /* Build the bit length tree: */
  17836. build_tree(s, s.bl_desc);
  17837. /* opt_len now includes the length of the tree representations, except
  17838. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  17839. */
  17840. /* Determine the number of bit length codes to send. The pkzip format
  17841. * requires that at least 4 bit length codes be sent. (appnote.txt says
  17842. * 3 but the actual value used is 4.)
  17843. */
  17844. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  17845. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  17846. break;
  17847. }
  17848. }
  17849. /* Update opt_len to include the bit length tree and counts */
  17850. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  17851. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  17852. // s->opt_len, s->static_len));
  17853. return max_blindex;
  17854. }
  17855. /* ===========================================================================
  17856. * Send the header for a block using dynamic Huffman trees: the counts, the
  17857. * lengths of the bit length codes, the literal tree and the distance tree.
  17858. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  17859. */
  17860. function send_all_trees(s, lcodes, dcodes, blcodes)
  17861. // deflate_state *s;
  17862. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  17863. {
  17864. var rank; /* index in bl_order */
  17865. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  17866. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  17867. // "too many codes");
  17868. //Tracev((stderr, "\nbl counts: "));
  17869. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  17870. send_bits(s, dcodes-1, 5);
  17871. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  17872. for (rank = 0; rank < blcodes; rank++) {
  17873. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  17874. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  17875. }
  17876. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  17877. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  17878. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  17879. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  17880. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  17881. }
  17882. /* ===========================================================================
  17883. * Check if the data type is TEXT or BINARY, using the following algorithm:
  17884. * - TEXT if the two conditions below are satisfied:
  17885. * a) There are no non-portable control characters belonging to the
  17886. * "black list" (0..6, 14..25, 28..31).
  17887. * b) There is at least one printable character belonging to the
  17888. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  17889. * - BINARY otherwise.
  17890. * - The following partially-portable control characters form a
  17891. * "gray list" that is ignored in this detection algorithm:
  17892. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  17893. * IN assertion: the fields Freq of dyn_ltree are set.
  17894. */
  17895. function detect_data_type(s) {
  17896. /* black_mask is the bit mask of black-listed bytes
  17897. * set bits 0..6, 14..25, and 28..31
  17898. * 0xf3ffc07f = binary 11110011111111111100000001111111
  17899. */
  17900. var black_mask = 0xf3ffc07f;
  17901. var n;
  17902. /* Check for non-textual ("black-listed") bytes. */
  17903. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  17904. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  17905. return Z_BINARY;
  17906. }
  17907. }
  17908. /* Check for textual ("white-listed") bytes. */
  17909. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  17910. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  17911. return Z_TEXT;
  17912. }
  17913. for (n = 32; n < LITERALS; n++) {
  17914. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  17915. return Z_TEXT;
  17916. }
  17917. }
  17918. /* There are no "black-listed" or "white-listed" bytes:
  17919. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  17920. */
  17921. return Z_BINARY;
  17922. }
  17923. var static_init_done = false;
  17924. /* ===========================================================================
  17925. * Initialize the tree data structures for a new zlib stream.
  17926. */
  17927. function _tr_init(s)
  17928. {
  17929. if (!static_init_done) {
  17930. tr_static_init();
  17931. static_init_done = true;
  17932. }
  17933. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  17934. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  17935. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  17936. s.bi_buf = 0;
  17937. s.bi_valid = 0;
  17938. /* Initialize the first block of the first file: */
  17939. init_block(s);
  17940. }
  17941. /* ===========================================================================
  17942. * Send a stored block
  17943. */
  17944. function _tr_stored_block(s, buf, stored_len, last)
  17945. //DeflateState *s;
  17946. //charf *buf; /* input block */
  17947. //ulg stored_len; /* length of input block */
  17948. //int last; /* one if this is the last block for a file */
  17949. {
  17950. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  17951. copy_block(s, buf, stored_len, true); /* with header */
  17952. }
  17953. /* ===========================================================================
  17954. * Send one empty static block to give enough lookahead for inflate.
  17955. * This takes 10 bits, of which 7 may remain in the bit buffer.
  17956. */
  17957. function _tr_align(s) {
  17958. send_bits(s, STATIC_TREES<<1, 3);
  17959. send_code(s, END_BLOCK, static_ltree);
  17960. bi_flush(s);
  17961. }
  17962. /* ===========================================================================
  17963. * Determine the best encoding for the current block: dynamic trees, static
  17964. * trees or store, and output the encoded block to the zip file.
  17965. */
  17966. function _tr_flush_block(s, buf, stored_len, last)
  17967. //DeflateState *s;
  17968. //charf *buf; /* input block, or NULL if too old */
  17969. //ulg stored_len; /* length of input block */
  17970. //int last; /* one if this is the last block for a file */
  17971. {
  17972. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  17973. var max_blindex = 0; /* index of last bit length code of non zero freq */
  17974. /* Build the Huffman trees unless a stored block is forced */
  17975. if (s.level > 0) {
  17976. /* Check if the file is binary or text */
  17977. if (s.strm.data_type === Z_UNKNOWN) {
  17978. s.strm.data_type = detect_data_type(s);
  17979. }
  17980. /* Construct the literal and distance trees */
  17981. build_tree(s, s.l_desc);
  17982. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  17983. // s->static_len));
  17984. build_tree(s, s.d_desc);
  17985. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  17986. // s->static_len));
  17987. /* At this point, opt_len and static_len are the total bit lengths of
  17988. * the compressed block data, excluding the tree representations.
  17989. */
  17990. /* Build the bit length tree for the above two trees, and get the index
  17991. * in bl_order of the last bit length code to send.
  17992. */
  17993. max_blindex = build_bl_tree(s);
  17994. /* Determine the best encoding. Compute the block lengths in bytes. */
  17995. opt_lenb = (s.opt_len+3+7) >>> 3;
  17996. static_lenb = (s.static_len+3+7) >>> 3;
  17997. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  17998. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  17999. // s->last_lit));
  18000. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  18001. } else {
  18002. // Assert(buf != (char*)0, "lost buf");
  18003. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  18004. }
  18005. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  18006. /* 4: two words for the lengths */
  18007. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  18008. * Otherwise we can't have processed more than WSIZE input bytes since
  18009. * the last block flush, because compression would have been
  18010. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  18011. * transform a block into a stored block.
  18012. */
  18013. _tr_stored_block(s, buf, stored_len, last);
  18014. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  18015. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  18016. compress_block(s, static_ltree, static_dtree);
  18017. } else {
  18018. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  18019. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  18020. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  18021. }
  18022. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  18023. /* The above check is made mod 2^32, for files larger than 512 MB
  18024. * and uLong implemented on 32 bits.
  18025. */
  18026. init_block(s);
  18027. if (last) {
  18028. bi_windup(s);
  18029. }
  18030. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  18031. // s->compressed_len-7*last));
  18032. }
  18033. /* ===========================================================================
  18034. * Save the match info and tally the frequency counts. Return true if
  18035. * the current block must be flushed.
  18036. */
  18037. function _tr_tally(s, dist, lc)
  18038. // deflate_state *s;
  18039. // unsigned dist; /* distance of matched string */
  18040. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  18041. {
  18042. //var out_length, in_length, dcode;
  18043. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  18044. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  18045. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  18046. s.last_lit++;
  18047. if (dist === 0) {
  18048. /* lc is the unmatched char */
  18049. s.dyn_ltree[lc*2]/*.Freq*/++;
  18050. } else {
  18051. s.matches++;
  18052. /* Here, lc is the match length - MIN_MATCH */
  18053. dist--; /* dist = match distance - 1 */
  18054. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  18055. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  18056. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  18057. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  18058. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  18059. }
  18060. // (!) This block is disabled in zlib defailts,
  18061. // don't enable it for binary compatibility
  18062. //#ifdef TRUNCATE_BLOCK
  18063. // /* Try to guess if it is profitable to stop the current block here */
  18064. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  18065. // /* Compute an upper bound for the compressed length */
  18066. // out_length = s.last_lit*8;
  18067. // in_length = s.strstart - s.block_start;
  18068. //
  18069. // for (dcode = 0; dcode < D_CODES; dcode++) {
  18070. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  18071. // }
  18072. // out_length >>>= 3;
  18073. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  18074. // // s->last_lit, in_length, out_length,
  18075. // // 100L - out_length*100L/in_length));
  18076. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  18077. // return true;
  18078. // }
  18079. // }
  18080. //#endif
  18081. return (s.last_lit === s.lit_bufsize-1);
  18082. /* We avoid equality with lit_bufsize because of wraparound at 64K
  18083. * on 16 bit machines and because stored blocks are restricted to
  18084. * 64K-1 bytes.
  18085. */
  18086. }
  18087. exports._tr_init = _tr_init;
  18088. exports._tr_stored_block = _tr_stored_block;
  18089. exports._tr_flush_block = _tr_flush_block;
  18090. exports._tr_tally = _tr_tally;
  18091. exports._tr_align = _tr_align;
  18092. },{"../utils/common":51}],63:[function(require,module,exports){
  18093. 'use strict';
  18094. function ZStream() {
  18095. /* next input byte */
  18096. this.input = null; // JS specific, because we have no pointers
  18097. this.next_in = 0;
  18098. /* number of bytes available at input */
  18099. this.avail_in = 0;
  18100. /* total number of input bytes read so far */
  18101. this.total_in = 0;
  18102. /* next output byte should be put there */
  18103. this.output = null; // JS specific, because we have no pointers
  18104. this.next_out = 0;
  18105. /* remaining free space at output */
  18106. this.avail_out = 0;
  18107. /* total number of bytes output so far */
  18108. this.total_out = 0;
  18109. /* last error message, NULL if no error */
  18110. this.msg = ''/*Z_NULL*/;
  18111. /* not visible by applications */
  18112. this.state = null;
  18113. /* best guess about the data type: binary or text */
  18114. this.data_type = 2/*Z_UNKNOWN*/;
  18115. /* adler32 value of the uncompressed data */
  18116. this.adler = 0;
  18117. }
  18118. module.exports = ZStream;
  18119. },{}],64:[function(require,module,exports){
  18120. /* Copyright @ 2015 Atlassian Pty Ltd
  18121. *
  18122. * Licensed under the Apache License, Version 2.0 (the "License");
  18123. * you may not use this file except in compliance with the License.
  18124. * You may obtain a copy of the License at
  18125. *
  18126. * http://www.apache.org/licenses/LICENSE-2.0
  18127. *
  18128. * Unless required by applicable law or agreed to in writing, software
  18129. * distributed under the License is distributed on an "AS IS" BASIS,
  18130. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18131. * See the License for the specific language governing permissions and
  18132. * limitations under the License.
  18133. */
  18134. module.exports = function arrayEquals(array) {
  18135. // if the other array is a falsy value, return
  18136. if (!array)
  18137. return false;
  18138. // compare lengths - can save a lot of time
  18139. if (this.length != array.length)
  18140. return false;
  18141. for (var i = 0, l = this.length; i < l; i++) {
  18142. // Check if we have nested arrays
  18143. if (this[i] instanceof Array && array[i] instanceof Array) {
  18144. // recurse into the nested arrays
  18145. if (!arrayEquals.apply(this[i], [array[i]]))
  18146. return false;
  18147. } else if (this[i] != array[i]) {
  18148. // Warning - two different object instances will never be equal:
  18149. // {x:20} != {x:20}
  18150. return false;
  18151. }
  18152. }
  18153. return true;
  18154. };
  18155. },{}],65:[function(require,module,exports){
  18156. /* Copyright @ 2015 Atlassian Pty Ltd
  18157. *
  18158. * Licensed under the Apache License, Version 2.0 (the "License");
  18159. * you may not use this file except in compliance with the License.
  18160. * You may obtain a copy of the License at
  18161. *
  18162. * http://www.apache.org/licenses/LICENSE-2.0
  18163. *
  18164. * Unless required by applicable law or agreed to in writing, software
  18165. * distributed under the License is distributed on an "AS IS" BASIS,
  18166. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18167. * See the License for the specific language governing permissions and
  18168. * limitations under the License.
  18169. */
  18170. exports.Interop = require('./interop');
  18171. },{"./interop":66}],66:[function(require,module,exports){
  18172. /* Copyright @ 2015 Atlassian Pty Ltd
  18173. *
  18174. * Licensed under the Apache License, Version 2.0 (the "License");
  18175. * you may not use this file except in compliance with the License.
  18176. * You may obtain a copy of the License at
  18177. *
  18178. * http://www.apache.org/licenses/LICENSE-2.0
  18179. *
  18180. * Unless required by applicable law or agreed to in writing, software
  18181. * distributed under the License is distributed on an "AS IS" BASIS,
  18182. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18183. * See the License for the specific language governing permissions and
  18184. * limitations under the License.
  18185. */
  18186. /* global RTCSessionDescription */
  18187. /* jshint -W097 */
  18188. "use strict";
  18189. var transform = require('./transform');
  18190. var arrayEquals = require('./array-equals');
  18191. function Interop() {
  18192. /**
  18193. * This map holds the most recent Unified Plan offer/answer SDP that was
  18194. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  18195. * the SDP string as values.
  18196. *
  18197. * @type {{}}
  18198. */
  18199. this.cache = {};
  18200. }
  18201. module.exports = Interop;
  18202. /**
  18203. * Returns the index of the first m-line with the given media type and with a
  18204. * direction which allows sending, in the last Unified Plan description with
  18205. * type "answer" converted to Plan B. Returns {null} if there is no saved
  18206. * answer, or if none of its m-lines with the given type allow sending.
  18207. * @param type the media type ("audio" or "video").
  18208. * @returns {*}
  18209. */
  18210. Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {
  18211. if (!this.cache.answer) {
  18212. return null;
  18213. }
  18214. var session = transform.parse(this.cache.answer);
  18215. if (session && session.media && Array.isArray(session.media)){
  18216. for (var i = 0; i < session.media.length; i++) {
  18217. if (session.media[i].type == type &&
  18218. (!session.media[i].direction /* default to sendrecv */ ||
  18219. session.media[i].direction === 'sendrecv' ||
  18220. session.media[i].direction === 'sendonly')){
  18221. return i;
  18222. }
  18223. }
  18224. }
  18225. return null;
  18226. };
  18227. /**
  18228. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  18229. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  18230. * application.
  18231. *
  18232. * @param desc
  18233. * @returns {*}
  18234. */
  18235. Interop.prototype.toPlanB = function(desc) {
  18236. var self = this;
  18237. //#region Preliminary input validation.
  18238. if (typeof desc !== 'object' || desc === null ||
  18239. typeof desc.sdp !== 'string') {
  18240. console.warn('An empty description was passed as an argument.');
  18241. return desc;
  18242. }
  18243. // Objectify the SDP for easier manipulation.
  18244. var session = transform.parse(desc.sdp);
  18245. // If the SDP contains no media, there's nothing to transform.
  18246. if (typeof session.media === 'undefined' ||
  18247. !Array.isArray(session.media) || session.media.length === 0) {
  18248. console.warn('The description has no media.');
  18249. return desc;
  18250. }
  18251. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  18252. // SDP has a video, an audio and a data "channel" at most.
  18253. if (session.media.length <= 3 && session.media.every(function(m) {
  18254. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  18255. })) {
  18256. console.warn('This description does not look like Unified Plan.');
  18257. return desc;
  18258. }
  18259. //#endregion
  18260. // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443
  18261. var sdp = desc.sdp;
  18262. var rewrite = false;
  18263. for (var i = 0; i < session.media.length; i++) {
  18264. var uLine = session.media[i];
  18265. uLine.rtp.forEach(function(rtp) {
  18266. if (rtp.codec === 'NULL')
  18267. {
  18268. rewrite = true;
  18269. var offer = transform.parse(self.cache['offer']);
  18270. rtp.codec = offer.media[i].rtp[0].codec;
  18271. }
  18272. });
  18273. };
  18274. if (rewrite) {
  18275. sdp = transform.write(session);
  18276. }
  18277. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  18278. // -> Unified Plan transformation.
  18279. this.cache[desc.type] = sdp;
  18280. //#region Convert from Unified Plan to Plan B.
  18281. // We rebuild the session.media array.
  18282. var media = session.media;
  18283. session.media = [];
  18284. // Associative array that maps channel types to channel objects for fast
  18285. // access to channel objects by their type, e.g. type2bl['audio']->channel
  18286. // obj.
  18287. var type2bl = {};
  18288. // Used to build the group:BUNDLE value after the channels construction
  18289. // loop.
  18290. var types = [];
  18291. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  18292. media.forEach(function(uLine) {
  18293. // rtcp-mux is required in the Plan B SDP.
  18294. if ((typeof uLine.rtcpMux !== 'string' ||
  18295. uLine.rtcpMux !== 'rtcp-mux') &&
  18296. uLine.direction !== 'inactive') {
  18297. throw new Error('Cannot convert to Plan B because m-lines ' +
  18298. 'without the rtcp-mux attribute were found.');
  18299. }
  18300. if (uLine.type === 'application') {
  18301. session.media.push(uLine);
  18302. types.push(uLine.mid);
  18303. return;
  18304. }
  18305. // If we don't have a channel for this uLine.type, then use this
  18306. // uLine as the channel basis.
  18307. if (typeof type2bl[uLine.type] === 'undefined') {
  18308. type2bl[uLine.type] = uLine;
  18309. }
  18310. // Add sources to the channel and handle a=msid.
  18311. if (typeof uLine.sources === 'object') {
  18312. Object.keys(uLine.sources).forEach(function(ssrc) {
  18313. if (typeof type2bl[uLine.type].sources !== 'object')
  18314. type2bl[uLine.type].sources = {};
  18315. // Assign the sources to the channel.
  18316. type2bl[uLine.type].sources[ssrc] =
  18317. uLine.sources[ssrc];
  18318. if (typeof uLine.msid !== 'undefined') {
  18319. // In Plan B the msid is an SSRC attribute. Also, we don't
  18320. // care about the obsolete label and mslabel attributes.
  18321. //
  18322. // Note that it is not guaranteed that the uLine will
  18323. // have an msid. recvonly channels in particular don't have
  18324. // one.
  18325. type2bl[uLine.type].sources[ssrc].msid =
  18326. uLine.msid;
  18327. }
  18328. // NOTE ssrcs in ssrc groups will share msids, as
  18329. // draft-uberti-rtcweb-plan-00 mandates.
  18330. });
  18331. }
  18332. // Add ssrc groups to the channel.
  18333. if (typeof uLine.ssrcGroups !== 'undefined' &&
  18334. Array.isArray(uLine.ssrcGroups)) {
  18335. // Create the ssrcGroups array, if it's not defined.
  18336. if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||
  18337. !Array.isArray(type2bl[uLine.type].ssrcGroups)) {
  18338. type2bl[uLine.type].ssrcGroups = [];
  18339. }
  18340. type2bl[uLine.type].ssrcGroups =
  18341. type2bl[uLine.type].ssrcGroups.concat(
  18342. uLine.ssrcGroups);
  18343. }
  18344. if (type2bl[uLine.type] === uLine) {
  18345. // Copy ICE related stuff from the principal media line.
  18346. uLine.candidates = media[0].candidates;
  18347. uLine.iceUfrag = media[0].iceUfrag;
  18348. uLine.icePwd = media[0].icePwd;
  18349. uLine.fingerprint = media[0].fingerprint;
  18350. // Plan B mids are in ['audio', 'video', 'data']
  18351. uLine.mid = uLine.type;
  18352. // Plan B doesn't support/need the bundle-only attribute.
  18353. delete uLine.bundleOnly;
  18354. // In Plan B the msid is an SSRC attribute.
  18355. delete uLine.msid;
  18356. // Used to build the group:BUNDLE value after this loop.
  18357. types.push(uLine.type);
  18358. // Add the channel to the new media array.
  18359. session.media.push(uLine);
  18360. }
  18361. });
  18362. // We regenerate the BUNDLE group with the new mids.
  18363. session.groups.some(function(group) {
  18364. if (group.type === 'BUNDLE') {
  18365. group.mids = types.join(' ');
  18366. return true;
  18367. }
  18368. });
  18369. // msid semantic
  18370. session.msidSemantic = {
  18371. semantic: 'WMS',
  18372. token: '*'
  18373. };
  18374. var resStr = transform.write(session);
  18375. return new RTCSessionDescription({
  18376. type: desc.type,
  18377. sdp: resStr
  18378. });
  18379. //#endregion
  18380. };
  18381. /**
  18382. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  18383. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  18384. * to FF.
  18385. *
  18386. * @param desc
  18387. * @returns {*}
  18388. */
  18389. Interop.prototype.toUnifiedPlan = function(desc) {
  18390. var self = this;
  18391. //#region Preliminary input validation.
  18392. if (typeof desc !== 'object' || desc === null ||
  18393. typeof desc.sdp !== 'string') {
  18394. console.warn('An empty description was passed as an argument.');
  18395. return desc;
  18396. }
  18397. var session = transform.parse(desc.sdp);
  18398. // If the SDP contains no media, there's nothing to transform.
  18399. if (typeof session.media === 'undefined' ||
  18400. !Array.isArray(session.media) || session.media.length === 0) {
  18401. console.warn('The description has no media.');
  18402. return desc;
  18403. }
  18404. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  18405. // a video, an audio and a data "channel" at most.
  18406. if (session.media.length > 3 || !session.media.every(function(m) {
  18407. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  18408. })) {
  18409. console.warn('This description does not look like Plan B.');
  18410. return desc;
  18411. }
  18412. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  18413. var mids = [];
  18414. session.media.forEach(function(m) {
  18415. mids.push(m.mid);
  18416. });
  18417. var hasBundle = false;
  18418. if (typeof session.groups !== 'undefined' &&
  18419. Array.isArray(session.groups)) {
  18420. hasBundle = session.groups.every(function(g) {
  18421. return g.type !== 'BUNDLE' ||
  18422. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  18423. });
  18424. }
  18425. if (!hasBundle) {
  18426. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  18427. " are not bundled were found.");
  18428. }
  18429. //#endregion
  18430. //#region Convert from Plan B to Unified Plan.
  18431. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  18432. // rebuild an equivalent Unified Plan offer/answer.
  18433. //
  18434. // For example, if this is a local answer (in Unified Plan style) that we
  18435. // convert to Plan B prior to handing it over to the application (the
  18436. // PeerConnection wrapper called us, for instance, after a successful
  18437. // createAnswer), we want to remember the m-line at which we've seen the
  18438. // (local) SSRC. That's because when the application wants to do call the
  18439. // SLD method, forcing us to do the inverse transformation (from Plan B to
  18440. // Unified Plan), we need to know to which m-line to assign the (local)
  18441. // SSRC. We also need to know all the other m-lines that the original
  18442. // answer had and include them in the transformed answer as well.
  18443. //
  18444. // Another example is if this is a remote offer that we convert to Plan B
  18445. // prior to giving it to the application, we want to remember the mid at
  18446. // which we've seen the (remote) SSRC.
  18447. //
  18448. // In the iteration that follows, we use the cached Unified Plan (if it
  18449. // exists) to assign mids to ssrcs.
  18450. var cached;
  18451. if (typeof this.cache[desc.type] !== 'undefined') {
  18452. cached = transform.parse(this.cache[desc.type]);
  18453. }
  18454. var recvonlySsrcs = {
  18455. audio: {},
  18456. video: {}
  18457. };
  18458. // A helper map that sends mids to m-line objects. We use it later to
  18459. // rebuild the Unified Plan style session.media array.
  18460. var mid2ul = {};
  18461. session.media.forEach(function(bLine) {
  18462. if ((typeof bLine.rtcpMux !== 'string' ||
  18463. bLine.rtcpMux !== 'rtcp-mux') &&
  18464. bLine.direction !== 'inactive') {
  18465. throw new Error("Cannot convert to Unified Plan because m-lines " +
  18466. "without the rtcp-mux attribute were found.");
  18467. }
  18468. if (bLine.type === 'application') {
  18469. mid2ul[bLine.mid] = bLine;
  18470. return;
  18471. }
  18472. // With rtcp-mux and bundle all the channels should have the same ICE
  18473. // stuff.
  18474. var sources = bLine.sources;
  18475. var ssrcGroups = bLine.ssrcGroups;
  18476. var candidates = bLine.candidates;
  18477. var iceUfrag = bLine.iceUfrag;
  18478. var icePwd = bLine.icePwd;
  18479. var fingerprint = bLine.fingerprint;
  18480. var port = bLine.port;
  18481. // We'll use the "bLine" object as a prototype for each new "mLine"
  18482. // that we create, but first we need to clean it up a bit.
  18483. delete bLine.sources;
  18484. delete bLine.ssrcGroups;
  18485. delete bLine.candidates;
  18486. delete bLine.iceUfrag;
  18487. delete bLine.icePwd;
  18488. delete bLine.fingerprint;
  18489. delete bLine.port;
  18490. delete bLine.mid;
  18491. // inverted ssrc group map
  18492. var ssrc2group = {};
  18493. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  18494. ssrcGroups.forEach(function (ssrcGroup) {
  18495. // TODO(gp) find out how to receive simulcast with FF. For the
  18496. // time being, hide it.
  18497. if (ssrcGroup.semantics === 'SIM') {
  18498. return;
  18499. }
  18500. // XXX This might brake if an SSRC is in more than one group
  18501. // for some reason.
  18502. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  18503. Array.isArray(ssrcGroup.ssrcs)) {
  18504. ssrcGroup.ssrcs.forEach(function (ssrc) {
  18505. if (typeof ssrc2group[ssrc] === 'undefined') {
  18506. ssrc2group[ssrc] = [];
  18507. }
  18508. ssrc2group[ssrc].push(ssrcGroup);
  18509. });
  18510. }
  18511. });
  18512. }
  18513. // ssrc to m-line index.
  18514. var ssrc2ml = {};
  18515. if (typeof sources === 'object') {
  18516. // Explode the Plan B channel sources with one m-line per source.
  18517. Object.keys(sources).forEach(function(ssrc) {
  18518. // The (unified) m-line for this SSRC. We either create it from
  18519. // scratch or, if it's a grouped SSRC, we re-use a related
  18520. // mline. In other words, if the source is grouped with another
  18521. // source, put the two together in the same m-line.
  18522. var uLine;
  18523. // We assume here that we are the answerer in the O/A, so any
  18524. // offers which we translate come from the remote side, while
  18525. // answers are local. So the check below is to make that we
  18526. // handle receive-only SSRCs in a special way only if they come
  18527. // from the remote side.
  18528. if (desc.type==='offer') {
  18529. // We want to detect SSRCs which are used by a remote peer
  18530. // in an m-line with direction=recvonly (i.e. they are
  18531. // being used for RTCP only).
  18532. // This information would have gotten lost if the remote
  18533. // peer used Unified Plan and their local description was
  18534. // translated to Plan B. So we use the lack of an MSID
  18535. // attribute to deduce a "receive only" SSRC.
  18536. if (!sources[ssrc].msid) {
  18537. recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];
  18538. // Receive-only SSRCs must not create new m-lines. We
  18539. // will assign them to an existing m-line later.
  18540. return;
  18541. }
  18542. }
  18543. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  18544. Array.isArray(ssrc2group[ssrc])) {
  18545. ssrc2group[ssrc].some(function (ssrcGroup) {
  18546. // ssrcGroup.ssrcs *is* an Array, no need to check
  18547. // again here.
  18548. return ssrcGroup.ssrcs.some(function (related) {
  18549. if (typeof ssrc2ml[related] === 'object') {
  18550. uLine = ssrc2ml[related];
  18551. return true;
  18552. }
  18553. });
  18554. });
  18555. }
  18556. if (typeof uLine === 'object') {
  18557. // the m-line already exists. Just add the source.
  18558. uLine.sources[ssrc] = sources[ssrc];
  18559. delete sources[ssrc].msid;
  18560. } else {
  18561. // Use the "bLine" as a prototype for the "uLine".
  18562. uLine = Object.create(bLine);
  18563. ssrc2ml[ssrc] = uLine;
  18564. if (typeof sources[ssrc].msid !== 'undefined') {
  18565. // Assign the msid of the source to the m-line. Note
  18566. // that it is not guaranteed that the source will have
  18567. // msid. In particular "recvonly" sources don't have an
  18568. // msid. Note that "recvonly" is a term only defined
  18569. // for m-lines.
  18570. uLine.msid = sources[ssrc].msid;
  18571. uLine.direction = 'sendrecv';
  18572. delete sources[ssrc].msid;
  18573. }
  18574. // We assign one SSRC per media line.
  18575. uLine.sources = {};
  18576. uLine.sources[ssrc] = sources[ssrc];
  18577. uLine.ssrcGroups = ssrc2group[ssrc];
  18578. // Use the cached Unified Plan SDP (if it exists) to assign
  18579. // SSRCs to mids.
  18580. if (typeof cached !== 'undefined' &&
  18581. typeof cached.media !== 'undefined' &&
  18582. Array.isArray(cached.media)) {
  18583. cached.media.forEach(function (m) {
  18584. if (typeof m.sources === 'object') {
  18585. Object.keys(m.sources).forEach(function (s) {
  18586. if (s === ssrc) {
  18587. uLine.mid = m.mid;
  18588. }
  18589. });
  18590. }
  18591. });
  18592. }
  18593. if (typeof uLine.mid === 'undefined') {
  18594. // If this is an SSRC that we see for the first time
  18595. // assign it a new mid. This is typically the case when
  18596. // this method is called to transform a remote
  18597. // description for the first time or when there is a
  18598. // new SSRC in the remote description because a new
  18599. // peer has joined the conference. Local SSRCs should
  18600. // have already been added to the map in the toPlanB
  18601. // method.
  18602. //
  18603. // Because FF generates answers in Unified Plan style,
  18604. // we MUST already have a cached answer with all the
  18605. // local SSRCs mapped to some m-line/mid.
  18606. if (desc.type === 'answer') {
  18607. throw new Error("An unmapped SSRC was found.");
  18608. }
  18609. uLine.mid = [bLine.type, '-', ssrc].join('');
  18610. }
  18611. // Include the candidates in the 1st media line.
  18612. uLine.candidates = candidates;
  18613. uLine.iceUfrag = iceUfrag;
  18614. uLine.icePwd = icePwd;
  18615. uLine.fingerprint = fingerprint;
  18616. uLine.port = port;
  18617. mid2ul[uLine.mid] = uLine;
  18618. }
  18619. });
  18620. }
  18621. });
  18622. // Rebuild the media array in the right order and add the missing mLines
  18623. // (missing from the Plan B SDP).
  18624. session.media = [];
  18625. mids = []; // reuse
  18626. if (desc.type === 'answer') {
  18627. // The media lines in the answer must match the media lines in the
  18628. // offer. The order is important too. Here we assume that Firefox is
  18629. // the answerer, so we merely have to use the reconstructed (unified)
  18630. // answer to update the cached (unified) answer accordingly.
  18631. //
  18632. // In the general case, one would have to use the cached (unified)
  18633. // offer to find the m-lines that are missing from the reconstructed
  18634. // answer, potentially grabbing them from the cached (unified) answer.
  18635. // One has to be careful with this approach because inactive m-lines do
  18636. // not always have an mid, making it tricky (impossible?) to find where
  18637. // exactly and which m-lines are missing from the reconstructed answer.
  18638. for (var i = 0; i < cached.media.length; i++) {
  18639. var uLine = cached.media[i];
  18640. if (typeof mid2ul[uLine.mid] === 'undefined') {
  18641. // The mid isn't in the reconstructed (unified) answer.
  18642. // This is either a (unified) m-line containing a remote
  18643. // track only, or a (unified) m-line containing a remote
  18644. // track and a local track that has been removed.
  18645. // In either case, it MUST exist in the cached
  18646. // (unified) answer.
  18647. //
  18648. // In case this is a removed local track, clean-up
  18649. // the (unified) m-line and make sure it's 'recvonly' or
  18650. // 'inactive'.
  18651. delete uLine.msid;
  18652. delete uLine.sources;
  18653. delete uLine.ssrcGroups;
  18654. if (!uLine.direction
  18655. || uLine.direction === 'sendrecv')
  18656. uLine.direction = 'recvonly';
  18657. else if (uLine.direction === 'sendonly')
  18658. uLine.direction = 'inactive';
  18659. } else {
  18660. // This is an (unified) m-line/channel that contains a local
  18661. // track (sendrecv or sendonly channel) or it's a unified
  18662. // recvonly m-line/channel. In either case, since we're
  18663. // going from PlanB -> Unified Plan this m-line MUST
  18664. // exist in the cached answer.
  18665. }
  18666. session.media.push(uLine);
  18667. if (typeof uLine.mid === 'string') {
  18668. // inactive lines don't/may not have an mid.
  18669. mids.push(uLine.mid);
  18670. }
  18671. }
  18672. } else {
  18673. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  18674. // under any circumstances. If we are no longer interested in sending a
  18675. // track, we just remove the msid and ssrc attributes and set it to
  18676. // either a=recvonly (as the reofferer, we must use recvonly if the
  18677. // other side was previously sending on the m-section, but we can also
  18678. // leave the possibility open if it wasn't previously in use), or
  18679. // a=inactive.
  18680. if (typeof cached !== 'undefined' &&
  18681. typeof cached.media !== 'undefined' &&
  18682. Array.isArray(cached.media)) {
  18683. cached.media.forEach(function(uLine) {
  18684. mids.push(uLine.mid);
  18685. if (typeof mid2ul[uLine.mid] !== 'undefined') {
  18686. session.media.push(mid2ul[uLine.mid]);
  18687. } else {
  18688. delete uLine.msid;
  18689. delete uLine.sources;
  18690. delete uLine.ssrcGroups;
  18691. if (!uLine.direction
  18692. || uLine.direction === 'sendrecv')
  18693. uLine.direction = 'recvonly';
  18694. if (!uLine.direction
  18695. || uLine.direction === 'sendonly')
  18696. uLine.direction = 'inactive';
  18697. session.media.push(uLine);
  18698. }
  18699. });
  18700. }
  18701. // Add all the remaining (new) m-lines of the transformed SDP.
  18702. Object.keys(mid2ul).forEach(function(mid) {
  18703. if (mids.indexOf(mid) === -1) {
  18704. mids.push(mid);
  18705. if (mid2ul[mid].direction === 'recvonly') {
  18706. // This is a remote recvonly channel. Add its SSRC to the
  18707. // appropriate sendrecv or sendonly channel.
  18708. // TODO(gp) what if we don't have sendrecv/sendonly
  18709. // channel?
  18710. session.media.some(function (uLine) {
  18711. if ((uLine.direction === 'sendrecv' ||
  18712. uLine.direction === 'sendonly') &&
  18713. uLine.type === mid2ul[mid].type) {
  18714. // mid2ul[mid] shouldn't have any ssrc-groups
  18715. Object.keys(mid2ul[mid].sources).forEach(
  18716. function (ssrc) {
  18717. uLine.sources[ssrc] =
  18718. mid2ul[mid].sources[ssrc];
  18719. });
  18720. return true;
  18721. }
  18722. });
  18723. } else {
  18724. session.media.push(mid2ul[mid]);
  18725. }
  18726. }
  18727. });
  18728. }
  18729. // After we have constructed the Plan Unified m-lines we can figure out
  18730. // where (in which m-line) to place the 'recvonly SSRCs'.
  18731. // Note: we assume here that we are the answerer in the O/A, so any offers
  18732. // which we translate come from the remote side, while answers are local
  18733. // (and so our last local description is cached as an 'answer').
  18734. ["audio", "video"].forEach(function (type) {
  18735. if (!session || !session.media || !Array.isArray(session.media))
  18736. return;
  18737. var idx = null;
  18738. if (Object.keys(recvonlySsrcs[type]).length > 0) {
  18739. idx = self.getFirstSendingIndexFromAnswer(type);
  18740. if (idx === null){
  18741. // If this is the first offer we receive, we don't have a
  18742. // cached answer. Assume that we will be sending media using
  18743. // the first m-line for each media type.
  18744. for (var i = 0; i < session.media.length; i++) {
  18745. if (session.media[i].type === type) {
  18746. idx = i;
  18747. break;
  18748. }
  18749. }
  18750. }
  18751. }
  18752. if (idx && session.media.length > idx) {
  18753. var mLine = session.media[idx];
  18754. Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {
  18755. if (mLine.sources && mLine.sources[ssrc]) {
  18756. console.warn("Replacing an existing SSRC.");
  18757. }
  18758. if (!mLine.sources) {
  18759. mLine.sources = {};
  18760. }
  18761. mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];
  18762. });
  18763. }
  18764. });
  18765. // We regenerate the BUNDLE group (since we regenerated the mids)
  18766. session.groups.some(function(group) {
  18767. if (group.type === 'BUNDLE') {
  18768. group.mids = mids.join(' ');
  18769. return true;
  18770. }
  18771. });
  18772. // msid semantic
  18773. session.msidSemantic = {
  18774. semantic: 'WMS',
  18775. token: '*'
  18776. };
  18777. var resStr = transform.write(session);
  18778. // Cache the transformed SDP (Unified Plan) for later re-use in this
  18779. // function.
  18780. this.cache[desc.type] = resStr;
  18781. return new RTCSessionDescription({
  18782. type: desc.type,
  18783. sdp: resStr
  18784. });
  18785. //#endregion
  18786. };
  18787. },{"./array-equals":64,"./transform":67}],67:[function(require,module,exports){
  18788. /* Copyright @ 2015 Atlassian Pty Ltd
  18789. *
  18790. * Licensed under the Apache License, Version 2.0 (the "License");
  18791. * you may not use this file except in compliance with the License.
  18792. * You may obtain a copy of the License at
  18793. *
  18794. * http://www.apache.org/licenses/LICENSE-2.0
  18795. *
  18796. * Unless required by applicable law or agreed to in writing, software
  18797. * distributed under the License is distributed on an "AS IS" BASIS,
  18798. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18799. * See the License for the specific language governing permissions and
  18800. * limitations under the License.
  18801. */
  18802. var transform = require('sdp-transform');
  18803. exports.write = function(session, opts) {
  18804. if (typeof session !== 'undefined' &&
  18805. typeof session.media !== 'undefined' &&
  18806. Array.isArray(session.media)) {
  18807. session.media.forEach(function (mLine) {
  18808. // expand sources to ssrcs
  18809. if (typeof mLine.sources !== 'undefined' &&
  18810. Object.keys(mLine.sources).length !== 0) {
  18811. mLine.ssrcs = [];
  18812. Object.keys(mLine.sources).forEach(function (ssrc) {
  18813. var source = mLine.sources[ssrc];
  18814. Object.keys(source).forEach(function (attribute) {
  18815. mLine.ssrcs.push({
  18816. id: ssrc,
  18817. attribute: attribute,
  18818. value: source[attribute]
  18819. });
  18820. });
  18821. });
  18822. delete mLine.sources;
  18823. }
  18824. // join ssrcs in ssrc groups
  18825. if (typeof mLine.ssrcGroups !== 'undefined' &&
  18826. Array.isArray(mLine.ssrcGroups)) {
  18827. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  18828. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  18829. Array.isArray(ssrcGroup.ssrcs)) {
  18830. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  18831. }
  18832. });
  18833. }
  18834. });
  18835. }
  18836. // join group mids
  18837. if (typeof session !== 'undefined' &&
  18838. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  18839. session.groups.forEach(function (g) {
  18840. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  18841. g.mids = g.mids.join(' ');
  18842. }
  18843. });
  18844. }
  18845. return transform.write(session, opts);
  18846. };
  18847. exports.parse = function(sdp) {
  18848. var session = transform.parse(sdp);
  18849. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  18850. Array.isArray(session.media)) {
  18851. session.media.forEach(function (mLine) {
  18852. // group sources attributes by ssrc
  18853. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  18854. mLine.sources = {};
  18855. mLine.ssrcs.forEach(function (ssrc) {
  18856. if (!mLine.sources[ssrc.id])
  18857. mLine.sources[ssrc.id] = {};
  18858. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  18859. });
  18860. delete mLine.ssrcs;
  18861. }
  18862. // split ssrcs in ssrc groups
  18863. if (typeof mLine.ssrcGroups !== 'undefined' &&
  18864. Array.isArray(mLine.ssrcGroups)) {
  18865. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  18866. if (typeof ssrcGroup.ssrcs === 'string') {
  18867. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  18868. }
  18869. });
  18870. }
  18871. });
  18872. }
  18873. // split group mids
  18874. if (typeof session !== 'undefined' &&
  18875. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  18876. session.groups.forEach(function (g) {
  18877. if (typeof g.mids === 'string') {
  18878. g.mids = g.mids.split(' ');
  18879. }
  18880. });
  18881. }
  18882. return session;
  18883. };
  18884. },{"sdp-transform":75}],68:[function(require,module,exports){
  18885. /* Copyright @ 2015 Atlassian Pty Ltd
  18886. *
  18887. * Licensed under the Apache License, Version 2.0 (the "License");
  18888. * you may not use this file except in compliance with the License.
  18889. * You may obtain a copy of the License at
  18890. *
  18891. * http://www.apache.org/licenses/LICENSE-2.0
  18892. *
  18893. * Unless required by applicable law or agreed to in writing, software
  18894. * distributed under the License is distributed on an "AS IS" BASIS,
  18895. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18896. * See the License for the specific language governing permissions and
  18897. * limitations under the License.
  18898. */
  18899. var transform = require('sdp-transform');
  18900. var transformUtils = require('./transform-utils');
  18901. var parseSsrcs = transformUtils.parseSsrcs;
  18902. var writeSsrcs = transformUtils.writeSsrcs;
  18903. //region Constants
  18904. var DEFAULT_NUM_OF_LAYERS = 3;
  18905. //endregion
  18906. //region Ctor
  18907. function Simulcast(options) {
  18908. this.options = options ? options : {};
  18909. if (!this.options.numOfLayers) {
  18910. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  18911. }
  18912. this.layers = [];
  18913. }
  18914. //endregion
  18915. //region Stateless private utility functions
  18916. /**
  18917. * Returns a random integer between min (included) and max (excluded)
  18918. * Using Math.round() gives a non-uniform distribution!
  18919. * @returns {number}
  18920. */
  18921. function generateSSRC() {
  18922. var min = 0, max = 0xffffffff;
  18923. return Math.floor(Math.random() * (max - min)) + min;
  18924. };
  18925. function processVideo(session, action) {
  18926. if (session == null || !Array.isArray(session.media)) {
  18927. return;
  18928. }
  18929. session.media.forEach(function (mLine) {
  18930. if (mLine.type === 'video') {
  18931. action(mLine);
  18932. }
  18933. });
  18934. }
  18935. function validateDescription(desc)
  18936. {
  18937. return desc && desc != null
  18938. && desc.type && desc.type != ''
  18939. && desc.sdp && desc.sdp != '';
  18940. }
  18941. function explodeRemoteSimulcast(mLine) {
  18942. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  18943. return;
  18944. }
  18945. var sources = parseSsrcs(mLine);
  18946. var order = [];
  18947. // Find the SIM group and explode its sources.
  18948. var j = mLine.ssrcGroups.length;
  18949. while (j--) {
  18950. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  18951. continue;
  18952. }
  18953. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  18954. for (var i = 0; i < simulcastSsrcs.length; i++) {
  18955. var ssrc = simulcastSsrcs[i];
  18956. order.push(ssrc);
  18957. var parts = sources[ssrc].msid.split(' ');
  18958. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  18959. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  18960. // Remove all the groups that this SSRC participates in.
  18961. mLine.ssrcGroups.forEach(function (relatedGroup) {
  18962. if (relatedGroup.semantics === 'SIM') {
  18963. return;
  18964. }
  18965. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  18966. if (relatedSsrcs.indexOf(ssrc) === -1) {
  18967. return;
  18968. }
  18969. // Nuke all the related SSRCs.
  18970. relatedSsrcs.forEach(function (relatedSSRC) {
  18971. sources[relatedSSRC].msid = sources[ssrc].msid;
  18972. sources[relatedSSRC].cname = sources[ssrc].cname;
  18973. if (relatedSSRC !== ssrc) {
  18974. order.push(relatedSSRC);
  18975. }
  18976. });
  18977. // Schedule the related group for nuking.
  18978. })
  18979. }
  18980. mLine.ssrcs = writeSsrcs(sources, order);
  18981. mLine.ssrcGroups.splice(j, 1);
  18982. };
  18983. }
  18984. function implodeRemoteSimulcast(mLine) {
  18985. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  18986. console.debug('Halt: There are no SSRC groups in the remote ' +
  18987. 'description.');
  18988. return;
  18989. }
  18990. var sources = parseSsrcs(mLine);
  18991. // Find the SIM group and nuke it.
  18992. mLine.ssrcGroups.forEach(function (simulcastGroup) {
  18993. if (simulcastGroup.semantics !== 'SIM') {
  18994. return;
  18995. }
  18996. console.debug("Imploding SIM group: " + simulcastGroup.ssrcs);
  18997. // Schedule the SIM group for nuking.
  18998. simulcastGroup.nuke = true;
  18999. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  19000. // Nuke all the higher layer SSRCs.
  19001. for (var i = 1; i < simulcastSsrcs.length; i++) {
  19002. var ssrc = simulcastSsrcs[i];
  19003. delete sources[ssrc];
  19004. // Remove all the groups that this SSRC participates in.
  19005. mLine.ssrcGroups.forEach(function (relatedGroup) {
  19006. if (relatedGroup.semantics === 'SIM') {
  19007. return;
  19008. }
  19009. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  19010. if (relatedSsrcs.indexOf(ssrc) === -1) {
  19011. return;
  19012. }
  19013. // Nuke all the related SSRCs.
  19014. relatedSsrcs.forEach(function (relatedSSRC) {
  19015. delete sources[relatedSSRC];
  19016. });
  19017. // Schedule the related group for nuking.
  19018. relatedGroup.nuke = true;
  19019. })
  19020. }
  19021. return;
  19022. });
  19023. mLine.ssrcs = writeSsrcs(sources);
  19024. // Nuke all the scheduled groups.
  19025. var i = mLine.ssrcGroups.length;
  19026. while (i--) {
  19027. if (mLine.ssrcGroups[i].nuke) {
  19028. mLine.ssrcGroups.splice(i, 1);
  19029. }
  19030. }
  19031. }
  19032. function removeGoogConference(mLine) {
  19033. if (!mLine || !Array.isArray(mLine.invalid)) {
  19034. return;
  19035. }
  19036. var i = mLine.invalid.length;
  19037. while (i--) {
  19038. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  19039. mLine.invalid.splice(i, 1);
  19040. }
  19041. }
  19042. }
  19043. function assertGoogConference(mLine) {
  19044. if (!mLine) {
  19045. return;
  19046. }
  19047. if (!Array.isArray(mLine.invalid)) {
  19048. mLine.invalid = [];
  19049. }
  19050. if (!mLine.invalid.some(
  19051. function (i) { return i.value === 'x-google-flag:conference' })) {
  19052. mLine.invalid.push({'value': 'x-google-flag:conference'});
  19053. }
  19054. }
  19055. //endregion
  19056. //region "Private" functions
  19057. /**
  19058. *
  19059. * @param mLine
  19060. * @private
  19061. */
  19062. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  19063. if (!mLine || mLine.type !== 'video') {
  19064. return;
  19065. }
  19066. var sources = parseSsrcs(mLine);
  19067. if (Object.keys(sources).length === 0) {
  19068. // no sources, disable simulcast.
  19069. if (this.layers.length !== 0) {
  19070. this.layers = [];
  19071. }
  19072. return;
  19073. }
  19074. // find the base layer (we'll reuse its msid and cname).
  19075. var baseLayerSSRC = Object.keys(sources)[0];
  19076. var baseLayer = sources[baseLayerSSRC];
  19077. // todo(gp) handle screen sharing.
  19078. // check if base CNAME has changed and reinitialise layers.
  19079. if (this.layers.length > 0
  19080. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  19081. this.layers = [];
  19082. }
  19083. // (re)initialise layers
  19084. if (this.layers.length < 1) {
  19085. // first push the base layer.
  19086. this.layers.push({
  19087. ssrc: baseLayerSSRC,
  19088. msid: baseLayer.msid,
  19089. cname: baseLayer.cname
  19090. });
  19091. var rtx = false; // RFC 4588
  19092. if (Array.isArray(mLine.rtp)) {
  19093. rtx = mLine.rtp.some(
  19094. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  19095. }
  19096. if (rtx) {
  19097. this.layers[0].rtx = generateSSRC();
  19098. }
  19099. // now push additional layers.
  19100. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  19101. var layer = { ssrc: generateSSRC() };
  19102. if (rtx) {
  19103. layer.rtx = generateSSRC();
  19104. }
  19105. this.layers.push(layer);
  19106. }
  19107. }
  19108. };
  19109. /**
  19110. *
  19111. * @param mLine
  19112. * @private
  19113. */
  19114. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  19115. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  19116. var sources = {};
  19117. var msid = this.layers[0].msid;
  19118. var cname = this.layers[0].cname;
  19119. var simulcastSsrcs = [];
  19120. var ssrcGroups = [];
  19121. for (var i = 0; i < this.layers.length; i++) {
  19122. var layer = this.layers[i];
  19123. sources[layer.ssrc] = { msid: msid, cname: cname };
  19124. simulcastSsrcs.push(layer.ssrc);
  19125. if (layer.rtx) {
  19126. sources[layer.rtx] = {
  19127. msid: msid,
  19128. cname: cname
  19129. }
  19130. ssrcGroups.push({
  19131. semantics: 'FID',
  19132. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  19133. });
  19134. }
  19135. }
  19136. ssrcGroups.push({
  19137. semantics: 'SIM',
  19138. ssrcs: simulcastSsrcs.join(' ')
  19139. });
  19140. mLine.ssrcGroups = ssrcGroups;
  19141. mLine.ssrcs = writeSsrcs(sources);
  19142. }
  19143. }
  19144. //endregion
  19145. //region "Public" functions
  19146. Simulcast.prototype.isSupported = function () {
  19147. return window.chrome;
  19148. // TODO this needs improvements. For example I doubt that Chrome in Android
  19149. // has simulcast support. Also, only recent versions of Chromium have native
  19150. // simulcast support.
  19151. }
  19152. /**
  19153. *
  19154. * @param desc
  19155. * @returns {RTCSessionDescription}
  19156. */
  19157. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  19158. if (!validateDescription(desc)) {
  19159. return desc;
  19160. }
  19161. var session = transform.parse(desc.sdp);
  19162. var self = this;
  19163. processVideo(session, function (mLine) {
  19164. // Handle simulcast reception.
  19165. if (self.options.explodeRemoteSimulcast) {
  19166. explodeRemoteSimulcast(mLine);
  19167. } else {
  19168. implodeRemoteSimulcast(mLine);
  19169. }
  19170. // If native simulcast is enabled, we must append the x-goog-conference
  19171. // attribute to the SDP.
  19172. if (self.layers.length < 1) {
  19173. removeGoogConference(mLine);
  19174. } else {
  19175. assertGoogConference(mLine);
  19176. }
  19177. });
  19178. return new RTCSessionDescription({
  19179. type: desc.type,
  19180. sdp: transform.write(session)
  19181. });
  19182. };
  19183. /**
  19184. *
  19185. * @param desc
  19186. * @returns {RTCSessionDescription}
  19187. */
  19188. Simulcast.prototype.mungeLocalDescription = function (desc) {
  19189. if (!validateDescription(desc) || !this.isSupported()) {
  19190. return desc;
  19191. }
  19192. var session = transform.parse(desc.sdp);
  19193. var self = this;
  19194. processVideo(session, function (mLine) {
  19195. // Initialize native simulcast layers, if not already done.
  19196. self._maybeInitializeLayers(mLine);
  19197. // Update the SDP with the simulcast layers.
  19198. self._restoreSimulcastView(mLine);
  19199. });
  19200. return new RTCSessionDescription({
  19201. type: desc.type,
  19202. sdp: transform.write(session)
  19203. });
  19204. };
  19205. //endregion
  19206. module.exports = Simulcast;
  19207. },{"./transform-utils":69,"sdp-transform":71}],69:[function(require,module,exports){
  19208. /* Copyright @ 2015 Atlassian Pty Ltd
  19209. *
  19210. * Licensed under the Apache License, Version 2.0 (the "License");
  19211. * you may not use this file except in compliance with the License.
  19212. * You may obtain a copy of the License at
  19213. *
  19214. * http://www.apache.org/licenses/LICENSE-2.0
  19215. *
  19216. * Unless required by applicable law or agreed to in writing, software
  19217. * distributed under the License is distributed on an "AS IS" BASIS,
  19218. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19219. * See the License for the specific language governing permissions and
  19220. * limitations under the License.
  19221. */
  19222. exports.writeSsrcs = function(sources, order) {
  19223. var ssrcs = [];
  19224. // expand sources to ssrcs
  19225. if (typeof sources !== 'undefined' &&
  19226. Object.keys(sources).length !== 0) {
  19227. if (Array.isArray(order)) {
  19228. for (var i = 0; i < order.length; i++) {
  19229. var ssrc = order[i];
  19230. var source = sources[ssrc];
  19231. Object.keys(source).forEach(function (attribute) {
  19232. ssrcs.push({
  19233. id: ssrc,
  19234. attribute: attribute,
  19235. value: source[attribute]
  19236. });
  19237. });
  19238. }
  19239. } else {
  19240. Object.keys(sources).forEach(function (ssrc) {
  19241. var source = sources[ssrc];
  19242. Object.keys(source).forEach(function (attribute) {
  19243. ssrcs.push({
  19244. id: ssrc,
  19245. attribute: attribute,
  19246. value: source[attribute]
  19247. });
  19248. });
  19249. });
  19250. }
  19251. }
  19252. return ssrcs;
  19253. };
  19254. exports.parseSsrcs = function (mLine) {
  19255. var sources = {};
  19256. // group sources attributes by ssrc.
  19257. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  19258. mLine.ssrcs.forEach(function (ssrc) {
  19259. if (!sources[ssrc.id])
  19260. sources[ssrc.id] = {};
  19261. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  19262. });
  19263. }
  19264. return sources;
  19265. };
  19266. },{}],70:[function(require,module,exports){
  19267. var grammar = module.exports = {
  19268. v: [{
  19269. name: 'version',
  19270. reg: /^(\d*)$/
  19271. }],
  19272. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  19273. // NB: sessionId will be a String in most cases because it is huge
  19274. name: 'origin',
  19275. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  19276. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  19277. format: "%s %s %d %s IP%d %s"
  19278. }],
  19279. // default parsing of these only (though some of these feel outdated)
  19280. s: [{ name: 'name' }],
  19281. i: [{ name: 'description' }],
  19282. u: [{ name: 'uri' }],
  19283. e: [{ name: 'email' }],
  19284. p: [{ name: 'phone' }],
  19285. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  19286. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  19287. //k: [{}], // outdated thing ignored
  19288. t: [{ //t=0 0
  19289. name: 'timing',
  19290. reg: /^(\d*) (\d*)/,
  19291. names: ['start', 'stop'],
  19292. format: "%d %d"
  19293. }],
  19294. c: [{ //c=IN IP4 10.47.197.26
  19295. name: 'connection',
  19296. reg: /^IN IP(\d) (\S*)/,
  19297. names: ['version', 'ip'],
  19298. format: "IN IP%d %s"
  19299. }],
  19300. b: [{ //b=AS:4000
  19301. push: 'bandwidth',
  19302. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  19303. names: ['type', 'limit'],
  19304. format: "%s:%s"
  19305. }],
  19306. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  19307. // NB: special - pushes to session
  19308. // TODO: rtp/fmtp should be filtered by the payloads found here?
  19309. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  19310. names: ['type', 'port', 'protocol', 'payloads'],
  19311. format: "%s %d %s %s"
  19312. }],
  19313. a: [
  19314. { //a=rtpmap:110 opus/48000/2
  19315. push: 'rtp',
  19316. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  19317. names: ['payload', 'codec', 'rate', 'encoding'],
  19318. format: function (o) {
  19319. return (o.encoding) ?
  19320. "rtpmap:%d %s/%s/%s":
  19321. "rtpmap:%d %s/%s";
  19322. }
  19323. },
  19324. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  19325. push: 'fmtp',
  19326. reg: /^fmtp:(\d*) (\S*)/,
  19327. names: ['payload', 'config'],
  19328. format: "fmtp:%d %s"
  19329. },
  19330. { //a=control:streamid=0
  19331. name: 'control',
  19332. reg: /^control:(.*)/,
  19333. format: "control:%s"
  19334. },
  19335. { //a=rtcp:65179 IN IP4 193.84.77.194
  19336. name: 'rtcp',
  19337. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  19338. names: ['port', 'netType', 'ipVer', 'address'],
  19339. format: function (o) {
  19340. return (o.address != null) ?
  19341. "rtcp:%d %s IP%d %s":
  19342. "rtcp:%d";
  19343. }
  19344. },
  19345. { //a=rtcp-fb:98 trr-int 100
  19346. push: 'rtcpFbTrrInt',
  19347. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  19348. names: ['payload', 'value'],
  19349. format: "rtcp-fb:%d trr-int %d"
  19350. },
  19351. { //a=rtcp-fb:98 nack rpsi
  19352. push: 'rtcpFb',
  19353. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  19354. names: ['payload', 'type', 'subtype'],
  19355. format: function (o) {
  19356. return (o.subtype != null) ?
  19357. "rtcp-fb:%s %s %s":
  19358. "rtcp-fb:%s %s";
  19359. }
  19360. },
  19361. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  19362. //a=extmap:1/recvonly URI-gps-string
  19363. push: 'ext',
  19364. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  19365. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  19366. format: function (o) {
  19367. return (o.config != null) ?
  19368. "extmap:%s %s %s":
  19369. "extmap:%s %s";
  19370. }
  19371. },
  19372. {
  19373. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  19374. push: 'crypto',
  19375. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  19376. names: ['id', 'suite', 'config', 'sessionConfig'],
  19377. format: function (o) {
  19378. return (o.sessionConfig != null) ?
  19379. "crypto:%d %s %s %s":
  19380. "crypto:%d %s %s";
  19381. }
  19382. },
  19383. { //a=setup:actpass
  19384. name: 'setup',
  19385. reg: /^setup:(\w*)/,
  19386. format: "setup:%s"
  19387. },
  19388. { //a=mid:1
  19389. name: 'mid',
  19390. reg: /^mid:([^\s]*)/,
  19391. format: "mid:%s"
  19392. },
  19393. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  19394. name: 'msid',
  19395. reg: /^msid:(.*)/,
  19396. format: "msid:%s"
  19397. },
  19398. { //a=ptime:20
  19399. name: 'ptime',
  19400. reg: /^ptime:(\d*)/,
  19401. format: "ptime:%d"
  19402. },
  19403. { //a=maxptime:60
  19404. name: 'maxptime',
  19405. reg: /^maxptime:(\d*)/,
  19406. format: "maxptime:%d"
  19407. },
  19408. { //a=sendrecv
  19409. name: 'direction',
  19410. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  19411. },
  19412. { //a=ice-lite
  19413. name: 'icelite',
  19414. reg: /^(ice-lite)/
  19415. },
  19416. { //a=ice-ufrag:F7gI
  19417. name: 'iceUfrag',
  19418. reg: /^ice-ufrag:(\S*)/,
  19419. format: "ice-ufrag:%s"
  19420. },
  19421. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  19422. name: 'icePwd',
  19423. reg: /^ice-pwd:(\S*)/,
  19424. format: "ice-pwd:%s"
  19425. },
  19426. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  19427. name: 'fingerprint',
  19428. reg: /^fingerprint:(\S*) (\S*)/,
  19429. names: ['type', 'hash'],
  19430. format: "fingerprint:%s %s"
  19431. },
  19432. {
  19433. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  19434. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  19435. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  19436. push:'candidates',
  19437. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  19438. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  19439. format: function (o) {
  19440. var str = "candidate:%s %d %s %d %s %d typ %s";
  19441. // NB: candidate has two optional chunks, so %void middle one if it's missing
  19442. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  19443. if (o.generation != null) {
  19444. str += " generation %d";
  19445. }
  19446. return str;
  19447. }
  19448. },
  19449. { //a=end-of-candidates (keep after the candidates line for readability)
  19450. name: 'endOfCandidates',
  19451. reg: /^(end-of-candidates)/
  19452. },
  19453. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  19454. name: 'remoteCandidates',
  19455. reg: /^remote-candidates:(.*)/,
  19456. format: "remote-candidates:%s"
  19457. },
  19458. { //a=ice-options:google-ice
  19459. name: 'iceOptions',
  19460. reg: /^ice-options:(\S*)/,
  19461. format: "ice-options:%s"
  19462. },
  19463. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  19464. push: "ssrcs",
  19465. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  19466. names: ['id', 'attribute', 'value'],
  19467. format: "ssrc:%d %s:%s"
  19468. },
  19469. { //a=ssrc-group:FEC 1 2
  19470. push: "ssrcGroups",
  19471. reg: /^ssrc-group:(\w*) (.*)/,
  19472. names: ['semantics', 'ssrcs'],
  19473. format: "ssrc-group:%s %s"
  19474. },
  19475. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  19476. name: "msidSemantic",
  19477. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  19478. names: ['semantic', 'token'],
  19479. format: "msid-semantic: %s %s" // space after ":" is not accidental
  19480. },
  19481. { //a=group:BUNDLE audio video
  19482. push: 'groups',
  19483. reg: /^group:(\w*) (.*)/,
  19484. names: ['type', 'mids'],
  19485. format: "group:%s %s"
  19486. },
  19487. { //a=rtcp-mux
  19488. name: 'rtcpMux',
  19489. reg: /^(rtcp-mux)/
  19490. },
  19491. { //a=rtcp-rsize
  19492. name: 'rtcpRsize',
  19493. reg: /^(rtcp-rsize)/
  19494. },
  19495. { // any a= that we don't understand is kepts verbatim on media.invalid
  19496. push: 'invalid',
  19497. names: ["value"]
  19498. }
  19499. ]
  19500. };
  19501. // set sensible defaults to avoid polluting the grammar with boring details
  19502. Object.keys(grammar).forEach(function (key) {
  19503. var objs = grammar[key];
  19504. objs.forEach(function (obj) {
  19505. if (!obj.reg) {
  19506. obj.reg = /(.*)/;
  19507. }
  19508. if (!obj.format) {
  19509. obj.format = "%s";
  19510. }
  19511. });
  19512. });
  19513. },{}],71:[function(require,module,exports){
  19514. var parser = require('./parser');
  19515. var writer = require('./writer');
  19516. exports.write = writer;
  19517. exports.parse = parser.parse;
  19518. exports.parseFmtpConfig = parser.parseFmtpConfig;
  19519. exports.parsePayloads = parser.parsePayloads;
  19520. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  19521. },{"./parser":72,"./writer":73}],72:[function(require,module,exports){
  19522. var toIntIfInt = function (v) {
  19523. return String(Number(v)) === v ? Number(v) : v;
  19524. };
  19525. var attachProperties = function (match, location, names, rawName) {
  19526. if (rawName && !names) {
  19527. location[rawName] = toIntIfInt(match[1]);
  19528. }
  19529. else {
  19530. for (var i = 0; i < names.length; i += 1) {
  19531. if (match[i+1] != null) {
  19532. location[names[i]] = toIntIfInt(match[i+1]);
  19533. }
  19534. }
  19535. }
  19536. };
  19537. var parseReg = function (obj, location, content) {
  19538. var needsBlank = obj.name && obj.names;
  19539. if (obj.push && !location[obj.push]) {
  19540. location[obj.push] = [];
  19541. }
  19542. else if (needsBlank && !location[obj.name]) {
  19543. location[obj.name] = {};
  19544. }
  19545. var keyLocation = obj.push ?
  19546. {} : // blank object that will be pushed
  19547. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  19548. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  19549. if (obj.push) {
  19550. location[obj.push].push(keyLocation);
  19551. }
  19552. };
  19553. var grammar = require('./grammar');
  19554. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  19555. exports.parse = function (sdp) {
  19556. var session = {}
  19557. , media = []
  19558. , location = session; // points at where properties go under (one of the above)
  19559. // parse lines we understand
  19560. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  19561. var type = l[0];
  19562. var content = l.slice(2);
  19563. if (type === 'm') {
  19564. media.push({rtp: [], fmtp: []});
  19565. location = media[media.length-1]; // point at latest media line
  19566. }
  19567. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  19568. var obj = grammar[type][j];
  19569. if (obj.reg.test(content)) {
  19570. return parseReg(obj, location, content);
  19571. }
  19572. }
  19573. });
  19574. session.media = media; // link it up
  19575. return session;
  19576. };
  19577. var fmtpReducer = function (acc, expr) {
  19578. var s = expr.split('=');
  19579. if (s.length === 2) {
  19580. acc[s[0]] = toIntIfInt(s[1]);
  19581. }
  19582. return acc;
  19583. };
  19584. exports.parseFmtpConfig = function (str) {
  19585. return str.split(';').reduce(fmtpReducer, {});
  19586. };
  19587. exports.parsePayloads = function (str) {
  19588. return str.split(' ').map(Number);
  19589. };
  19590. exports.parseRemoteCandidates = function (str) {
  19591. var candidates = [];
  19592. var parts = str.split(' ').map(toIntIfInt);
  19593. for (var i = 0; i < parts.length; i += 3) {
  19594. candidates.push({
  19595. component: parts[i],
  19596. ip: parts[i + 1],
  19597. port: parts[i + 2]
  19598. });
  19599. }
  19600. return candidates;
  19601. };
  19602. },{"./grammar":70}],73:[function(require,module,exports){
  19603. var grammar = require('./grammar');
  19604. // customized util.format - discards excess arguments and can void middle ones
  19605. var formatRegExp = /%[sdv%]/g;
  19606. var format = function (formatStr) {
  19607. var i = 1;
  19608. var args = arguments;
  19609. var len = args.length;
  19610. return formatStr.replace(formatRegExp, function (x) {
  19611. if (i >= len) {
  19612. return x; // missing argument
  19613. }
  19614. var arg = args[i];
  19615. i += 1;
  19616. switch (x) {
  19617. case '%%':
  19618. return '%';
  19619. case '%s':
  19620. return String(arg);
  19621. case '%d':
  19622. return Number(arg);
  19623. case '%v':
  19624. return '';
  19625. }
  19626. });
  19627. // NB: we discard excess arguments - they are typically undefined from makeLine
  19628. };
  19629. var makeLine = function (type, obj, location) {
  19630. var str = obj.format instanceof Function ?
  19631. (obj.format(obj.push ? location : location[obj.name])) :
  19632. obj.format;
  19633. var args = [type + '=' + str];
  19634. if (obj.names) {
  19635. for (var i = 0; i < obj.names.length; i += 1) {
  19636. var n = obj.names[i];
  19637. if (obj.name) {
  19638. args.push(location[obj.name][n]);
  19639. }
  19640. else { // for mLine and push attributes
  19641. args.push(location[obj.names[i]]);
  19642. }
  19643. }
  19644. }
  19645. else {
  19646. args.push(location[obj.name]);
  19647. }
  19648. return format.apply(null, args);
  19649. };
  19650. // RFC specified order
  19651. // TODO: extend this with all the rest
  19652. var defaultOuterOrder = [
  19653. 'v', 'o', 's', 'i',
  19654. 'u', 'e', 'p', 'c',
  19655. 'b', 't', 'r', 'z', 'a'
  19656. ];
  19657. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  19658. module.exports = function (session, opts) {
  19659. opts = opts || {};
  19660. // ensure certain properties exist
  19661. if (session.version == null) {
  19662. session.version = 0; // "v=0" must be there (only defined version atm)
  19663. }
  19664. if (session.name == null) {
  19665. session.name = " "; // "s= " must be there if no meaningful name set
  19666. }
  19667. session.media.forEach(function (mLine) {
  19668. if (mLine.payloads == null) {
  19669. mLine.payloads = "";
  19670. }
  19671. });
  19672. var outerOrder = opts.outerOrder || defaultOuterOrder;
  19673. var innerOrder = opts.innerOrder || defaultInnerOrder;
  19674. var sdp = [];
  19675. // loop through outerOrder for matching properties on session
  19676. outerOrder.forEach(function (type) {
  19677. grammar[type].forEach(function (obj) {
  19678. if (obj.name in session && session[obj.name] != null) {
  19679. sdp.push(makeLine(type, obj, session));
  19680. }
  19681. else if (obj.push in session && session[obj.push] != null) {
  19682. session[obj.push].forEach(function (el) {
  19683. sdp.push(makeLine(type, obj, el));
  19684. });
  19685. }
  19686. });
  19687. });
  19688. // then for each media line, follow the innerOrder
  19689. session.media.forEach(function (mLine) {
  19690. sdp.push(makeLine('m', grammar.m[0], mLine));
  19691. innerOrder.forEach(function (type) {
  19692. grammar[type].forEach(function (obj) {
  19693. if (obj.name in mLine && mLine[obj.name] != null) {
  19694. sdp.push(makeLine(type, obj, mLine));
  19695. }
  19696. else if (obj.push in mLine && mLine[obj.push] != null) {
  19697. mLine[obj.push].forEach(function (el) {
  19698. sdp.push(makeLine(type, obj, el));
  19699. });
  19700. }
  19701. });
  19702. });
  19703. });
  19704. return sdp.join('\r\n') + '\r\n';
  19705. };
  19706. },{"./grammar":70}],74:[function(require,module,exports){
  19707. var grammar = module.exports = {
  19708. v: [{
  19709. name: 'version',
  19710. reg: /^(\d*)$/
  19711. }],
  19712. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  19713. // NB: sessionId will be a String in most cases because it is huge
  19714. name: 'origin',
  19715. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  19716. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  19717. format: "%s %s %d %s IP%d %s"
  19718. }],
  19719. // default parsing of these only (though some of these feel outdated)
  19720. s: [{ name: 'name' }],
  19721. i: [{ name: 'description' }],
  19722. u: [{ name: 'uri' }],
  19723. e: [{ name: 'email' }],
  19724. p: [{ name: 'phone' }],
  19725. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  19726. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  19727. //k: [{}], // outdated thing ignored
  19728. t: [{ //t=0 0
  19729. name: 'timing',
  19730. reg: /^(\d*) (\d*)/,
  19731. names: ['start', 'stop'],
  19732. format: "%d %d"
  19733. }],
  19734. c: [{ //c=IN IP4 10.47.197.26
  19735. name: 'connection',
  19736. reg: /^IN IP(\d) (\S*)/,
  19737. names: ['version', 'ip'],
  19738. format: "IN IP%d %s"
  19739. }],
  19740. b: [{ //b=AS:4000
  19741. push: 'bandwidth',
  19742. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  19743. names: ['type', 'limit'],
  19744. format: "%s:%s"
  19745. }],
  19746. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  19747. // NB: special - pushes to session
  19748. // TODO: rtp/fmtp should be filtered by the payloads found here?
  19749. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  19750. names: ['type', 'port', 'protocol', 'payloads'],
  19751. format: "%s %d %s %s"
  19752. }],
  19753. a: [
  19754. { //a=rtpmap:110 opus/48000/2
  19755. push: 'rtp',
  19756. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  19757. names: ['payload', 'codec', 'rate', 'encoding'],
  19758. format: function (o) {
  19759. return (o.encoding) ?
  19760. "rtpmap:%d %s/%s/%s":
  19761. "rtpmap:%d %s/%s";
  19762. }
  19763. },
  19764. {
  19765. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  19766. //a=fmtp:111 minptime=10; useinbandfec=1
  19767. push: 'fmtp',
  19768. reg: /^fmtp:(\d*) ([\S| ]*)/,
  19769. names: ['payload', 'config'],
  19770. format: "fmtp:%d %s"
  19771. },
  19772. { //a=control:streamid=0
  19773. name: 'control',
  19774. reg: /^control:(.*)/,
  19775. format: "control:%s"
  19776. },
  19777. { //a=rtcp:65179 IN IP4 193.84.77.194
  19778. name: 'rtcp',
  19779. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  19780. names: ['port', 'netType', 'ipVer', 'address'],
  19781. format: function (o) {
  19782. return (o.address != null) ?
  19783. "rtcp:%d %s IP%d %s":
  19784. "rtcp:%d";
  19785. }
  19786. },
  19787. { //a=rtcp-fb:98 trr-int 100
  19788. push: 'rtcpFbTrrInt',
  19789. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  19790. names: ['payload', 'value'],
  19791. format: "rtcp-fb:%d trr-int %d"
  19792. },
  19793. { //a=rtcp-fb:98 nack rpsi
  19794. push: 'rtcpFb',
  19795. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  19796. names: ['payload', 'type', 'subtype'],
  19797. format: function (o) {
  19798. return (o.subtype != null) ?
  19799. "rtcp-fb:%s %s %s":
  19800. "rtcp-fb:%s %s";
  19801. }
  19802. },
  19803. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  19804. //a=extmap:1/recvonly URI-gps-string
  19805. push: 'ext',
  19806. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  19807. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  19808. format: function (o) {
  19809. return (o.config != null) ?
  19810. "extmap:%s %s %s":
  19811. "extmap:%s %s";
  19812. }
  19813. },
  19814. {
  19815. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  19816. push: 'crypto',
  19817. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  19818. names: ['id', 'suite', 'config', 'sessionConfig'],
  19819. format: function (o) {
  19820. return (o.sessionConfig != null) ?
  19821. "crypto:%d %s %s %s":
  19822. "crypto:%d %s %s";
  19823. }
  19824. },
  19825. { //a=setup:actpass
  19826. name: 'setup',
  19827. reg: /^setup:(\w*)/,
  19828. format: "setup:%s"
  19829. },
  19830. { //a=mid:1
  19831. name: 'mid',
  19832. reg: /^mid:([^\s]*)/,
  19833. format: "mid:%s"
  19834. },
  19835. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  19836. name: 'msid',
  19837. reg: /^msid:(.*)/,
  19838. format: "msid:%s"
  19839. },
  19840. { //a=ptime:20
  19841. name: 'ptime',
  19842. reg: /^ptime:(\d*)/,
  19843. format: "ptime:%d"
  19844. },
  19845. { //a=maxptime:60
  19846. name: 'maxptime',
  19847. reg: /^maxptime:(\d*)/,
  19848. format: "maxptime:%d"
  19849. },
  19850. { //a=sendrecv
  19851. name: 'direction',
  19852. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  19853. },
  19854. { //a=ice-lite
  19855. name: 'icelite',
  19856. reg: /^(ice-lite)/
  19857. },
  19858. { //a=ice-ufrag:F7gI
  19859. name: 'iceUfrag',
  19860. reg: /^ice-ufrag:(\S*)/,
  19861. format: "ice-ufrag:%s"
  19862. },
  19863. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  19864. name: 'icePwd',
  19865. reg: /^ice-pwd:(\S*)/,
  19866. format: "ice-pwd:%s"
  19867. },
  19868. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  19869. name: 'fingerprint',
  19870. reg: /^fingerprint:(\S*) (\S*)/,
  19871. names: ['type', 'hash'],
  19872. format: "fingerprint:%s %s"
  19873. },
  19874. {
  19875. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  19876. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  19877. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  19878. push:'candidates',
  19879. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  19880. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  19881. format: function (o) {
  19882. var str = "candidate:%s %d %s %d %s %d typ %s";
  19883. // NB: candidate has two optional chunks, so %void middle one if it's missing
  19884. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  19885. if (o.generation != null) {
  19886. str += " generation %d";
  19887. }
  19888. return str;
  19889. }
  19890. },
  19891. { //a=end-of-candidates (keep after the candidates line for readability)
  19892. name: 'endOfCandidates',
  19893. reg: /^(end-of-candidates)/
  19894. },
  19895. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  19896. name: 'remoteCandidates',
  19897. reg: /^remote-candidates:(.*)/,
  19898. format: "remote-candidates:%s"
  19899. },
  19900. { //a=ice-options:google-ice
  19901. name: 'iceOptions',
  19902. reg: /^ice-options:(\S*)/,
  19903. format: "ice-options:%s"
  19904. },
  19905. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  19906. push: "ssrcs",
  19907. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  19908. names: ['id', 'attribute', 'value'],
  19909. format: "ssrc:%d %s:%s"
  19910. },
  19911. { //a=ssrc-group:FEC 1 2
  19912. push: "ssrcGroups",
  19913. reg: /^ssrc-group:(\w*) (.*)/,
  19914. names: ['semantics', 'ssrcs'],
  19915. format: "ssrc-group:%s %s"
  19916. },
  19917. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  19918. name: "msidSemantic",
  19919. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  19920. names: ['semantic', 'token'],
  19921. format: "msid-semantic: %s %s" // space after ":" is not accidental
  19922. },
  19923. { //a=group:BUNDLE audio video
  19924. push: 'groups',
  19925. reg: /^group:(\w*) (.*)/,
  19926. names: ['type', 'mids'],
  19927. format: "group:%s %s"
  19928. },
  19929. { //a=rtcp-mux
  19930. name: 'rtcpMux',
  19931. reg: /^(rtcp-mux)/
  19932. },
  19933. { //a=rtcp-rsize
  19934. name: 'rtcpRsize',
  19935. reg: /^(rtcp-rsize)/
  19936. },
  19937. { // any a= that we don't understand is kepts verbatim on media.invalid
  19938. push: 'invalid',
  19939. names: ["value"]
  19940. }
  19941. ]
  19942. };
  19943. // set sensible defaults to avoid polluting the grammar with boring details
  19944. Object.keys(grammar).forEach(function (key) {
  19945. var objs = grammar[key];
  19946. objs.forEach(function (obj) {
  19947. if (!obj.reg) {
  19948. obj.reg = /(.*)/;
  19949. }
  19950. if (!obj.format) {
  19951. obj.format = "%s";
  19952. }
  19953. });
  19954. });
  19955. },{}],75:[function(require,module,exports){
  19956. arguments[4][71][0].apply(exports,arguments)
  19957. },{"./parser":76,"./writer":77,"dup":71}],76:[function(require,module,exports){
  19958. var toIntIfInt = function (v) {
  19959. return String(Number(v)) === v ? Number(v) : v;
  19960. };
  19961. var attachProperties = function (match, location, names, rawName) {
  19962. if (rawName && !names) {
  19963. location[rawName] = toIntIfInt(match[1]);
  19964. }
  19965. else {
  19966. for (var i = 0; i < names.length; i += 1) {
  19967. if (match[i+1] != null) {
  19968. location[names[i]] = toIntIfInt(match[i+1]);
  19969. }
  19970. }
  19971. }
  19972. };
  19973. var parseReg = function (obj, location, content) {
  19974. var needsBlank = obj.name && obj.names;
  19975. if (obj.push && !location[obj.push]) {
  19976. location[obj.push] = [];
  19977. }
  19978. else if (needsBlank && !location[obj.name]) {
  19979. location[obj.name] = {};
  19980. }
  19981. var keyLocation = obj.push ?
  19982. {} : // blank object that will be pushed
  19983. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  19984. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  19985. if (obj.push) {
  19986. location[obj.push].push(keyLocation);
  19987. }
  19988. };
  19989. var grammar = require('./grammar');
  19990. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  19991. exports.parse = function (sdp) {
  19992. var session = {}
  19993. , media = []
  19994. , location = session; // points at where properties go under (one of the above)
  19995. // parse lines we understand
  19996. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  19997. var type = l[0];
  19998. var content = l.slice(2);
  19999. if (type === 'm') {
  20000. media.push({rtp: [], fmtp: []});
  20001. location = media[media.length-1]; // point at latest media line
  20002. }
  20003. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  20004. var obj = grammar[type][j];
  20005. if (obj.reg.test(content)) {
  20006. return parseReg(obj, location, content);
  20007. }
  20008. }
  20009. });
  20010. session.media = media; // link it up
  20011. return session;
  20012. };
  20013. var fmtpReducer = function (acc, expr) {
  20014. var s = expr.split('=');
  20015. if (s.length === 2) {
  20016. acc[s[0]] = toIntIfInt(s[1]);
  20017. }
  20018. return acc;
  20019. };
  20020. exports.parseFmtpConfig = function (str) {
  20021. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  20022. };
  20023. exports.parsePayloads = function (str) {
  20024. return str.split(' ').map(Number);
  20025. };
  20026. exports.parseRemoteCandidates = function (str) {
  20027. var candidates = [];
  20028. var parts = str.split(' ').map(toIntIfInt);
  20029. for (var i = 0; i < parts.length; i += 3) {
  20030. candidates.push({
  20031. component: parts[i],
  20032. ip: parts[i + 1],
  20033. port: parts[i + 2]
  20034. });
  20035. }
  20036. return candidates;
  20037. };
  20038. },{"./grammar":74}],77:[function(require,module,exports){
  20039. arguments[4][73][0].apply(exports,arguments)
  20040. },{"./grammar":74,"dup":73}],78:[function(require,module,exports){
  20041. var MediaStreamType = {
  20042. VIDEO_TYPE: "Video",
  20043. AUDIO_TYPE: "Audio"
  20044. };
  20045. module.exports = MediaStreamType;
  20046. },{}],79:[function(require,module,exports){
  20047. var RTCEvents = {
  20048. RTC_READY: "rtc.ready",
  20049. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  20050. LASTN_CHANGED: "rtc.lastn_changed",
  20051. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  20052. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  20053. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  20054. };
  20055. module.exports = RTCEvents;
  20056. },{}],80:[function(require,module,exports){
  20057. var Resolutions = {
  20058. "1080": {
  20059. width: 1920,
  20060. height: 1080,
  20061. order: 7
  20062. },
  20063. "fullhd": {
  20064. width: 1920,
  20065. height: 1080,
  20066. order: 7
  20067. },
  20068. "720": {
  20069. width: 1280,
  20070. height: 720,
  20071. order: 6
  20072. },
  20073. "hd": {
  20074. width: 1280,
  20075. height: 720,
  20076. order: 6
  20077. },
  20078. "960": {
  20079. width: 960,
  20080. height: 720,
  20081. order: 5
  20082. },
  20083. "640": {
  20084. width: 640,
  20085. height: 480,
  20086. order: 4
  20087. },
  20088. "vga": {
  20089. width: 640,
  20090. height: 480,
  20091. order: 4
  20092. },
  20093. "360": {
  20094. width: 640,
  20095. height: 360,
  20096. order: 3
  20097. },
  20098. "320": {
  20099. width: 320,
  20100. height: 240,
  20101. order: 2
  20102. },
  20103. "180": {
  20104. width: 320,
  20105. height: 180,
  20106. order: 1
  20107. }
  20108. };
  20109. module.exports = Resolutions;
  20110. },{}],81:[function(require,module,exports){
  20111. var StreamEventTypes = {
  20112. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  20113. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  20114. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  20115. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  20116. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  20117. TRACK_MUTE_CHANGED: "rtc.track_mute_changed"
  20118. };
  20119. module.exports = StreamEventTypes;
  20120. },{}],82:[function(require,module,exports){
  20121. var AuthenticationEvents = {
  20122. /**
  20123. * Event callback arguments:
  20124. * function(authenticationEnabled, userIdentity)
  20125. * authenticationEnabled - indicates whether authentication has been enabled
  20126. * in this session
  20127. * userIdentity - if user has been logged in then it contains user name. If
  20128. * contains 'null' or 'undefined' then user is not logged in.
  20129. */
  20130. IDENTITY_UPDATED: "authentication.identity_updated"
  20131. };
  20132. module.exports = AuthenticationEvents;
  20133. },{}],83:[function(require,module,exports){
  20134. var DesktopSharingEventTypes = {
  20135. INIT: "ds.init",
  20136. SWITCHING_DONE: "ds.switching_done",
  20137. NEW_STREAM_CREATED: "ds.new_stream_created",
  20138. /**
  20139. * An event which indicates that the jidesha extension for Firefox is
  20140. * needed to proceed with screen sharing, and that it is not installed.
  20141. */
  20142. FIREFOX_EXTENSION_NEEDED: "ds.firefox_extension_needed"
  20143. };
  20144. module.exports = DesktopSharingEventTypes;
  20145. },{}],84:[function(require,module,exports){
  20146. module.exports = {
  20147. /**
  20148. * An event carrying connection statistics.
  20149. */
  20150. CONNECTION_STATS: "statistics.connectionstats",
  20151. /**
  20152. * FIXME: needs documentation.
  20153. */
  20154. AUDIO_LEVEL: "statistics.audioLevel",
  20155. /**
  20156. * FIXME: needs documentation.
  20157. */
  20158. STOP: "statistics.stop"
  20159. };
  20160. },{}],85:[function(require,module,exports){
  20161. var Constants = {
  20162. LOCAL_JID: 'local'
  20163. };
  20164. module.exports = Constants;
  20165. },{}],86:[function(require,module,exports){
  20166. var XMPPEvents = {
  20167. // Designates an event indicating that the connection to the XMPP server
  20168. // failed.
  20169. CONNECTION_FAILED: "xmpp.connection.failed",
  20170. // Designates an event indicating that the media (ICE) connection was
  20171. // interrupted. This should go to the RTC module.
  20172. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  20173. // Designates an event indicating that the media (ICE) connection was
  20174. // restored. This should go to the RTC module.
  20175. CONNECTION_RESTORED: "xmpp.connection.restored",
  20176. // Designates an event indicating that an offer (e.g. Jingle
  20177. // session-initiate) was received.
  20178. CALL_INCOMING: "xmpp.callincoming.jingle",
  20179. // Designates an event indicating that we were kicked from the XMPP MUC.
  20180. KICKED: "xmpp.kicked",
  20181. // Designates an event indicating that the userID for a specific JID has
  20182. // changed.
  20183. // Note: currently this event fires every time we receive presence from
  20184. // someone (regardless of whether or not the "userID" changed).
  20185. USER_ID_CHANGED: "xmpp.user_id_changed",
  20186. // Designates an event indicating that we have joined the XMPP MUC.
  20187. MUC_JOINED: "xmpp.muc_joined",
  20188. // Designates an event indicating that a participant joined the XMPP MUC.
  20189. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  20190. // Designates an event indicating that a participant left the XMPP MUC.
  20191. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  20192. // Designates an event indicating that the MUC role of a participant has
  20193. // changed.
  20194. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  20195. // Designates an event indicating that the XMPP MUC was destroyed.
  20196. MUC_DESTROYED: "xmpp.muc_destroyed",
  20197. // Designates an event indicating that the display name of a participant
  20198. // has changed.
  20199. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  20200. // Designates an event indicating that we received statistics from a
  20201. // participant in the MUC.
  20202. REMOTE_STATS: "xmpp.remote_stats",
  20203. // Designates an event indicating that our role in the XMPP MUC has changed.
  20204. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  20205. // Designates an event indicating that the subject of the XMPP MUC has
  20206. // changed.
  20207. SUBJECT_CHANGED: "xmpp.subject_changed",
  20208. // Designates an event indicating that an XMPP message in the MUC was
  20209. // received.
  20210. MESSAGE_RECEIVED: "xmpp.message_received",
  20211. // Designates an event indicating that we sent an XMPP message to the MUC.
  20212. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  20213. // Designates an event indicating that the video type (e.g. 'camera' or
  20214. // 'screen') for a participant has changed.
  20215. // Note: currently this event fires every time we receive presence from
  20216. // someone (regardless of whether or not the "video type" changed).
  20217. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  20218. // Designates an event indicating that a participant in the XMPP MUC has
  20219. // advertised that they have audio muted (or unmuted).
  20220. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  20221. // Designates an event indicating that a participant in the XMPP MUC has
  20222. // advertised that they have video muted (or unmuted).
  20223. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  20224. // Designates an event indicating that the focus has asked us to mute our
  20225. // audio.
  20226. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  20227. // Designates an event indicating that a moderator in the room changed the
  20228. // "start muted" settings for the conference.
  20229. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  20230. // Designates an event indicating that we should join the conference with
  20231. // audio and/or video muted.
  20232. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  20233. // Designates an event indicating that a remote participant's available
  20234. // devices (whether he supports a audio and/or video) changed.
  20235. // Note: currently this event fires every time we receive presence from
  20236. // someone (regardless of whether or not the devices changed).
  20237. DEVICE_AVAILABLE: "xmpp.device_available",
  20238. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  20239. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  20240. PASSWORD_REQUIRED: "xmpp.password_required",
  20241. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  20242. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  20243. ETHERPAD: "xmpp.etherpad",
  20244. BRIDGE_DOWN: "xmpp.bridge_down",
  20245. PRESENCE_STATUS: "xmpp.presence_status",
  20246. RESERVATION_ERROR: "xmpp.room_reservation_error",
  20247. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  20248. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  20249. // TODO: only used in a hack, should probably be removed.
  20250. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  20251. // TODO: only used in a hack, should probably be removed.
  20252. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  20253. // TODO: only used in a hack, should probably be removed.
  20254. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  20255. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  20256. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  20257. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  20258. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  20259. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  20260. // xmpp is connected and obtained user media
  20261. READY_TO_JOIN: 'xmpp.ready_to_join',
  20262. FOCUS_LEFT: "xmpp.focus_left",
  20263. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received"
  20264. };
  20265. module.exports = XMPPEvents;
  20266. },{}]},{},[7])(7)
  20267. });