You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

lib-jitsi-meet.js 769KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695
  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, $, Promise */
  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 AuthenticationEvents = require("./service/authentication/AuthenticationEvents");
  9. var RTCEvents = require("./service/RTC/RTCEvents");
  10. var EventEmitter = require("events");
  11. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  12. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  13. var JitsiParticipant = require("./JitsiParticipant");
  14. var Statistics = require("./modules/statistics/statistics");
  15. var JitsiDTMFManager = require('./modules/DTMF/JitsiDTMFManager');
  16. var JitsiTrackEvents = require("./JitsiTrackEvents");
  17. /**
  18. * Creates a JitsiConference object with the given name and properties.
  19. * Note: this constructor is not a part of the public API (objects should be
  20. * created using JitsiConnection.createConference).
  21. * @param options.config properties / settings related to the conference that will be created.
  22. * @param options.name the name of the conference
  23. * @param options.connection the JitsiConnection object for this JitsiConference.
  24. * @constructor
  25. */
  26. function JitsiConference(options) {
  27. if(!options.name || options.name.toLowerCase() !== options.name) {
  28. logger.error("Invalid conference name (no conference name passed or it"
  29. + "contains invalid characters like capital letters)!");
  30. return;
  31. }
  32. this.options = options;
  33. this.connection = this.options.connection;
  34. this.xmpp = this.connection.xmpp;
  35. this.eventEmitter = new EventEmitter();
  36. this.room = this.xmpp.createRoom(this.options.name, this.options.config);
  37. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  38. this.rtc = new RTC(this.room, options);
  39. if(!RTC.options.disableAudioLevels)
  40. this.statistics = new Statistics();
  41. setupListeners(this);
  42. this.participants = {};
  43. this.lastActiveSpeaker = null;
  44. this.dtmfManager = null;
  45. this.somebodySupportsDTMF = false;
  46. this.authEnabled = false;
  47. this.authIdentity;
  48. }
  49. /**
  50. * Joins the conference.
  51. * @param password {string} the password
  52. */
  53. JitsiConference.prototype.join = function (password) {
  54. if(this.room)
  55. this.room.join(password);
  56. };
  57. /**
  58. * Check if joined to the conference.
  59. */
  60. JitsiConference.prototype.isJoined = function () {
  61. return this.room && this.room.joined;
  62. };
  63. /**
  64. * Leaves the conference.
  65. */
  66. JitsiConference.prototype.leave = function () {
  67. if(this.xmpp && this.room)
  68. this.xmpp.leaveRoom(this.room.roomjid);
  69. this.room = null;
  70. };
  71. /**
  72. * Returns name of this conference.
  73. */
  74. JitsiConference.prototype.getName = function () {
  75. return this.options.name;
  76. };
  77. /**
  78. * Check if authentication is enabled for this conference.
  79. */
  80. JitsiConference.prototype.isAuthEnabled = function () {
  81. return this.authEnabled;
  82. };
  83. /**
  84. * Check if user is logged in.
  85. */
  86. JitsiConference.prototype.isLoggedIn = function () {
  87. return !!this.authIdentity;
  88. };
  89. /**
  90. * Get authorized login.
  91. */
  92. JitsiConference.prototype.getAuthLogin = function () {
  93. return this.authIdentity;
  94. };
  95. /**
  96. * Check if external authentication is enabled for this conference.
  97. */
  98. JitsiConference.prototype.isExternalAuthEnabled = function () {
  99. return this.room && this.room.moderator.isExternalAuthEnabled();
  100. };
  101. /**
  102. * Get url for external authentication.
  103. * @param {boolean} [urlForPopup] if true then return url for login popup,
  104. * else url of login page.
  105. * @returns {Promise}
  106. */
  107. JitsiConference.prototype.getExternalAuthUrl = function (urlForPopup) {
  108. return new Promise(function (resolve, reject) {
  109. if (!this.isExternalAuthEnabled()) {
  110. reject();
  111. return;
  112. }
  113. if (urlForPopup) {
  114. this.room.moderator.getPopupLoginUrl(resolve, reject);
  115. } else {
  116. this.room.moderator.getLoginUrl(resolve, reject);
  117. }
  118. }.bind(this));
  119. };
  120. /**
  121. * Returns the local tracks.
  122. */
  123. JitsiConference.prototype.getLocalTracks = function () {
  124. if (this.rtc) {
  125. return this.rtc.localStreams;
  126. } else {
  127. return [];
  128. }
  129. };
  130. /**
  131. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  132. * in JitsiConferenceEvents.
  133. * @param eventId the event ID.
  134. * @param handler handler for the event.
  135. *
  136. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  137. */
  138. JitsiConference.prototype.on = function (eventId, handler) {
  139. if(this.eventEmitter)
  140. this.eventEmitter.on(eventId, handler);
  141. };
  142. /**
  143. * Removes event listener
  144. * @param eventId the event ID.
  145. * @param [handler] optional, the specific handler to unbind
  146. *
  147. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  148. */
  149. JitsiConference.prototype.off = function (eventId, handler) {
  150. if(this.eventEmitter)
  151. this.eventEmitter.removeListener(eventId, handler);
  152. };
  153. // Common aliases for event emitter
  154. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  155. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  156. /**
  157. * Receives notifications from another participants for commands / custom events
  158. * (send by sendPresenceCommand method).
  159. * @param command {String} the name of the command
  160. * @param handler {Function} handler for the command
  161. */
  162. JitsiConference.prototype.addCommandListener = function (command, handler) {
  163. if(this.room)
  164. this.room.addPresenceListener(command, handler);
  165. };
  166. /**
  167. * Removes command listener
  168. * @param command {String} the name of the command
  169. */
  170. JitsiConference.prototype.removeCommandListener = function (command) {
  171. if(this.room)
  172. this.room.removePresenceListener(command);
  173. };
  174. /**
  175. * Sends text message to the other participants in the conference
  176. * @param message the text message.
  177. */
  178. JitsiConference.prototype.sendTextMessage = function (message) {
  179. if(this.room)
  180. this.room.sendMessage(message);
  181. };
  182. /**
  183. * Send presence command.
  184. * @param name the name of the command.
  185. * @param values Object with keys and values that will be send.
  186. **/
  187. JitsiConference.prototype.sendCommand = function (name, values) {
  188. if(this.room) {
  189. this.room.addToPresence(name, values);
  190. this.room.sendPresence();
  191. }
  192. };
  193. /**
  194. * Send presence command one time.
  195. * @param name the name of the command.
  196. * @param values Object with keys and values that will be send.
  197. **/
  198. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  199. this.sendCommand(name, values);
  200. this.removeCommand(name);
  201. };
  202. /**
  203. * Send presence command.
  204. * @param name the name of the command.
  205. * @param values Object with keys and values that will be send.
  206. * @param persistent if false the command will be sent only one time
  207. **/
  208. JitsiConference.prototype.removeCommand = function (name) {
  209. if(this.room)
  210. this.room.removeFromPresence(name);
  211. };
  212. /**
  213. * Sets the display name for this conference.
  214. * @param name the display name to set
  215. */
  216. JitsiConference.prototype.setDisplayName = function(name) {
  217. if(this.room){
  218. // remove previously set nickname
  219. this.room.removeFromPresence("nick");
  220. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  221. this.room.sendPresence();
  222. }
  223. };
  224. /**
  225. * Adds JitsiLocalTrack object to the conference.
  226. * @param track the JitsiLocalTrack object.
  227. */
  228. JitsiConference.prototype.addTrack = function (track) {
  229. this.room.addStream(track.getOriginalStream(), function () {
  230. this.rtc.addLocalStream(track);
  231. var muteHandler = this._fireMuteChangeEvent.bind(this, track);
  232. var stopHandler = this.removeTrack.bind(this, track);
  233. var audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  234. track.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, muteHandler);
  235. track.addEventListener(JitsiTrackEvents.TRACK_STOPPED, stopHandler);
  236. track.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, audioLevelHandler);
  237. this.addEventListener(JitsiConferenceEvents.TRACK_REMOVED, function (someTrack) {
  238. if (someTrack !== track) {
  239. return;
  240. }
  241. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, muteHandler);
  242. track.removeEventListener(JitsiTrackEvents.TRACK_STOPPED, stopHandler);
  243. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, audioLevelHandler);
  244. });
  245. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  246. }.bind(this));
  247. };
  248. /**
  249. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event.
  250. * @param audioLevel the audio level
  251. */
  252. JitsiConference.prototype._fireAudioLevelChangeEvent = function (audioLevel) {
  253. this.eventEmitter.emit(
  254. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  255. this.myUserId(), audioLevel);
  256. };
  257. /**
  258. * Fires TRACK_MUTE_CHANGED change conference event.
  259. * @param track the JitsiTrack object related to the event.
  260. */
  261. JitsiConference.prototype._fireMuteChangeEvent = function (track) {
  262. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  263. };
  264. /**
  265. * Removes JitsiLocalTrack object to the conference.
  266. * @param track the JitsiLocalTrack object.
  267. */
  268. JitsiConference.prototype.removeTrack = function (track) {
  269. if(!this.room){
  270. if(this.rtc)
  271. this.rtc.removeLocalStream(track);
  272. return;
  273. }
  274. this.room.removeStream(track.getOriginalStream(), function(){
  275. this.rtc.removeLocalStream(track);
  276. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  277. }.bind(this));
  278. };
  279. /**
  280. * Get role of the local user.
  281. * @returns {string} user role: 'moderator' or 'none'
  282. */
  283. JitsiConference.prototype.getRole = function () {
  284. return this.room.role;
  285. };
  286. /**
  287. * Check if local user is moderator.
  288. * @returns {boolean} true if local user is moderator, false otherwise.
  289. */
  290. JitsiConference.prototype.isModerator = function () {
  291. return this.room.isModerator();
  292. };
  293. /**
  294. * Set password for the room.
  295. * @param {string} password new password for the room.
  296. * @returns {Promise}
  297. */
  298. JitsiConference.prototype.lock = function (password) {
  299. if (!this.isModerator()) {
  300. return Promise.reject();
  301. }
  302. var conference = this;
  303. return new Promise(function (resolve, reject) {
  304. conference.room.lockRoom(password || "", function () {
  305. resolve();
  306. }, function (err) {
  307. reject(err);
  308. }, function () {
  309. reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED);
  310. });
  311. });
  312. };
  313. /**
  314. * Remove password from the room.
  315. * @returns {Promise}
  316. */
  317. JitsiConference.prototype.unlock = function () {
  318. return this.lock();
  319. };
  320. /**
  321. * Elects the participant with the given id to be the selected participant or the speaker.
  322. * @param id the identifier of the participant
  323. */
  324. JitsiConference.prototype.selectParticipant = function(participantId) {
  325. if (this.rtc) {
  326. this.rtc.selectedEndpoint(participantId);
  327. }
  328. };
  329. /**
  330. *
  331. * @param id the identifier of the participant
  332. */
  333. JitsiConference.prototype.pinParticipant = function(participantId) {
  334. if (this.rtc) {
  335. this.rtc.pinEndpoint(participantId);
  336. }
  337. };
  338. /**
  339. * Returns the list of participants for this conference.
  340. * @return Array<JitsiParticipant> a list of participant identifiers containing all conference participants.
  341. */
  342. JitsiConference.prototype.getParticipants = function() {
  343. return Object.keys(this.participants).map(function (key) {
  344. return this.participants[key];
  345. }, this);
  346. };
  347. /**
  348. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  349. * undefined if there isn't one).
  350. * @param id the id of the participant.
  351. */
  352. JitsiConference.prototype.getParticipantById = function(id) {
  353. return this.participants[id];
  354. };
  355. /**
  356. * Kick participant from this conference.
  357. * @param {string} id id of the participant to kick
  358. */
  359. JitsiConference.prototype.kickParticipant = function (id) {
  360. var participant = this.getParticipantById(id);
  361. if (!participant) {
  362. return;
  363. }
  364. this.room.kick(participant.getJid());
  365. };
  366. JitsiConference.prototype.onMemberJoined = function (jid, email, nick) {
  367. var id = Strophe.getResourceFromJid(jid);
  368. if (id === 'focus' || this.myUserId() === id) {
  369. return;
  370. }
  371. var participant = new JitsiParticipant(jid, this, nick);
  372. this.participants[id] = participant;
  373. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, id, participant);
  374. this.xmpp.connection.disco.info(
  375. jid, "node", function(iq) {
  376. participant._supportsDTMF = $(iq).find(
  377. '>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  378. this.updateDTMFSupport();
  379. }.bind(this)
  380. );
  381. };
  382. JitsiConference.prototype.onMemberLeft = function (jid) {
  383. var id = Strophe.getResourceFromJid(jid);
  384. if (id === 'focus' || this.myUserId() === id) {
  385. return;
  386. }
  387. var participant = this.participants[id];
  388. delete this.participants[id];
  389. this.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, id, participant);
  390. };
  391. JitsiConference.prototype.onUserRoleChanged = function (jid, role) {
  392. var id = Strophe.getResourceFromJid(jid);
  393. var participant = this.getParticipantById(id);
  394. if (!participant) {
  395. return;
  396. }
  397. participant._role = role;
  398. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  399. };
  400. JitsiConference.prototype.onDisplayNameChanged = function (jid, displayName) {
  401. var id = Strophe.getResourceFromJid(jid);
  402. var participant = this.getParticipantById(id);
  403. if (!participant) {
  404. return;
  405. }
  406. participant._displayName = displayName;
  407. this.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED, id, displayName);
  408. };
  409. JitsiConference.prototype.onTrackAdded = function (track) {
  410. var id = track.getParticipantId();
  411. var participant = this.getParticipantById(id);
  412. if (!participant) {
  413. return;
  414. }
  415. // add track to JitsiParticipant
  416. participant._tracks.push(track);
  417. var emitter = this.eventEmitter;
  418. track.addEventListener(
  419. JitsiTrackEvents.TRACK_STOPPED,
  420. function () {
  421. // remove track from JitsiParticipant
  422. var pos = participant._tracks.indexOf(track);
  423. if (pos > -1) {
  424. participant._tracks.splice(pos, 1);
  425. }
  426. emitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  427. }
  428. );
  429. track.addEventListener(
  430. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  431. function () {
  432. emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  433. }
  434. );
  435. track.addEventListener(
  436. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  437. function (audioLevel) {
  438. emitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, id, audioLevel);
  439. }
  440. );
  441. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  442. };
  443. JitsiConference.prototype.updateDTMFSupport = function () {
  444. var somebodySupportsDTMF = false;
  445. var participants = this.getParticipants();
  446. // check if at least 1 participant supports DTMF
  447. for (var i = 0; i < participants.length; i += 1) {
  448. if (participants[i].supportsDTMF()) {
  449. somebodySupportsDTMF = true;
  450. break;
  451. }
  452. }
  453. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  454. this.somebodySupportsDTMF = somebodySupportsDTMF;
  455. this.eventEmitter.emit(JitsiConferenceEvents.DTMF_SUPPORT_CHANGED, somebodySupportsDTMF);
  456. }
  457. };
  458. /**
  459. * Allows to check if there is at least one user in the conference
  460. * that supports DTMF.
  461. * @returns {boolean} true if somebody supports DTMF, false otherwise
  462. */
  463. JitsiConference.prototype.isDTMFSupported = function () {
  464. return this.somebodySupportsDTMF;
  465. };
  466. /**
  467. * Returns the local user's ID
  468. * @return {string} local user's ID
  469. */
  470. JitsiConference.prototype.myUserId = function () {
  471. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  472. };
  473. JitsiConference.prototype.sendTones = function (tones, duration, pause) {
  474. if (!this.dtmfManager) {
  475. var connection = this.xmpp.connection.jingle.activecall.peerconnection;
  476. if (!connection) {
  477. logger.warn("cannot sendTones: no conneciton");
  478. return;
  479. }
  480. var tracks = this.getLocalTracks().filter(function (track) {
  481. return track.isAudioTrack();
  482. });
  483. if (!tracks.length) {
  484. logger.warn("cannot sendTones: no local audio stream");
  485. return;
  486. }
  487. this.dtmfManager = new JitsiDTMFManager(tracks[0], connection);
  488. }
  489. this.dtmfManager.sendTones(tones, duration, pause);
  490. };
  491. /**
  492. * Returns true if the recording is supproted and false if not.
  493. */
  494. JitsiConference.prototype.isRecordingSupported = function () {
  495. if(this.room)
  496. return this.room.isRecordingSupported();
  497. return false;
  498. };
  499. /**
  500. * Returns null if the recording is not supported, "on" if the recording started
  501. * and "off" if the recording is not started.
  502. */
  503. JitsiConference.prototype.getRecordingState = function () {
  504. if(this.room)
  505. return this.room.getRecordingState();
  506. return "off";
  507. }
  508. /**
  509. * Returns the url of the recorded video.
  510. */
  511. JitsiConference.prototype.getRecordingURL = function () {
  512. if(this.room)
  513. return this.room.getRecordingURL();
  514. return null;
  515. }
  516. /**
  517. * Starts/stops the recording
  518. * @param token a token for authentication.
  519. */
  520. JitsiConference.prototype.toggleRecording = function (token, followEntity) {
  521. if(this.room)
  522. return this.room.toggleRecording(token, followEntity);
  523. return new Promise(function(resolve, reject){
  524. reject(new Error("The conference is not created yet!"))});
  525. }
  526. /**
  527. * Dials a number.
  528. * @param number the number
  529. */
  530. JitsiConference.prototype.dial = function (number) {
  531. if(this.room)
  532. return this.room.dial(number);
  533. return new Promise(function(resolve, reject){
  534. reject(new Error("The conference is not created yet!"))});
  535. }
  536. /**
  537. * Hangup an existing call
  538. */
  539. JitsiConference.prototype.hangup = function () {
  540. if(this.room)
  541. return this.room.hangup();
  542. return new Promise(function(resolve, reject){
  543. reject(new Error("The conference is not created yet!"))});
  544. }
  545. /**
  546. * Returns the phone number for joining the conference.
  547. */
  548. JitsiConference.prototype.getPhoneNumber = function () {
  549. if(this.room)
  550. return this.room.getPhoneNumber();
  551. return null;
  552. }
  553. /**
  554. * Returns the pin for joining the conference with phone.
  555. */
  556. JitsiConference.prototype.getPhonePin = function () {
  557. if(this.room)
  558. return this.room.getPhonePin();
  559. return null;
  560. }
  561. /**
  562. * Returns the connection state for the current room. Its ice connection state
  563. * for its session.
  564. */
  565. JitsiConference.prototype.getConnectionState = function () {
  566. if(this.room)
  567. return this.room.getConnectionState();
  568. return null;
  569. }
  570. /**
  571. * Setups the listeners needed for the conference.
  572. * @param conference the conference
  573. */
  574. function setupListeners(conference) {
  575. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  576. conference.rtc.onIncommingCall(event);
  577. if(conference.statistics)
  578. conference.statistics.startRemoteStats(event.peerconnection);
  579. });
  580. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  581. function (data, sid, thessrc) {
  582. var track = conference.rtc.createRemoteStream(data, sid, thessrc);
  583. if (track) {
  584. conference.onTrackAdded(track);
  585. }
  586. }
  587. );
  588. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  589. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  590. });
  591. conference.room.addListener(XMPPEvents.ROOM_JOIN_ERROR, function (pres) {
  592. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  593. });
  594. conference.room.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function (pres) {
  595. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  596. });
  597. conference.room.addListener(XMPPEvents.PASSWORD_REQUIRED, function (pres) {
  598. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.PASSWORD_REQUIRED, pres);
  599. });
  600. conference.room.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, function () {
  601. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.AUTHENTICATION_REQUIRED);
  602. });
  603. // FIXME
  604. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  605. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  606. // });
  607. conference.room.addListener(XMPPEvents.KICKED, function () {
  608. conference.eventEmitter.emit(JitsiConferenceEvents.KICKED);
  609. });
  610. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  611. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT, conference.onMemberLeft.bind(conference));
  612. conference.room.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, conference.onDisplayNameChanged.bind(conference));
  613. conference.room.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, function (role) {
  614. conference.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, conference.myUserId(), role);
  615. });
  616. conference.room.addListener(XMPPEvents.MUC_ROLE_CHANGED, conference.onUserRoleChanged.bind(conference));
  617. conference.room.addListener(XMPPEvents.CONNECTION_INTERRUPTED, function () {
  618. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  619. });
  620. conference.room.addListener(XMPPEvents.RECORDING_STATE_CHANGED,
  621. function () {
  622. conference.eventEmitter.emit(
  623. JitsiConferenceEvents.RECORDING_STATE_CHANGED);
  624. });
  625. conference.room.addListener(XMPPEvents.PHONE_NUMBER_CHANGED, function () {
  626. conference.eventEmitter.emit(
  627. JitsiConferenceEvents.PHONE_NUMBER_CHANGED);
  628. });
  629. conference.room.addListener(XMPPEvents.CONNECTION_RESTORED, function () {
  630. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  631. });
  632. conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  633. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.SETUP_FAILED);
  634. });
  635. conference.room.addListener(AuthenticationEvents.IDENTITY_UPDATED, function (authEnabled, authIdentity) {
  636. conference.authEnabled = authEnabled;
  637. conference.authIdentity = authIdentity;
  638. });
  639. conference.room.addListener(XMPPEvents.MESSAGE_RECEIVED, function (jid, displayName, txt, myJid, ts) {
  640. var id = Strophe.getResourceFromJid(jid);
  641. conference.eventEmitter.emit(JitsiConferenceEvents.MESSAGE_RECEIVED, id, txt, ts);
  642. });
  643. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  644. if(conference.lastActiveSpeaker !== id && conference.room) {
  645. conference.lastActiveSpeaker = id;
  646. conference.eventEmitter.emit(JitsiConferenceEvents.ACTIVE_SPEAKER_CHANGED, id);
  647. }
  648. });
  649. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  650. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  651. });
  652. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  653. function (lastNEndpoints, endpointsEnteringLastN) {
  654. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  655. lastNEndpoints, endpointsEnteringLastN);
  656. });
  657. conference.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, function () {
  658. conference.eventEmitter.emit(JitsiConferenceErrors.PASSWORD_REQUIRED);
  659. });
  660. if(conference.statistics) {
  661. //FIXME: Maybe remove event should not be associated with the conference.
  662. conference.statistics.addAudioLevelListener(function (ssrc, level) {
  663. var userId = null;
  664. var jid = conference.room.getJidBySSRC(ssrc);
  665. if (!jid)
  666. return;
  667. conference.rtc.setAudioLevel(jid, level);
  668. });
  669. conference.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE,
  670. function () {
  671. conference.statistics.dispose();
  672. });
  673. // FIXME: Maybe we should move this.
  674. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  675. // conference.room.updateDeviceAvailability(devices);
  676. // });
  677. }
  678. }
  679. module.exports = JitsiConference;
  680. }).call(this,"/JitsiConference.js")
  681. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./JitsiTrackEvents":10,"./modules/DTMF/JitsiDTMFManager":11,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"./service/RTC/RTCEvents":80,"./service/authentication/AuthenticationEvents":83,"./service/xmpp/XMPPEvents":87,"events":44,"jitsi-meet-logger":48}],2:[function(require,module,exports){
  682. /**
  683. * Enumeration with the errors for the conference.
  684. * @type {{string: string}}
  685. */
  686. var JitsiConferenceErrors = {
  687. /**
  688. * Indicates that a password is required in order to join the conference.
  689. */
  690. PASSWORD_REQUIRED: "conference.passwordRequired",
  691. /**
  692. * Indicates that client must be authenticated to create the conference.
  693. */
  694. AUTHENTICATION_REQUIRED: "conference.authenticationRequired",
  695. /**
  696. * Indicates that password cannot be set for this conference.
  697. */
  698. PASSWORD_NOT_SUPPORTED: "conference.passwordNotSupported",
  699. /**
  700. * Indicates that a connection error occurred when trying to join a
  701. * conference.
  702. */
  703. CONNECTION_ERROR: "conference.connectionError",
  704. /**
  705. * Indicates that the conference setup failed.
  706. */
  707. SETUP_FAILED: "conference.setup_failed",
  708. /**
  709. * Indicates that there is no available videobridge.
  710. */
  711. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  712. /**
  713. * Many more errors TBD here.
  714. */
  715. };
  716. module.exports = JitsiConferenceErrors;
  717. },{}],3:[function(require,module,exports){
  718. /**
  719. * Enumeration with the events for the conference.
  720. * @type {{string: string}}
  721. */
  722. var JitsiConferenceEvents = {
  723. /**
  724. * A new media track was added to the conference.
  725. */
  726. TRACK_ADDED: "conference.trackAdded",
  727. /**
  728. * The media track was removed from the conference.
  729. */
  730. TRACK_REMOVED: "conference.trackRemoved",
  731. /**
  732. * The active speaker was changed.
  733. */
  734. ACTIVE_SPEAKER_CHANGED: "conference.activeSpeaker",
  735. /**
  736. * A new user joinned the conference.
  737. */
  738. USER_JOINED: "conference.userJoined",
  739. /**
  740. * A user has left the conference.
  741. */
  742. USER_LEFT: "conference.userLeft",
  743. /**
  744. * User role changed.
  745. */
  746. USER_ROLE_CHANGED: "conference.roleChanged",
  747. /**
  748. * New text message was received.
  749. */
  750. MESSAGE_RECEIVED: "conference.messageReceived",
  751. /**
  752. * A user has changed it display name
  753. */
  754. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  755. /**
  756. * A participant avatar has changed.
  757. */
  758. AVATAR_CHANGED: "conference.avatarChanged",
  759. /**
  760. * New connection statistics are received.
  761. */
  762. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  763. /**
  764. * The Last N set is changed.
  765. */
  766. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  767. /**
  768. * You are included / excluded in somebody's last N set
  769. */
  770. IN_LAST_N_CHANGED: "conference.lastNEndpointsChanged",
  771. /**
  772. * A media track ( attached to the conference) mute status was changed.
  773. */
  774. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  775. /**
  776. * Audio levels of a media track ( attached to the conference) was changed.
  777. */
  778. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  779. /**
  780. * Indicates that the connection to the conference has been interrupted
  781. * for some reason.
  782. */
  783. CONNECTION_INTERRUPTED: "conference.connectionInterrupted",
  784. /**
  785. * Indicates that the connection to the conference has been restored.
  786. */
  787. CONNECTION_RESTORED: "conference.connectionRestored",
  788. /**
  789. * Indicates that conference failed.
  790. */
  791. CONFERENCE_FAILED: "conference.failed",
  792. /**
  793. * Indicates that conference has been joined.
  794. */
  795. CONFERENCE_JOINED: "conference.joined",
  796. /**
  797. * Indicates that conference has been left.
  798. */
  799. CONFERENCE_LEFT: "conference.left",
  800. /**
  801. * You are kicked from the conference.
  802. */
  803. KICKED: "conferenece.kicked",
  804. /**
  805. * Indicates that DTMF support changed.
  806. */
  807. DTMF_SUPPORT_CHANGED: "conference.dtmfSupportChanged",
  808. /**
  809. * Indicates that recording state changed.
  810. */
  811. RECORDING_STATE_CHANGED: "conference.recordingStateChanged",
  812. /**
  813. * Indicates that phone number changed.
  814. */
  815. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged"
  816. };
  817. module.exports = JitsiConferenceEvents;
  818. },{}],4:[function(require,module,exports){
  819. var JitsiConference = require("./JitsiConference");
  820. var XMPP = require("./modules/xmpp/xmpp");
  821. /**
  822. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  823. * JitsiConference interface.
  824. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  825. * @param token the JWT token used to authenticate with the server(optional)
  826. * @param options Object with properties / settings related to connection with the server.
  827. * @constructor
  828. */
  829. function JitsiConnection(appID, token, options) {
  830. this.appID = appID;
  831. this.token = token;
  832. this.options = options;
  833. this.xmpp = new XMPP(options);
  834. this.conferences = {};
  835. }
  836. /**
  837. * Connect the client with the server.
  838. * @param options {object} connecting options (for example authentications parameters).
  839. */
  840. JitsiConnection.prototype.connect = function (options) {
  841. if(!options)
  842. options = {};
  843. this.xmpp.connect(options.id, options.password);
  844. }
  845. /**
  846. * Disconnect the client from the server.
  847. */
  848. JitsiConnection.prototype.disconnect = function () {
  849. this.xmpp.disconnect();
  850. }
  851. /**
  852. * This method allows renewal of the tokens if they are expiring.
  853. * @param token the new token.
  854. */
  855. JitsiConnection.prototype.setToken = function (token) {
  856. this.token = token;
  857. }
  858. /**
  859. * Creates and joins new conference.
  860. * @param name the name of the conference; if null - a generated name will be provided from the api
  861. * @param options Object with properties / settings related to the conference that will be created.
  862. * @returns {JitsiConference} returns the new conference object.
  863. */
  864. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  865. this.conferences[name] = new JitsiConference({name: name, config: options, connection: this});
  866. return this.conferences[name];
  867. }
  868. /**
  869. * Subscribes the passed listener to the event.
  870. * @param event {JitsiConnectionEvents} the connection event.
  871. * @param listener {Function} the function that will receive the event
  872. */
  873. JitsiConnection.prototype.addEventListener = function (event, listener) {
  874. this.xmpp.addListener(event, listener);
  875. }
  876. /**
  877. * Unsubscribes the passed handler.
  878. * @param event {JitsiConnectionEvents} the connection event.
  879. * @param listener {Function} the function that will receive the event
  880. */
  881. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  882. this.xmpp.removeListener(event, listener);
  883. }
  884. module.exports = JitsiConnection;
  885. },{"./JitsiConference":1,"./modules/xmpp/xmpp":42}],5:[function(require,module,exports){
  886. /**
  887. * Enumeration with the errors for the connection.
  888. * @type {{string: string}}
  889. */
  890. var JitsiConnectionErrors = {
  891. /**
  892. * Indicates that a password is required in order to join the conference.
  893. */
  894. PASSWORD_REQUIRED: "connection.passwordRequired",
  895. /**
  896. * Indicates that a connection error occurred when trying to join a
  897. * conference.
  898. */
  899. CONNECTION_ERROR: "connection.connectionError",
  900. /**
  901. * Not specified errors.
  902. */
  903. OTHER_ERROR: "connection.otherError"
  904. };
  905. module.exports = JitsiConnectionErrors;
  906. },{}],6:[function(require,module,exports){
  907. /**
  908. * Enumeration with the events for the connection.
  909. * @type {{string: string}}
  910. */
  911. var JitsiConnnectionEvents = {
  912. /**
  913. * Indicates that the connection has been failed for some reason.
  914. */
  915. CONNECTION_FAILED: "connection.connectionFailed",
  916. /**
  917. * Indicates that the connection has been established.
  918. */
  919. CONNECTION_ESTABLISHED: "connection.connectionEstablished",
  920. /**
  921. * Indicates that the connection has been disconnected.
  922. */
  923. CONNECTION_DISCONNECTED: "connection.connectionDisconnected",
  924. /**
  925. * Indicates that the perfomed action cannot be executed because the
  926. * connection is not in the correct state(connected, disconnected, etc.)
  927. */
  928. WRONG_STATE: "connection.wrongState"
  929. };
  930. module.exports = JitsiConnnectionEvents;
  931. },{}],7:[function(require,module,exports){
  932. var JitsiConnection = require("./JitsiConnection");
  933. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  934. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  935. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  936. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  937. var JitsiTrackEvents = require("./JitsiTrackEvents");
  938. var JitsiTrackErrors = require("./JitsiTrackErrors");
  939. var Logger = require("jitsi-meet-logger");
  940. var RTC = require("./modules/RTC/RTC");
  941. var Statistics = require("./modules/statistics/statistics");
  942. /**
  943. * Namespace for the interface of Jitsi Meet Library.
  944. */
  945. var LibJitsiMeet = {
  946. JitsiConnection: JitsiConnection,
  947. events: {
  948. conference: JitsiConferenceEvents,
  949. connection: JitsiConnectionEvents,
  950. track: JitsiTrackEvents
  951. },
  952. errors: {
  953. conference: JitsiConferenceErrors,
  954. connection: JitsiConnectionErrors,
  955. track: JitsiTrackErrors
  956. },
  957. logLevels: Logger.levels,
  958. init: function (options) {
  959. return RTC.init(options || {});
  960. },
  961. setLogLevel: function (level) {
  962. Logger.setLogLevel(level);
  963. },
  964. /**
  965. * Creates the media tracks and returns them trough the callback.
  966. * @param options Object with properties / settings specifying the tracks which should be created.
  967. * should be created or some additional configurations about resolution for example.
  968. * @param {Array} options.devices the devices that will be requested
  969. * @param {string} options.resolution resolution constraints
  970. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  971. * type: "audio" or "video", videoType: "camera" or "desktop"}
  972. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  973. * @param {string} options.cameraDeviceId
  974. * @param {string} options.micDeviceId
  975. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>}
  976. * A promise that returns an array of created JitsiTracks if resolved,
  977. * or a JitsiConferenceError if rejected.
  978. */
  979. createLocalTracks: function (options) {
  980. return RTC.obtainAudioAndVideoPermissions(options || {}).then(
  981. function(tracks) {
  982. if(!RTC.options.disableAudioLevels)
  983. for(var i = 0; i < tracks.length; i++) {
  984. var track = tracks[i];
  985. var mStream = track.getOriginalStream();
  986. if(track.getType() === "audio"){
  987. Statistics.startLocalStats(mStream,
  988. track.setAudioLevel.bind(track));
  989. track.addEventListener(
  990. JitsiTrackEvents.TRACK_STOPPED,
  991. function(){
  992. Statistics.stopLocalStats(mStream);
  993. });
  994. }
  995. }
  996. return tracks;
  997. });
  998. },
  999. /**
  1000. * Checks if its possible to enumerate available cameras/micropones.
  1001. * @returns {boolean} true if available, false otherwise.
  1002. */
  1003. isDeviceListAvailable: function () {
  1004. return RTC.isDeviceListAvailable();
  1005. },
  1006. /**
  1007. * Returns true if changing the camera / microphone device is supported and
  1008. * false if not.
  1009. * @returns {boolean} true if available, false otherwise.
  1010. */
  1011. isDeviceChangeAvailable: function () {
  1012. return RTC.isDeviceChangeAvailable();
  1013. },
  1014. enumerateDevices: function (callback) {
  1015. RTC.enumerateDevices(callback);
  1016. }
  1017. };
  1018. require("es6-promise").polyfill()
  1019. //Setups the promise object.
  1020. window.Promise = window.Promise || require("es6-promise").Promise;
  1021. module.exports = LibJitsiMeet;
  1022. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./JitsiTrackErrors":9,"./JitsiTrackEvents":10,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"es6-promise":46,"jitsi-meet-logger":48}],8:[function(require,module,exports){
  1023. /* global Strophe */
  1024. /**
  1025. * Represents a participant in (a member of) a conference.
  1026. */
  1027. function JitsiParticipant(jid, conference, displayName){
  1028. this._jid = jid;
  1029. this._id = Strophe.getResourceFromJid(jid);
  1030. this._conference = conference;
  1031. this._displayName = displayName;
  1032. this._supportsDTMF = false;
  1033. this._tracks = [];
  1034. this._role = 'none';
  1035. }
  1036. /**
  1037. * @returns {JitsiConference} The conference that this participant belongs to.
  1038. */
  1039. JitsiParticipant.prototype.getConference = function() {
  1040. return this._conference;
  1041. };
  1042. /**
  1043. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  1044. */
  1045. JitsiParticipant.prototype.getTracks = function() {
  1046. return this._tracks;
  1047. };
  1048. /**
  1049. * @returns {String} The ID of this participant.
  1050. */
  1051. JitsiParticipant.prototype.getId = function() {
  1052. return this._id;
  1053. };
  1054. /**
  1055. * @returns {String} The JID of this participant.
  1056. */
  1057. JitsiParticipant.prototype.getJid = function() {
  1058. return this._jid;
  1059. };
  1060. /**
  1061. * @returns {String} The human-readable display name of this participant.
  1062. */
  1063. JitsiParticipant.prototype.getDisplayName = function() {
  1064. return this._displayName;
  1065. };
  1066. /**
  1067. * @returns {Boolean} Whether this participant is a moderator or not.
  1068. */
  1069. JitsiParticipant.prototype.isModerator = function() {
  1070. return this._role === 'moderator';
  1071. };
  1072. // Gets a link to an etherpad instance advertised by the participant?
  1073. //JitsiParticipant.prototype.getEtherpad = function() {
  1074. //
  1075. //}
  1076. /*
  1077. * @returns {Boolean} Whether this participant has muted their audio.
  1078. */
  1079. JitsiParticipant.prototype.isAudioMuted = function() {
  1080. return this.getTracks().reduce(function (track, isAudioMuted) {
  1081. return isAudioMuted && (track.isVideoTrack() || track.isMuted());
  1082. }, true);
  1083. };
  1084. /*
  1085. * @returns {Boolean} Whether this participant has muted their video.
  1086. */
  1087. JitsiParticipant.prototype.isVideoMuted = function() {
  1088. return this.getTracks().reduce(function (track, isVideoMuted) {
  1089. return isVideoMuted && (track.isAudioTrack() || track.isMuted());
  1090. }, true);
  1091. };
  1092. /*
  1093. * @returns {???} The latest statistics reported by this participant
  1094. * (i.e. info used to populate the GSM bars)
  1095. * TODO: do we expose this or handle it internally?
  1096. */
  1097. JitsiParticipant.prototype.getLatestStats = function() {
  1098. };
  1099. /**
  1100. * @returns {String} The role of this participant.
  1101. */
  1102. JitsiParticipant.prototype.getRole = function() {
  1103. return this._role;
  1104. };
  1105. /*
  1106. * @returns {Boolean} Whether this participant is
  1107. * the conference focus (i.e. jicofo).
  1108. */
  1109. JitsiParticipant.prototype.isFocus = function() {
  1110. };
  1111. /*
  1112. * @returns {Boolean} Whether this participant is
  1113. * a conference recorder (i.e. jirecon).
  1114. */
  1115. JitsiParticipant.prototype.isRecorder = function() {
  1116. };
  1117. /*
  1118. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  1119. */
  1120. JitsiParticipant.prototype.isSipGateway = function() {
  1121. };
  1122. /**
  1123. * @returns {Boolean} Whether this participant
  1124. * is currently sharing their screen.
  1125. */
  1126. JitsiParticipant.prototype.isScreenSharing = function() {
  1127. };
  1128. /**
  1129. * @returns {String} The user agent of this participant
  1130. * (i.e. browser userAgent string).
  1131. */
  1132. JitsiParticipant.prototype.getUserAgent = function() {
  1133. };
  1134. /**
  1135. * Kicks the participant from the conference (requires certain privileges).
  1136. */
  1137. JitsiParticipant.prototype.kick = function() {
  1138. };
  1139. /**
  1140. * Asks this participant to mute themselves.
  1141. */
  1142. JitsiParticipant.prototype.askToMute = function() {
  1143. };
  1144. JitsiParticipant.prototype.supportsDTMF = function () {
  1145. return this._supportsDTMF;
  1146. };
  1147. module.exports = JitsiParticipant;
  1148. },{}],9:[function(require,module,exports){
  1149. module.exports = {
  1150. /**
  1151. * Returns JitsiTrackErrors based on the error object passed by GUM
  1152. * @param error the error
  1153. * @param {Object} options the options object given to GUM.
  1154. */
  1155. parseError: function (error, options) {
  1156. options = options || {};
  1157. if (typeof error == "object" && error.constraintName && error.name
  1158. && (error.name == "ConstraintNotSatisfiedError" ||
  1159. error.name == "OverconstrainedError") &&
  1160. (error.constraintName == "minWidth" ||
  1161. error.constraintName == "maxWidth" ||
  1162. error.constraintName == "minHeight" ||
  1163. error.constraintName == "maxHeight") &&
  1164. options.devices.indexOf("video") !== -1) {
  1165. return this.UNSUPPORTED_RESOLUTION;
  1166. } else {
  1167. return this.GENERAL;
  1168. }
  1169. },
  1170. UNSUPPORTED_RESOLUTION: "gum.unsupported_resolution",
  1171. GENERAL: "gum.general"
  1172. };
  1173. },{}],10:[function(require,module,exports){
  1174. var JitsiTrackEvents = {
  1175. /**
  1176. * A media track mute status was changed.
  1177. */
  1178. TRACK_MUTE_CHANGED: "track.trackMuteChanged",
  1179. /**
  1180. * Audio levels of a this track was changed.
  1181. */
  1182. TRACK_AUDIO_LEVEL_CHANGED: "track.audioLevelsChanged",
  1183. /**
  1184. * The media track was removed to the conference.
  1185. */
  1186. TRACK_STOPPED: "track.stopped"
  1187. };
  1188. module.exports = JitsiTrackEvents;
  1189. },{}],11:[function(require,module,exports){
  1190. (function (__filename){
  1191. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1192. function JitsiDTMFManager (localAudio, peerConnection) {
  1193. var tracks = localAudio._getTracks();
  1194. if (!tracks.length) {
  1195. throw new Error("Failed to initialize DTMFSender: no audio track.");
  1196. }
  1197. this.dtmfSender = peerConnection.peerconnection.createDTMFSender(tracks[0]);
  1198. logger.debug("Initialized DTMFSender");
  1199. }
  1200. JitsiDTMFManager.prototype.sendTones = function (tones, duration, pause) {
  1201. this.dtmfSender.insertDTMF(tones, (duration || 200), (pause || 200));
  1202. };
  1203. }).call(this,"/modules/DTMF/JitsiDTMFManager.js")
  1204. },{"jitsi-meet-logger":48}],12:[function(require,module,exports){
  1205. (function (__filename){
  1206. /* global config, APP, Strophe */
  1207. // cache datachannels to avoid garbage collection
  1208. // https://code.google.com/p/chromium/issues/detail?id=405545
  1209. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1210. var RTCEvents = require("../../service/RTC/RTCEvents");
  1211. /**
  1212. * Binds "ondatachannel" event listener to given PeerConnection instance.
  1213. * @param peerConnection WebRTC peer connection instance.
  1214. */
  1215. function DataChannels(peerConnection, emitter) {
  1216. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  1217. this.eventEmitter = emitter;
  1218. this._dataChannels = [];
  1219. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  1220. // Although it's not a requirement to open separate channels from both bridge
  1221. // and peer as single channel can be used for sending and receiving data.
  1222. // So either channel opened by the bridge or the one opened here is enough
  1223. // for communication with the bridge.
  1224. /*var dataChannelOptions =
  1225. {
  1226. reliable: true
  1227. };
  1228. var dataChannel
  1229. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  1230. // Can be used only when is in open state
  1231. dataChannel.onopen = function ()
  1232. {
  1233. dataChannel.send("My channel !!!");
  1234. };
  1235. dataChannel.onmessage = function (event)
  1236. {
  1237. var msgData = event.data;
  1238. logger.info("Got My Data Channel Message:", msgData, dataChannel);
  1239. };*/
  1240. };
  1241. /**
  1242. * Callback triggered by PeerConnection when new data channel is opened
  1243. * on the bridge.
  1244. * @param event the event info object.
  1245. */
  1246. DataChannels.prototype.onDataChannel = function (event) {
  1247. var dataChannel = event.channel;
  1248. var self = this;
  1249. dataChannel.onopen = function () {
  1250. logger.info("Data channel opened by the Videobridge!", dataChannel);
  1251. // Code sample for sending string and/or binary data
  1252. // Sends String message to the bridge
  1253. //dataChannel.send("Hello bridge!");
  1254. // Sends 12 bytes binary message to the bridge
  1255. //dataChannel.send(new ArrayBuffer(12));
  1256. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  1257. };
  1258. dataChannel.onerror = function (error) {
  1259. logger.error("Data Channel Error:", error, dataChannel);
  1260. };
  1261. dataChannel.onmessage = function (event) {
  1262. var data = event.data;
  1263. // JSON
  1264. var obj;
  1265. try {
  1266. obj = JSON.parse(data);
  1267. }
  1268. catch (e) {
  1269. logger.error(
  1270. "Failed to parse data channel message as JSON: ",
  1271. data,
  1272. dataChannel);
  1273. }
  1274. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  1275. var colibriClass = obj.colibriClass;
  1276. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  1277. // Endpoint ID from the Videobridge.
  1278. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  1279. logger.info(
  1280. "Data channel new dominant speaker event: ",
  1281. dominantSpeakerEndpoint);
  1282. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  1283. }
  1284. else if ("InLastNChangeEvent" === colibriClass) {
  1285. var oldValue = obj.oldValue;
  1286. var newValue = obj.newValue;
  1287. // Make sure that oldValue and newValue are of type boolean.
  1288. var type;
  1289. if ((type = typeof oldValue) !== 'boolean') {
  1290. if (type === 'string') {
  1291. oldValue = (oldValue == "true");
  1292. } else {
  1293. oldValue = new Boolean(oldValue).valueOf();
  1294. }
  1295. }
  1296. if ((type = typeof newValue) !== 'boolean') {
  1297. if (type === 'string') {
  1298. newValue = (newValue == "true");
  1299. } else {
  1300. newValue = new Boolean(newValue).valueOf();
  1301. }
  1302. }
  1303. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  1304. }
  1305. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  1306. // The new/latest list of last-n endpoint IDs.
  1307. var lastNEndpoints = obj.lastNEndpoints;
  1308. // The list of endpoint IDs which are entering the list of
  1309. // last-n at this time i.e. were not in the old list of last-n
  1310. // endpoint IDs.
  1311. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  1312. logger.info(
  1313. "Data channel new last-n event: ",
  1314. lastNEndpoints, endpointsEnteringLastN, obj);
  1315. self.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1316. lastNEndpoints, endpointsEnteringLastN, obj);
  1317. }
  1318. else {
  1319. logger.debug("Data channel JSON-formatted message: ", obj);
  1320. // The received message appears to be appropriately formatted
  1321. // (i.e. is a JSON object which assigns a value to the mandatory
  1322. // property colibriClass) so don't just swallow it, expose it to
  1323. // public consumption.
  1324. self.eventEmitter.emit("rtc.datachannel." + colibriClass, obj);
  1325. }
  1326. }
  1327. };
  1328. dataChannel.onclose = function () {
  1329. logger.info("The Data Channel closed", dataChannel);
  1330. var idx = self._dataChannels.indexOf(dataChannel);
  1331. if (idx > -1)
  1332. self._dataChannels = self._dataChannels.splice(idx, 1);
  1333. };
  1334. this._dataChannels.push(dataChannel);
  1335. };
  1336. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  1337. this._onXXXEndpointChanged("selected", userResource);
  1338. }
  1339. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  1340. this._onXXXEndpointChanged("pinnned", userResource);
  1341. }
  1342. /**
  1343. * Notifies Videobridge about a change in the value of a specific
  1344. * endpoint-related property such as selected endpoint and pinnned endpoint.
  1345. *
  1346. * @param xxx the name of the endpoint-related property whose value changed
  1347. * @param userResource the new value of the endpoint-related property after the
  1348. * change
  1349. */
  1350. DataChannels.prototype._onXXXEndpointChanged = function (xxx, userResource) {
  1351. // Derive the correct words from xxx such as selected and Selected, pinned
  1352. // and Pinned.
  1353. var head = xxx.charAt(0);
  1354. var tail = xxx.substring(1);
  1355. var lower = head.toLowerCase() + tail;
  1356. var upper = head.toUpperCase() + tail;
  1357. // Notify Videobridge about the specified endpoint change.
  1358. console.log(lower + ' endpoint changed: ', userResource);
  1359. this._some(function (dataChannel) {
  1360. if (dataChannel.readyState == 'open') {
  1361. console.log(
  1362. 'sending ' + lower
  1363. + ' endpoint changed notification to the bridge: ',
  1364. userResource);
  1365. var jsonObject = {};
  1366. jsonObject.colibriClass = (upper + 'EndpointChangedEvent');
  1367. jsonObject[lower + "Endpoint"]
  1368. = (userResource ? userResource : null);
  1369. dataChannel.send(JSON.stringify(jsonObject));
  1370. return true;
  1371. }
  1372. });
  1373. }
  1374. DataChannels.prototype._some = function (callback, thisArg) {
  1375. var dataChannels = this._dataChannels;
  1376. if (dataChannels && dataChannels.length !== 0) {
  1377. if (thisArg)
  1378. return dataChannels.some(callback, thisArg);
  1379. else
  1380. return dataChannels.some(callback);
  1381. } else {
  1382. return false;
  1383. }
  1384. }
  1385. module.exports = DataChannels;
  1386. }).call(this,"/modules/RTC/DataChannels.js")
  1387. },{"../../service/RTC/RTCEvents":80,"jitsi-meet-logger":48}],13:[function(require,module,exports){
  1388. var JitsiTrack = require("./JitsiTrack");
  1389. var RTCBrowserType = require("./RTCBrowserType");
  1390. var JitsiTrackEvents = require('../../JitsiTrackEvents');
  1391. var RTC = require("./RTCUtils");
  1392. /**
  1393. * Represents a single media track (either audio or video).
  1394. * @constructor
  1395. */
  1396. function JitsiLocalTrack(stream, videoType,
  1397. resolution)
  1398. {
  1399. this.videoType = videoType;
  1400. this.dontFireRemoveEvent = false;
  1401. this.resolution = resolution;
  1402. this.startMuted = false;
  1403. var self = this;
  1404. JitsiTrack.call(this, null, stream,
  1405. function () {
  1406. if(!this.dontFireRemoveEvent)
  1407. this.eventEmitter.emit(
  1408. JitsiTrackEvents.TRACK_STOPPED);
  1409. this.dontFireRemoveEvent = false;
  1410. }.bind(this));
  1411. }
  1412. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  1413. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  1414. /**
  1415. * Mutes / unmutes the track.
  1416. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  1417. */
  1418. JitsiLocalTrack.prototype._setMute = function (mute) {
  1419. if(!this.rtc) {
  1420. this.startMuted = mute;
  1421. return;
  1422. }
  1423. var isAudio = this.type === JitsiTrack.AUDIO;
  1424. this.dontFireRemoveEvent = false;
  1425. if ((window.location.protocol != "https:") ||
  1426. (isAudio) || this.videoType === "desktop" ||
  1427. // FIXME FF does not support 'removeStream' method used to mute
  1428. RTCBrowserType.isFirefox()) {
  1429. var tracks = this._getTracks();
  1430. for (var idx = 0; idx < tracks.length; idx++) {
  1431. tracks[idx].enabled = !mute;
  1432. }
  1433. if(isAudio)
  1434. this.rtc.room.setAudioMute(mute);
  1435. else
  1436. this.rtc.room.setVideoMute(mute);
  1437. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1438. } else {
  1439. if (mute) {
  1440. this.dontFireRemoveEvent = true;
  1441. this.rtc.room.removeStream(this.stream, function () {});
  1442. RTC.stopMediaStream(this.stream);
  1443. if(isAudio)
  1444. this.rtc.room.setAudioMute(mute);
  1445. else
  1446. this.rtc.room.setVideoMute(mute);
  1447. this.stream = null;
  1448. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1449. //FIXME: Maybe here we should set the SRC for the containers to something
  1450. } else {
  1451. var self = this;
  1452. RTC.obtainAudioAndVideoPermissions({
  1453. devices: (isAudio ? ["audio"] : ["video"]),
  1454. resolution: self.resolution})
  1455. .then(function (streams) {
  1456. var stream = null;
  1457. for(var i = 0; i < streams.length; i++) {
  1458. stream = streams[i];
  1459. if(stream.type === self.type) {
  1460. self.stream = stream.stream;
  1461. self.videoType = stream.videoType;
  1462. break;
  1463. }
  1464. }
  1465. if(!stream)
  1466. return;
  1467. for(var i = 0; i < self.containers.length; i++)
  1468. {
  1469. RTC.attachMediaStream(self.containers[i], self.stream);
  1470. }
  1471. self.rtc.room.addStream(stream.stream,
  1472. function () {
  1473. if(isAudio)
  1474. self.rtc.room.setAudioMute(mute);
  1475. else
  1476. self.rtc.room.setVideoMute(mute);
  1477. self.eventEmitter.emit(
  1478. JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1479. });
  1480. });
  1481. }
  1482. }
  1483. }
  1484. /**
  1485. * Stops sending the media track. And removes it from the HTML.
  1486. * NOTE: Works for local tracks only.
  1487. */
  1488. JitsiLocalTrack.prototype.stop = function () {
  1489. if(!this.stream)
  1490. return;
  1491. if(this.rtc)
  1492. this.rtc.room.removeStream(this.stream, function () {});
  1493. RTC.stopMediaStream(this.stream);
  1494. this.detach();
  1495. }
  1496. /**
  1497. * Returns <tt>true</tt> - if the stream is muted
  1498. * and <tt>false</tt> otherwise.
  1499. * @returns {boolean} <tt>true</tt> - if the stream is muted
  1500. * and <tt>false</tt> otherwise.
  1501. */
  1502. JitsiLocalTrack.prototype.isMuted = function () {
  1503. if (!this.stream)
  1504. return true;
  1505. var tracks = [];
  1506. var isAudio = this.type === JitsiTrack.AUDIO;
  1507. if (isAudio) {
  1508. tracks = this.stream.getAudioTracks();
  1509. } else {
  1510. if (!this.isActive())
  1511. return true;
  1512. tracks = this.stream.getVideoTracks();
  1513. }
  1514. for (var idx = 0; idx < tracks.length; idx++) {
  1515. if(tracks[idx].enabled)
  1516. return false;
  1517. }
  1518. return true;
  1519. };
  1520. /**
  1521. * Private method. Updates rtc property of the track.
  1522. * @param rtc the rtc instance.
  1523. */
  1524. JitsiLocalTrack.prototype._setRTC = function (rtc) {
  1525. this.rtc = rtc;
  1526. };
  1527. /**
  1528. * Return true;
  1529. */
  1530. JitsiLocalTrack.prototype.isLocal = function () {
  1531. return true;
  1532. }
  1533. module.exports = JitsiLocalTrack;
  1534. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils":18}],14:[function(require,module,exports){
  1535. var JitsiTrack = require("./JitsiTrack");
  1536. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1537. /**
  1538. * Represents a single media track (either audio or video).
  1539. * @param RTC the rtc instance.
  1540. * @param data object with the stream and some details about it(participant id, video type, etc.)
  1541. * @param sid sid for the Media Stream
  1542. * @param ssrc ssrc for the Media Stream
  1543. * @param eventEmitter the event emitter
  1544. * @constructor
  1545. */
  1546. function JitsiRemoteTrack(RTC, data, sid, ssrc) {
  1547. JitsiTrack.call(this, RTC, data.stream,
  1548. function () {
  1549. this.eventEmitter.emit(JitsiTrackEvents.TRACK_STOPPED);
  1550. }.bind(this));
  1551. this.rtc = RTC;
  1552. this.sid = sid;
  1553. this.stream = data.stream;
  1554. this.peerjid = data.peerjid;
  1555. this.videoType = data.videoType;
  1556. this.ssrc = ssrc;
  1557. this.muted = false;
  1558. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  1559. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  1560. this.muted = true;
  1561. }
  1562. }
  1563. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  1564. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  1565. /**
  1566. * Sets current muted status and fires an events for the change.
  1567. * @param value the muted status.
  1568. */
  1569. JitsiRemoteTrack.prototype.setMute = function (value) {
  1570. this.stream.muted = value;
  1571. this.muted = value;
  1572. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1573. };
  1574. /**
  1575. * Returns the current muted status of the track.
  1576. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  1577. */
  1578. JitsiRemoteTrack.prototype.isMuted = function () {
  1579. return this.muted;
  1580. };
  1581. /**
  1582. * Returns the participant id which owns the track.
  1583. * @returns {string} the id of the participants.
  1584. */
  1585. JitsiRemoteTrack.prototype.getParticipantId = function() {
  1586. return Strophe.getResourceFromJid(this.peerjid);
  1587. };
  1588. /**
  1589. * Return false;
  1590. */
  1591. JitsiRemoteTrack.prototype.isLocal = function () {
  1592. return false;
  1593. };
  1594. delete JitsiRemoteTrack.prototype.stop;
  1595. delete JitsiRemoteTrack.prototype.start;
  1596. module.exports = JitsiRemoteTrack;
  1597. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15}],15:[function(require,module,exports){
  1598. var RTCBrowserType = require("./RTCBrowserType");
  1599. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1600. var EventEmitter = require("events");
  1601. /**
  1602. * This implements 'onended' callback normally fired by WebRTC after the stream
  1603. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  1604. * @param jitsiTrack our track object holding the original WebRTC stream object
  1605. * to which 'onended' handling will be added.
  1606. */
  1607. function implementOnEndedHandling(jitsiTrack) {
  1608. var stream = jitsiTrack.getOriginalStream();
  1609. var originalStop = stream.stop;
  1610. stream.stop = function () {
  1611. originalStop.apply(stream);
  1612. if (jitsiTrack.isActive()) {
  1613. stream.onended();
  1614. }
  1615. };
  1616. }
  1617. /**
  1618. * Adds onended/oninactive handler to a MediaStream.
  1619. * @param mediaStream a MediaStream to attach onended/oninactive handler
  1620. * @param handler the handler
  1621. */
  1622. function addMediaStreamInactiveHandler(mediaStream, handler) {
  1623. if(RTCBrowserType.isTemasysPluginUsed()) {
  1624. // themasys
  1625. //FIXME: Seems that not working properly.
  1626. if(mediaStream.onended) {
  1627. mediaStream.onended = handler;
  1628. } else if(mediaStream.addEventListener) {
  1629. mediaStream.addEventListener('ended', function () {
  1630. handler(mediaStream);
  1631. });
  1632. } else if(mediaStream.attachEvent) {
  1633. mediaStream.attachEvent('ended', function () {
  1634. handler(mediaStream);
  1635. });
  1636. }
  1637. }
  1638. else {
  1639. if(typeof mediaStream.active !== "undefined")
  1640. mediaStream.oninactive = handler;
  1641. else
  1642. mediaStream.onended = handler;
  1643. }
  1644. }
  1645. /**
  1646. * Represents a single media track (either audio or video).
  1647. * @constructor
  1648. * @param rtc the rtc instance
  1649. * @param stream the stream
  1650. * @param streamInactiveHandler the function that will handle
  1651. * onended/oninactive events of the stream.
  1652. */
  1653. function JitsiTrack(rtc, stream, streamInactiveHandler)
  1654. {
  1655. /**
  1656. * Array with the HTML elements that are displaying the streams.
  1657. * @type {Array}
  1658. */
  1659. this.containers = [];
  1660. this.rtc = rtc;
  1661. this.stream = stream;
  1662. this.eventEmitter = new EventEmitter();
  1663. this.audioLevel = -1;
  1664. this.type = (this.stream.getVideoTracks().length > 0)?
  1665. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  1666. if(this.type == "audio") {
  1667. this._getTracks = function () {
  1668. return this.stream.getAudioTracks();
  1669. }.bind(this);
  1670. } else {
  1671. this._getTracks = function () {
  1672. return this.stream.getVideoTracks();
  1673. }.bind(this);
  1674. }
  1675. if (RTCBrowserType.isFirefox() && this.stream) {
  1676. implementOnEndedHandling(this);
  1677. }
  1678. if(stream)
  1679. addMediaStreamInactiveHandler(stream, streamInactiveHandler);
  1680. }
  1681. /**
  1682. * JitsiTrack video type.
  1683. * @type {string}
  1684. */
  1685. JitsiTrack.VIDEO = "video";
  1686. /**
  1687. * JitsiTrack audio type.
  1688. * @type {string}
  1689. */
  1690. JitsiTrack.AUDIO = "audio";
  1691. /**
  1692. * Returns the type (audio or video) of this track.
  1693. */
  1694. JitsiTrack.prototype.getType = function() {
  1695. return this.type;
  1696. };
  1697. /**
  1698. * Check if this is audiotrack.
  1699. */
  1700. JitsiTrack.prototype.isAudioTrack = function () {
  1701. return this.getType() === JitsiTrack.AUDIO;
  1702. };
  1703. /**
  1704. * Check if this is videotrack.
  1705. */
  1706. JitsiTrack.prototype.isVideoTrack = function () {
  1707. return this.getType() === JitsiTrack.VIDEO;
  1708. };
  1709. /**
  1710. * Returns the RTCMediaStream from the browser (?).
  1711. */
  1712. JitsiTrack.prototype.getOriginalStream = function() {
  1713. return this.stream;
  1714. }
  1715. /**
  1716. * Mutes the track.
  1717. */
  1718. JitsiTrack.prototype.mute = function () {
  1719. this._setMute(true);
  1720. }
  1721. /**
  1722. * Unmutes the stream.
  1723. */
  1724. JitsiTrack.prototype.unmute = function () {
  1725. this._setMute(false);
  1726. }
  1727. /**
  1728. * Attaches the MediaStream of this track to an HTML container (?).
  1729. * Adds the container to the list of containers that are displaying the track.
  1730. * @param container the HTML container
  1731. */
  1732. JitsiTrack.prototype.attach = function (container) {
  1733. if(this.stream)
  1734. require("./RTCUtils").attachMediaStream(container, this.stream);
  1735. this.containers.push(container);
  1736. }
  1737. /**
  1738. * Removes the track from the passed HTML container.
  1739. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  1740. */
  1741. JitsiTrack.prototype.detach = function (container) {
  1742. for(var i = 0; i < this.containers.length; i++)
  1743. {
  1744. if(this.containers[i].is(container))
  1745. {
  1746. this.containers.splice(i,1);
  1747. }
  1748. if(!container)
  1749. {
  1750. this.containers[i].find(">video").remove();
  1751. }
  1752. }
  1753. if(container)
  1754. $(container).find(">video").remove();
  1755. }
  1756. /**
  1757. * Stops sending the media track. And removes it from the HTML.
  1758. * NOTE: Works for local tracks only.
  1759. */
  1760. JitsiTrack.prototype.stop = function () {
  1761. }
  1762. /**
  1763. * Returns true if this is a video track and the source of the video is a
  1764. * screen capture as opposed to a camera.
  1765. */
  1766. JitsiTrack.prototype.isScreenSharing = function(){
  1767. }
  1768. /**
  1769. * Returns id of the track.
  1770. * @returns {string} id of the track or null if this is fake track.
  1771. */
  1772. JitsiTrack.prototype.getId = function () {
  1773. var tracks = this.stream.getTracks();
  1774. if(!tracks || tracks.length === 0)
  1775. return null;
  1776. return tracks[0].id;
  1777. };
  1778. /**
  1779. * Checks whether the MediaStream is avtive/not ended.
  1780. * When there is no check for active we don't have information and so
  1781. * will return that stream is active (in case of FF).
  1782. * @returns {boolean} whether MediaStream is active.
  1783. */
  1784. JitsiTrack.prototype.isActive = function () {
  1785. if((typeof this.stream.active !== "undefined"))
  1786. return this.stream.active;
  1787. else
  1788. return true;
  1789. };
  1790. /**
  1791. * Attaches a handler for events(For example - "audio level changed".).
  1792. * All possible event are defined in JitsiTrackEvents.
  1793. * @param eventId the event ID.
  1794. * @param handler handler for the event.
  1795. */
  1796. JitsiTrack.prototype.on = function (eventId, handler) {
  1797. if(this.eventEmitter)
  1798. this.eventEmitter.on(eventId, handler);
  1799. }
  1800. /**
  1801. * Removes event listener
  1802. * @param eventId the event ID.
  1803. * @param [handler] optional, the specific handler to unbind
  1804. */
  1805. JitsiTrack.prototype.off = function (eventId, handler) {
  1806. if(this.eventEmitter)
  1807. this.eventEmitter.removeListener(eventId, handler);
  1808. }
  1809. // Common aliases for event emitter
  1810. JitsiTrack.prototype.addEventListener = JitsiTrack.prototype.on;
  1811. JitsiTrack.prototype.removeEventListener = JitsiTrack.prototype.off;
  1812. /**
  1813. * Sets the audio level for the stream
  1814. * @param audioLevel the new audio level
  1815. */
  1816. JitsiTrack.prototype.setAudioLevel = function (audioLevel) {
  1817. if(this.audioLevel !== audioLevel) {
  1818. this.eventEmitter.emit(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1819. audioLevel);
  1820. this.audioLevel = audioLevel;
  1821. }
  1822. }
  1823. module.exports = JitsiTrack;
  1824. },{"../../JitsiTrackEvents":10,"./RTCBrowserType":17,"./RTCUtils":18,"events":44}],16:[function(require,module,exports){
  1825. /* global APP */
  1826. var EventEmitter = require("events");
  1827. var RTCBrowserType = require("./RTCBrowserType");
  1828. var RTCUtils = require("./RTCUtils.js");
  1829. var JitsiTrack = require("./JitsiTrack");
  1830. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  1831. var DataChannels = require("./DataChannels");
  1832. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  1833. var DesktopSharingEventTypes
  1834. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1835. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  1836. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  1837. function createLocalTracks(streams) {
  1838. var newStreams = []
  1839. for (var i = 0; i < streams.length; i++) {
  1840. var localStream = new JitsiLocalTrack(streams[i].stream,
  1841. streams[i].videoType, streams[i].resolution);
  1842. newStreams.push(localStream);
  1843. if (streams[i].isMuted === true)
  1844. localStream.setMute(true);
  1845. }
  1846. return newStreams;
  1847. }
  1848. function RTC(room, options) {
  1849. this.room = room;
  1850. this.localStreams = [];
  1851. //FIXME: we should start removing those streams.
  1852. //FIXME: We should support multiple streams per jid.
  1853. this.remoteStreams = {};
  1854. this.localAudio = null;
  1855. this.localVideo = null;
  1856. this.eventEmitter = new EventEmitter();
  1857. var self = this;
  1858. this.options = options || {};
  1859. room.addPresenceListener("videomuted", function (values, from) {
  1860. if(self.remoteStreams[from]) {
  1861. self.remoteStreams[from][JitsiTrack.VIDEO].setMute(values.value == "true");
  1862. }
  1863. });
  1864. room.addPresenceListener("audiomuted", function (values, from) {
  1865. if(self.remoteStreams[from]) {
  1866. self.remoteStreams[from][JitsiTrack.AUDIO].setMute(values.value == "true");
  1867. }
  1868. });
  1869. }
  1870. /**
  1871. * Creates the local MediaStreams.
  1872. * @param {Object} [options] optional parameters
  1873. * @param {Array} options.devices the devices that will be requested
  1874. * @param {string} options.resolution resolution constraints
  1875. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1876. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1877. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1878. * @param {string} options.cameraDeviceId
  1879. * @param {string} options.micDeviceId
  1880. * @returns {*} Promise object that will receive the new JitsiTracks
  1881. */
  1882. RTC.obtainAudioAndVideoPermissions = function (options) {
  1883. return RTCUtils.obtainAudioAndVideoPermissions(options).then(createLocalTracks);
  1884. }
  1885. RTC.prototype.onIncommingCall = function(event) {
  1886. if(this.options.config.openSctp)
  1887. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  1888. for(var i = 0; i < this.localStreams.length; i++)
  1889. if(this.localStreams[i])
  1890. {
  1891. this.room.addStream(this.localStreams[i].getOriginalStream(), function () {});
  1892. }
  1893. }
  1894. RTC.prototype.selectedEndpoint = function (id) {
  1895. if(this.dataChannels)
  1896. this.dataChannels.handleSelectedEndpointEvent(id);
  1897. }
  1898. RTC.prototype.pinEndpoint = function (id) {
  1899. if(this.dataChannels)
  1900. this.dataChannels.handlePinnedEndpointEvent(id);
  1901. }
  1902. RTC.prototype.addListener = function (type, listener) {
  1903. this.eventEmitter.on(type, listener);
  1904. };
  1905. RTC.prototype.removeListener = function (eventType, listener) {
  1906. this.eventEmitter.removeListener(eventType, listener);
  1907. };
  1908. RTC.addListener = function (eventType, listener) {
  1909. RTCUtils.addListener(eventType, listener);
  1910. }
  1911. RTC.removeListener = function (eventType, listener) {
  1912. RTCUtils.removeListener(eventType, listener)
  1913. }
  1914. RTC.isRTCReady = function () {
  1915. return RTCUtils.isRTCReady();
  1916. }
  1917. RTC.init = function (options) {
  1918. this.options = options || {};
  1919. return RTCUtils.init(this.options);
  1920. }
  1921. RTC.getDeviceAvailability = function () {
  1922. return RTCUtils.getDeviceAvailability();
  1923. }
  1924. RTC.prototype.addLocalStream = function (stream) {
  1925. this.localStreams.push(stream);
  1926. stream._setRTC(this);
  1927. if (stream.type == "audio") {
  1928. this.localAudio = stream;
  1929. } else {
  1930. this.localVideo = stream;
  1931. }
  1932. };
  1933. RTC.prototype.removeLocalStream = function (stream) {
  1934. for(var i = 0; i < this.localStreams.length; i++) {
  1935. if(this.localStreams[i].getOriginalStream() === stream) {
  1936. delete this.localStreams[i];
  1937. return;
  1938. }
  1939. }
  1940. };
  1941. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  1942. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc);
  1943. if(!data.peerjid)
  1944. return;
  1945. var jid = data.peerjid;
  1946. if(!this.remoteStreams[jid]) {
  1947. this.remoteStreams[jid] = {};
  1948. }
  1949. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  1950. return remoteStream;
  1951. };
  1952. RTC.getPCConstraints = function () {
  1953. return RTCUtils.pc_constraints;
  1954. };
  1955. RTC.attachMediaStream = function (elSelector, stream) {
  1956. RTCUtils.attachMediaStream(elSelector, stream);
  1957. };
  1958. RTC.getStreamID = function (stream) {
  1959. return RTCUtils.getStreamID(stream);
  1960. };
  1961. RTC.getVideoSrc = function (element) {
  1962. return RTCUtils.getVideoSrc(element);
  1963. };
  1964. /**
  1965. * Returns true if retrieving the the list of input devices is supported and
  1966. * false if not.
  1967. */
  1968. RTC.isDeviceListAvailable = function () {
  1969. return RTCUtils.isDeviceListAvailable();
  1970. };
  1971. /**
  1972. * Returns true if changing the camera / microphone device is supported and
  1973. * false if not.
  1974. */
  1975. RTC.isDeviceChangeAvailable = function () {
  1976. return RTCUtils.isDeviceChangeAvailable();
  1977. }
  1978. /**
  1979. * Allows to receive list of available cameras/microphones.
  1980. * @param {function} callback would receive array of devices as an argument
  1981. */
  1982. RTC.enumerateDevices = function (callback) {
  1983. RTCUtils.enumerateDevices(callback);
  1984. };
  1985. RTC.setVideoSrc = function (element, src) {
  1986. RTCUtils.setVideoSrc(element, src);
  1987. };
  1988. /**
  1989. * A method to handle stopping of the stream.
  1990. * One point to handle the differences in various implementations.
  1991. * @param mediaStream MediaStream object to stop.
  1992. */
  1993. RTC.stopMediaStream = function (mediaStream) {
  1994. RTCUtils.stopMediaStream(mediaStream);
  1995. };
  1996. RTC.prototype.getVideoElementName = function () {
  1997. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  1998. };
  1999. RTC.prototype.dispose = function() {
  2000. };
  2001. RTC.prototype.switchVideoStreams = function (newStream) {
  2002. this.localVideo.stream = newStream;
  2003. this.localStreams = [];
  2004. //in firefox we have only one stream object
  2005. if (this.localAudio.getOriginalStream() != newStream)
  2006. this.localStreams.push(this.localAudio);
  2007. this.localStreams.push(this.localVideo);
  2008. };
  2009. RTC.prototype.setAudioLevel = function (jid, audioLevel) {
  2010. if(this.remoteStreams[jid] && this.remoteStreams[jid][JitsiTrack.AUDIO])
  2011. this.remoteStreams[jid][JitsiTrack.AUDIO].setAudioLevel(audioLevel);
  2012. }
  2013. module.exports = RTC;
  2014. },{"../../service/RTC/MediaStreamTypes":79,"../../service/RTC/RTCEvents.js":80,"../../service/desktopsharing/DesktopSharingEventTypes":84,"./DataChannels":12,"./JitsiLocalTrack.js":13,"./JitsiRemoteTrack.js":14,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils.js":18,"events":44}],17:[function(require,module,exports){
  2015. var currentBrowser;
  2016. var browserVersion;
  2017. var isAndroid;
  2018. var RTCBrowserType = {
  2019. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  2020. RTC_BROWSER_OPERA: "rtc_browser.opera",
  2021. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  2022. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  2023. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  2024. getBrowserType: function () {
  2025. return currentBrowser;
  2026. },
  2027. isChrome: function () {
  2028. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  2029. },
  2030. isOpera: function () {
  2031. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  2032. },
  2033. isFirefox: function () {
  2034. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  2035. },
  2036. isIExplorer: function () {
  2037. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2038. },
  2039. isSafari: function () {
  2040. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  2041. },
  2042. isTemasysPluginUsed: function () {
  2043. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  2044. },
  2045. getFirefoxVersion: function () {
  2046. return RTCBrowserType.isFirefox() ? browserVersion : null;
  2047. },
  2048. getChromeVersion: function () {
  2049. return RTCBrowserType.isChrome() ? browserVersion : null;
  2050. },
  2051. usesPlanB: function() {
  2052. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  2053. RTCBrowserType.isTemasysPluginUsed();
  2054. },
  2055. usesUnifiedPlan: function() {
  2056. return RTCBrowserType.isFirefox();
  2057. },
  2058. /**
  2059. * Whether the browser is running on an android device.
  2060. */
  2061. isAndroid: function() {
  2062. return isAndroid;
  2063. }
  2064. // Add version getters for other browsers when needed
  2065. };
  2066. // detectOpera() must be called before detectChrome() !!!
  2067. // otherwise Opera wil be detected as Chrome
  2068. function detectChrome() {
  2069. if (navigator.webkitGetUserMedia) {
  2070. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  2071. var userAgent = navigator.userAgent.toLowerCase();
  2072. // We can assume that user agent is chrome, because it's
  2073. // enforced when 'ext' streaming method is set
  2074. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  2075. console.log("This appears to be Chrome, ver: " + ver);
  2076. return ver;
  2077. }
  2078. return null;
  2079. }
  2080. function detectOpera() {
  2081. var userAgent = navigator.userAgent;
  2082. if (userAgent.match(/Opera|OPR/)) {
  2083. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  2084. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  2085. console.info("This appears to be Opera, ver: " + version);
  2086. return version;
  2087. }
  2088. return null;
  2089. }
  2090. function detectFirefox() {
  2091. if (navigator.mozGetUserMedia) {
  2092. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  2093. var version = parseInt(
  2094. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2095. console.log('This appears to be Firefox, ver: ' + version);
  2096. return version;
  2097. }
  2098. return null;
  2099. }
  2100. function detectSafari() {
  2101. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  2102. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  2103. console.info("This appears to be Safari");
  2104. // FIXME detect Safari version when needed
  2105. return 1;
  2106. }
  2107. return null;
  2108. }
  2109. function detectIE() {
  2110. var version;
  2111. var ua = window.navigator.userAgent;
  2112. var msie = ua.indexOf('MSIE ');
  2113. if (msie > 0) {
  2114. // IE 10 or older => return version number
  2115. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  2116. }
  2117. var trident = ua.indexOf('Trident/');
  2118. if (!version && trident > 0) {
  2119. // IE 11 => return version number
  2120. var rv = ua.indexOf('rv:');
  2121. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  2122. }
  2123. var edge = ua.indexOf('Edge/');
  2124. if (!version && edge > 0) {
  2125. // IE 12 => return version number
  2126. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  2127. }
  2128. if (version) {
  2129. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2130. console.info("This appears to be IExplorer, ver: " + version);
  2131. }
  2132. return version;
  2133. }
  2134. function detectBrowser() {
  2135. var version;
  2136. var detectors = [
  2137. detectOpera,
  2138. detectChrome,
  2139. detectFirefox,
  2140. detectIE,
  2141. detectSafari
  2142. ];
  2143. // Try all browser detectors
  2144. for (var i = 0; i < detectors.length; i++) {
  2145. version = detectors[i]();
  2146. if (version)
  2147. return version;
  2148. }
  2149. console.warn("Browser type defaults to Safari ver 1");
  2150. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  2151. return 1;
  2152. }
  2153. browserVersion = detectBrowser();
  2154. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  2155. module.exports = RTCBrowserType;
  2156. },{}],18:[function(require,module,exports){
  2157. (function (__filename){
  2158. /* global config, require, attachMediaStream, getUserMedia,
  2159. RTCPeerConnection, RTCSessionDescription, RTCIceCandidate, MediaStreamTrack,
  2160. mozRTCPeerConnection, mozRTCSessionDescription, mozRTCIceCandidate,
  2161. webkitRTCPeerConnection, webkitMediaStream, webkitURL
  2162. */
  2163. /* jshint -W101 */
  2164. var logger = require("jitsi-meet-logger").getLogger(__filename);
  2165. var RTCBrowserType = require("./RTCBrowserType");
  2166. var Resolutions = require("../../service/RTC/Resolutions");
  2167. var RTCEvents = require("../../service/RTC/RTCEvents");
  2168. var AdapterJS = require("./adapter.screenshare");
  2169. var SDPUtil = require("../xmpp/SDPUtil");
  2170. var EventEmitter = require("events");
  2171. var screenObtainer = require("./ScreenObtainer");
  2172. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  2173. var eventEmitter = new EventEmitter();
  2174. var devices = {
  2175. audio: true,
  2176. video: true
  2177. };
  2178. var rtcReady = false;
  2179. function setResolutionConstraints(constraints, resolution) {
  2180. var isAndroid = RTCBrowserType.isAndroid();
  2181. if (Resolutions[resolution]) {
  2182. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  2183. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  2184. }
  2185. else if (isAndroid) {
  2186. // FIXME can't remember if the purpose of this was to always request
  2187. // low resolution on Android ? if yes it should be moved up front
  2188. constraints.video.mandatory.minWidth = 320;
  2189. constraints.video.mandatory.minHeight = 240;
  2190. constraints.video.mandatory.maxFrameRate = 15;
  2191. }
  2192. if (constraints.video.mandatory.minWidth)
  2193. constraints.video.mandatory.maxWidth =
  2194. constraints.video.mandatory.minWidth;
  2195. if (constraints.video.mandatory.minHeight)
  2196. constraints.video.mandatory.maxHeight =
  2197. constraints.video.mandatory.minHeight;
  2198. }
  2199. /**
  2200. * @param {string[]} um required user media types
  2201. *
  2202. * @param {Object} [options={}] optional parameters
  2203. * @param {string} options.resolution
  2204. * @param {number} options.bandwidth
  2205. * @param {number} options.fps
  2206. * @param {string} options.desktopStream
  2207. * @param {string} options.cameraDeviceId
  2208. * @param {string} options.micDeviceId
  2209. * @param {bool} firefox_fake_device
  2210. */
  2211. function getConstraints(um, options) {
  2212. var constraints = {audio: false, video: false};
  2213. if (um.indexOf('video') >= 0) {
  2214. // same behaviour as true
  2215. constraints.video = { mandatory: {}, optional: [] };
  2216. if (options.cameraDeviceId) {
  2217. constraints.video.optional.push({
  2218. sourceId: options.cameraDeviceId
  2219. });
  2220. }
  2221. constraints.video.optional.push({ googLeakyBucket: true });
  2222. setResolutionConstraints(constraints, options.resolution);
  2223. }
  2224. if (um.indexOf('audio') >= 0) {
  2225. if (!RTCBrowserType.isFirefox()) {
  2226. // same behaviour as true
  2227. constraints.audio = { mandatory: {}, optional: []};
  2228. if (options.micDeviceId) {
  2229. constraints.audio.optional.push({
  2230. sourceId: options.micDeviceId
  2231. });
  2232. }
  2233. // if it is good enough for hangouts...
  2234. constraints.audio.optional.push(
  2235. {googEchoCancellation: true},
  2236. {googAutoGainControl: true},
  2237. {googNoiseSupression: true},
  2238. {googHighpassFilter: true},
  2239. {googNoisesuppression2: true},
  2240. {googEchoCancellation2: true},
  2241. {googAutoGainControl2: true}
  2242. );
  2243. } else {
  2244. if (options.micDeviceId) {
  2245. constraints.audio = {
  2246. mandatory: {},
  2247. optional: [{
  2248. sourceId: options.micDeviceId
  2249. }]};
  2250. } else {
  2251. constraints.audio = true;
  2252. }
  2253. }
  2254. }
  2255. if (um.indexOf('screen') >= 0) {
  2256. if (RTCBrowserType.isChrome()) {
  2257. constraints.video = {
  2258. mandatory: {
  2259. chromeMediaSource: "screen",
  2260. googLeakyBucket: true,
  2261. maxWidth: window.screen.width,
  2262. maxHeight: window.screen.height,
  2263. maxFrameRate: 3
  2264. },
  2265. optional: []
  2266. };
  2267. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  2268. constraints.video = {
  2269. optional: [
  2270. {
  2271. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  2272. }
  2273. ]
  2274. };
  2275. } else if (RTCBrowserType.isFirefox()) {
  2276. constraints.video = {
  2277. mozMediaSource: "window",
  2278. mediaSource: "window"
  2279. };
  2280. } else {
  2281. logger.error(
  2282. "'screen' WebRTC media source is supported only in Chrome" +
  2283. " and with Temasys plugin");
  2284. }
  2285. }
  2286. if (um.indexOf('desktop') >= 0) {
  2287. constraints.video = {
  2288. mandatory: {
  2289. chromeMediaSource: "desktop",
  2290. chromeMediaSourceId: options.desktopStream,
  2291. googLeakyBucket: true,
  2292. maxWidth: window.screen.width,
  2293. maxHeight: window.screen.height,
  2294. maxFrameRate: 3
  2295. },
  2296. optional: []
  2297. };
  2298. }
  2299. if (options.bandwidth) {
  2300. if (!constraints.video) {
  2301. //same behaviour as true
  2302. constraints.video = {mandatory: {}, optional: []};
  2303. }
  2304. constraints.video.optional.push({bandwidth: options.bandwidth});
  2305. }
  2306. if (options.fps) {
  2307. // for some cameras it might be necessary to request 30fps
  2308. // so they choose 30fps mjpg over 10fps yuy2
  2309. if (!constraints.video) {
  2310. // same behaviour as true;
  2311. constraints.video = {mandatory: {}, optional: []};
  2312. }
  2313. constraints.video.mandatory.minFrameRate = options.fps;
  2314. }
  2315. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  2316. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  2317. // this later can be a problem with some of the tests
  2318. if(RTCBrowserType.isFirefox() && options.firefox_fake_device)
  2319. {
  2320. // seems to be fixed now, removing this experimental fix, as having
  2321. // multiple audio tracks brake the tests
  2322. //constraints.audio = true;
  2323. constraints.fake = true;
  2324. }
  2325. return constraints;
  2326. }
  2327. function setAvailableDevices(um, available) {
  2328. if (um.indexOf("video") != -1) {
  2329. devices.video = available;
  2330. }
  2331. if (um.indexOf("audio") != -1) {
  2332. devices.audio = available;
  2333. }
  2334. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  2335. }
  2336. // In case of IE we continue from 'onReady' callback
  2337. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  2338. // once it is initialized.
  2339. function onReady (options, GUM) {
  2340. rtcReady = true;
  2341. eventEmitter.emit(RTCEvents.RTC_READY, true);
  2342. screenObtainer.init(eventEmitter, options, GUM);
  2343. }
  2344. /**
  2345. * Apply function with arguments if function exists.
  2346. * Do nothing if function not provided.
  2347. * @param {function} [fn] function to apply
  2348. * @param {Array} [args=[]] arguments for function
  2349. */
  2350. function maybeApply(fn, args) {
  2351. if (fn) {
  2352. fn.apply(null, args || []);
  2353. }
  2354. }
  2355. var getUserMediaStatus = {
  2356. initialized: false,
  2357. callbacks: []
  2358. };
  2359. /**
  2360. * Wrap `getUserMedia` to allow others to know if it was executed at least
  2361. * once or not. Wrapper function uses `getUserMediaStatus` object.
  2362. * @param {Function} getUserMedia native function
  2363. * @returns {Function} wrapped function
  2364. */
  2365. function wrapGetUserMedia(getUserMedia) {
  2366. return function (constraints, successCallback, errorCallback) {
  2367. getUserMedia(constraints, function (stream) {
  2368. maybeApply(successCallback, [stream]);
  2369. if (!getUserMediaStatus.initialized) {
  2370. getUserMediaStatus.initialized = true;
  2371. getUserMediaStatus.callbacks.forEach(function (callback) {
  2372. callback();
  2373. });
  2374. getUserMediaStatus.callbacks.length = 0;
  2375. }
  2376. }, function (error) {
  2377. maybeApply(errorCallback, [error]);
  2378. });
  2379. };
  2380. }
  2381. /**
  2382. * Create stub device which equals to auto selected device.
  2383. * @param {string} kind if that should be `audio` or `video` device
  2384. * @returns {Object} stub device description in `enumerateDevices` format
  2385. */
  2386. function createAutoDeviceInfo(kind) {
  2387. return {
  2388. facing: null,
  2389. label: 'Auto',
  2390. kind: kind,
  2391. deviceId: '',
  2392. groupId: null
  2393. };
  2394. }
  2395. /**
  2396. * Execute function after getUserMedia was executed at least once.
  2397. * @param {Function} callback function to execute after getUserMedia
  2398. */
  2399. function afterUserMediaInitialized(callback) {
  2400. if (getUserMediaStatus.initialized) {
  2401. callback();
  2402. } else {
  2403. getUserMediaStatus.callbacks.push(callback);
  2404. }
  2405. }
  2406. /**
  2407. * Wrapper function which makes enumerateDevices to wait
  2408. * until someone executes getUserMedia first time.
  2409. * @param {Function} enumerateDevices native function
  2410. * @returns {Funtion} wrapped function
  2411. */
  2412. function wrapEnumerateDevices(enumerateDevices) {
  2413. return function (callback) {
  2414. // enumerate devices only after initial getUserMedia
  2415. afterUserMediaInitialized(function () {
  2416. enumerateDevices().then(function (devices) {
  2417. //add auto devices
  2418. devices.unshift(
  2419. createAutoDeviceInfo('audioinput'),
  2420. createAutoDeviceInfo('videoinput')
  2421. );
  2422. callback(devices);
  2423. }, function (err) {
  2424. console.error('cannot enumerate devices: ', err);
  2425. // return only auto devices
  2426. callback([createAutoDeviceInfo('audioInput'),
  2427. createAutoDeviceInfo('videoinput')]);
  2428. });
  2429. });
  2430. };
  2431. }
  2432. /**
  2433. * Use old MediaStreamTrack to get devices list and
  2434. * convert it to enumerateDevices format.
  2435. * @param {Function} callback function to call when received devices list.
  2436. */
  2437. function enumerateDevicesThroughMediaStreamTrack (callback) {
  2438. MediaStreamTrack.getSources(function (sources) {
  2439. var devices = sources.map(function (source) {
  2440. var kind = (source.kind || '').toLowerCase();
  2441. return {
  2442. facing: source.facing || null,
  2443. label: source.label,
  2444. kind: kind ? kind + 'input': null,
  2445. deviceId: source.id,
  2446. groupId: source.groupId || null
  2447. };
  2448. });
  2449. //add auto devices
  2450. devices.unshift(
  2451. createAutoDeviceInfo('audioinput'),
  2452. createAutoDeviceInfo('videoinput')
  2453. );
  2454. callback(devices);
  2455. });
  2456. }
  2457. function obtainDevices(options) {
  2458. if(!options.devices || options.devices.length === 0) {
  2459. return options.successCallback(options.streams || {});
  2460. }
  2461. var device = options.devices.splice(0, 1);
  2462. options.deviceGUM[device](function (stream) {
  2463. options.streams = options.streams || {};
  2464. options.streams[device] = stream;
  2465. obtainDevices(options);
  2466. },
  2467. function (error) {
  2468. logger.error(
  2469. "failed to obtain " + device + " stream - stop", error);
  2470. options.errorCallback(JitsiTrackErrors.parseError(error));
  2471. });
  2472. }
  2473. /**
  2474. * Handles the newly created Media Streams.
  2475. * @param streams the new Media Streams
  2476. * @param resolution the resolution of the video streams
  2477. * @returns {*[]} object that describes the new streams
  2478. */
  2479. function handleLocalStream(streams, resolution) {
  2480. var audioStream, videoStream, desktopStream, res = [];
  2481. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  2482. // an object with two properties: audioStream, videoStream.
  2483. if (window.webkitMediaStream) {
  2484. var audioVideo = streams.audioVideo;
  2485. if (audioVideo) {
  2486. var audioTracks = audioVideo.getAudioTracks();
  2487. if(audioTracks.length) {
  2488. audioStream = new webkitMediaStream();
  2489. for (var i = 0; i < audioTracks.length; i++) {
  2490. audioStream.addTrack(audioTracks[i]);
  2491. }
  2492. }
  2493. var videoTracks = audioVideo.getVideoTracks();
  2494. if(videoTracks.length) {
  2495. videoStream = new webkitMediaStream();
  2496. for (var j = 0; j < videoTracks.length; j++) {
  2497. videoStream.addTrack(videoTracks[j]);
  2498. }
  2499. }
  2500. }
  2501. if (streams && streams.desktopStream)
  2502. desktopStream = streams.desktopStream;
  2503. }
  2504. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  2505. if (streams && streams.audio)
  2506. audioStream = streams.audio;
  2507. if (streams && streams.video)
  2508. videoStream = streams.video;
  2509. if(streams && streams.desktop)
  2510. desktopStream = streams.desktop;
  2511. }
  2512. if (desktopStream)
  2513. res.push({stream: desktopStream,
  2514. type: "video", videoType: "desktop"});
  2515. if(audioStream)
  2516. res.push({stream: audioStream, type: "audio", videoType: null});
  2517. if(videoStream)
  2518. res.push({stream: videoStream, type: "video", videoType: "camera",
  2519. resolution: resolution});
  2520. return res;
  2521. }
  2522. //Options parameter is to pass config options. Currently uses only "useIPv6".
  2523. var RTCUtils = {
  2524. init: function (options) {
  2525. return new Promise(function(resolve, reject) {
  2526. if (RTCBrowserType.isFirefox()) {
  2527. var FFversion = RTCBrowserType.getFirefoxVersion();
  2528. if (FFversion < 40) {
  2529. logger.error(
  2530. "Firefox version too old: " + FFversion +
  2531. ". Required >= 40.");
  2532. reject(new Error("Firefox version too old: " + FFversion +
  2533. ". Required >= 40."));
  2534. return;
  2535. }
  2536. this.peerconnection = mozRTCPeerConnection;
  2537. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  2538. this.enumerateDevices = wrapEnumerateDevices(
  2539. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2540. );
  2541. this.pc_constraints = {};
  2542. this.attachMediaStream = function (element, stream) {
  2543. // srcObject is being standardized and FF will eventually
  2544. // support that unprefixed. FF also supports the
  2545. // "element.src = URL.createObjectURL(...)" combo, but that
  2546. // will be deprecated in favour of srcObject.
  2547. //
  2548. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  2549. // https://github.com/webrtc/samples/issues/302
  2550. if (!element[0])
  2551. return;
  2552. element[0].mozSrcObject = stream;
  2553. element[0].play();
  2554. };
  2555. this.getStreamID = function (stream) {
  2556. var id = stream.id;
  2557. if (!id) {
  2558. var tracks = stream.getVideoTracks();
  2559. if (!tracks || tracks.length === 0) {
  2560. tracks = stream.getAudioTracks();
  2561. }
  2562. id = tracks[0].id;
  2563. }
  2564. return SDPUtil.filter_special_chars(id);
  2565. };
  2566. this.getVideoSrc = function (element) {
  2567. if (!element)
  2568. return null;
  2569. return element.mozSrcObject;
  2570. };
  2571. this.setVideoSrc = function (element, src) {
  2572. if (element)
  2573. element.mozSrcObject = src;
  2574. };
  2575. RTCSessionDescription = mozRTCSessionDescription;
  2576. RTCIceCandidate = mozRTCIceCandidate;
  2577. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  2578. this.peerconnection = webkitRTCPeerConnection;
  2579. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2580. if (navigator.mediaDevices) {
  2581. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  2582. this.enumerateDevices = wrapEnumerateDevices(
  2583. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2584. );
  2585. } else {
  2586. this.getUserMedia = getUserMedia;
  2587. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2588. }
  2589. this.attachMediaStream = function (element, stream) {
  2590. element.attr('src', webkitURL.createObjectURL(stream));
  2591. };
  2592. this.getStreamID = function (stream) {
  2593. // streams from FF endpoints have the characters '{' and '}'
  2594. // that make jQuery choke.
  2595. return SDPUtil.filter_special_chars(stream.id);
  2596. };
  2597. this.getVideoSrc = function (element) {
  2598. if (!element)
  2599. return null;
  2600. return element.getAttribute("src");
  2601. };
  2602. this.setVideoSrc = function (element, src) {
  2603. if (element)
  2604. element.setAttribute("src", src);
  2605. };
  2606. // DTLS should now be enabled by default but..
  2607. this.pc_constraints = {'optional': [
  2608. {'DtlsSrtpKeyAgreement': 'true'}
  2609. ]};
  2610. if (options.useIPv6) {
  2611. // https://code.google.com/p/webrtc/issues/detail?id=2828
  2612. this.pc_constraints.optional.push({googIPv6: true});
  2613. }
  2614. if (RTCBrowserType.isAndroid()) {
  2615. this.pc_constraints = {}; // disable DTLS on Android
  2616. }
  2617. if (!webkitMediaStream.prototype.getVideoTracks) {
  2618. webkitMediaStream.prototype.getVideoTracks = function () {
  2619. return this.videoTracks;
  2620. };
  2621. }
  2622. if (!webkitMediaStream.prototype.getAudioTracks) {
  2623. webkitMediaStream.prototype.getAudioTracks = function () {
  2624. return this.audioTracks;
  2625. };
  2626. }
  2627. }
  2628. // Detect IE/Safari
  2629. else if (RTCBrowserType.isTemasysPluginUsed()) {
  2630. //AdapterJS.WebRTCPlugin.setLogLevel(
  2631. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  2632. var self = this;
  2633. AdapterJS.webRTCReady(function (isPlugin) {
  2634. self.peerconnection = RTCPeerConnection;
  2635. self.getUserMedia = window.getUserMedia;
  2636. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2637. self.attachMediaStream = function (elSel, stream) {
  2638. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  2639. return;
  2640. }
  2641. attachMediaStream(elSel[0], stream);
  2642. };
  2643. self.getStreamID = function (stream) {
  2644. var id = SDPUtil.filter_special_chars(stream.label);
  2645. return id;
  2646. };
  2647. self.getVideoSrc = function (element) {
  2648. if (!element) {
  2649. logger.warn("Attempt to get video SRC of null element");
  2650. return null;
  2651. }
  2652. var children = element.children;
  2653. for (var i = 0; i !== children.length; ++i) {
  2654. if (children[i].name === 'streamId') {
  2655. return children[i].value;
  2656. }
  2657. }
  2658. //logger.info(element.id + " SRC: " + src);
  2659. return null;
  2660. };
  2661. self.setVideoSrc = function (element, src) {
  2662. //logger.info("Set video src: ", element, src);
  2663. if (!src) {
  2664. logger.warn("Not attaching video stream, 'src' is null");
  2665. return;
  2666. }
  2667. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2668. var stream = AdapterJS.WebRTCPlugin.plugin
  2669. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  2670. attachMediaStream(element, stream);
  2671. };
  2672. onReady(options, self.getUserMediaWithConstraints);
  2673. resolve();
  2674. });
  2675. } else {
  2676. try {
  2677. logger.error('Browser does not appear to be WebRTC-capable');
  2678. } catch (e) {
  2679. }
  2680. reject('Browser does not appear to be WebRTC-capable');
  2681. return;
  2682. }
  2683. // Call onReady() if Temasys plugin is not used
  2684. if (!RTCBrowserType.isTemasysPluginUsed()) {
  2685. onReady(options, this.getUserMediaWithConstraints);
  2686. resolve();
  2687. }
  2688. }.bind(this));
  2689. },
  2690. /**
  2691. * @param {string[]} um required user media types
  2692. * @param {function} success_callback
  2693. * @param {Function} failure_callback
  2694. * @param {Object} [options] optional parameters
  2695. * @param {string} options.resolution
  2696. * @param {number} options.bandwidth
  2697. * @param {number} options.fps
  2698. * @param {string} options.desktopStream
  2699. * @param {string} options.cameraDeviceId
  2700. * @param {string} options.micDeviceId
  2701. **/
  2702. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  2703. options = options || {};
  2704. var resolution = options.resolution;
  2705. var constraints = getConstraints(um, options);
  2706. logger.info("Get media constraints", constraints);
  2707. try {
  2708. this.getUserMedia(constraints,
  2709. function (stream) {
  2710. logger.log('onUserMediaSuccess');
  2711. setAvailableDevices(um, true);
  2712. success_callback(stream);
  2713. },
  2714. function (error) {
  2715. setAvailableDevices(um, false);
  2716. logger.warn('Failed to get access to local media. Error ',
  2717. error, constraints);
  2718. if (failure_callback) {
  2719. failure_callback(error, resolution);
  2720. }
  2721. });
  2722. } catch (e) {
  2723. logger.error('GUM failed: ', e);
  2724. if (failure_callback) {
  2725. failure_callback(e);
  2726. }
  2727. }
  2728. },
  2729. /**
  2730. * Creates the local MediaStreams.
  2731. * @param {Object} [options] optional parameters
  2732. * @param {Array} options.devices the devices that will be requested
  2733. * @param {string} options.resolution resolution constraints
  2734. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2735. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2736. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2737. * @param {string} options.cameraDeviceId
  2738. * @param {string} options.micDeviceId
  2739. * @returns {*} Promise object that will receive the new JitsiTracks
  2740. */
  2741. obtainAudioAndVideoPermissions: function (options) {
  2742. var self = this;
  2743. options = options || {};
  2744. return new Promise(function (resolve, reject) {
  2745. var successCallback = function (stream) {
  2746. resolve(handleLocalStream(stream, options.resolution));
  2747. };
  2748. options.devices = options.devices || ['audio', 'video'];
  2749. if(!screenObtainer.isSupported()
  2750. && options.devices.indexOf("desktop") !== -1){
  2751. reject(new Error("Desktop sharing is not supported!"));
  2752. }
  2753. if (RTCBrowserType.isFirefox() ||
  2754. RTCBrowserType.isTemasysPluginUsed()) {
  2755. var GUM = function (device, s, e) {
  2756. this.getUserMediaWithConstraints(device, s, e, options);
  2757. };
  2758. var deviceGUM = {
  2759. "audio": GUM.bind(self, ["audio"]),
  2760. "video": GUM.bind(self, ["video"]),
  2761. "desktop": screenObtainer.obtainStream
  2762. };
  2763. // With FF/IE we can't split the stream into audio and video because FF
  2764. // doesn't support media stream constructors. So, we need to get the
  2765. // audio stream separately from the video stream using two distinct GUM
  2766. // calls. Not very user friendly :-( but we don't have many other
  2767. // options neither.
  2768. //
  2769. // Note that we pack those 2 streams in a single object and pass it to
  2770. // the successCallback method.
  2771. obtainDevices({
  2772. devices: options.devices,
  2773. streams: [],
  2774. successCallback: successCallback,
  2775. errorCallback: reject,
  2776. deviceGUM: deviceGUM
  2777. });
  2778. } else {
  2779. var hasDesktop = options.devices.indexOf('desktop') > -1;
  2780. if (hasDesktop) {
  2781. options.devices.splice(options.devices.indexOf("desktop"), 1);
  2782. }
  2783. options.resolution = options.resolution || '360';
  2784. if(options.devices.length) {
  2785. this.getUserMediaWithConstraints(
  2786. options.devices,
  2787. function (stream) {
  2788. if(hasDesktop) {
  2789. screenObtainer.obtainStream(
  2790. function (desktopStream) {
  2791. successCallback({audioVideo: stream,
  2792. desktopStream: desktopStream});
  2793. }, function (error) {
  2794. reject(
  2795. JitsiTrackErrors.parseError(error));
  2796. });
  2797. } else {
  2798. successCallback({audioVideo: stream});
  2799. }
  2800. },
  2801. function (error) {
  2802. reject(JitsiTrackErrors.parseError(error));
  2803. },
  2804. options);
  2805. } else if (hasDesktop) {
  2806. screenObtainer.obtainStream(
  2807. function (stream) {
  2808. successCallback({desktopStream: stream});
  2809. }, function (error) {
  2810. reject(
  2811. JitsiTrackErrors.parseError(error));
  2812. });
  2813. }
  2814. }
  2815. }.bind(this));
  2816. },
  2817. addListener: function (eventType, listener) {
  2818. eventEmitter.on(eventType, listener);
  2819. },
  2820. removeListener: function (eventType, listener) {
  2821. eventEmitter.removeListener(eventType, listener);
  2822. },
  2823. getDeviceAvailability: function () {
  2824. return devices;
  2825. },
  2826. isRTCReady: function () {
  2827. return rtcReady;
  2828. },
  2829. /**
  2830. * Checks if its possible to enumerate available cameras/micropones.
  2831. * @returns {boolean} true if available, false otherwise.
  2832. */
  2833. isDeviceListAvailable: function () {
  2834. var isEnumerateDevicesAvailable = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  2835. if (isEnumerateDevicesAvailable) {
  2836. return true;
  2837. }
  2838. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  2839. },
  2840. /**
  2841. * Returns true if changing the camera / microphone device is supported and
  2842. * false if not.
  2843. */
  2844. isDeviceChangeAvailable: function () {
  2845. if(RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  2846. RTCBrowserType.isTemasysPluginUsed())
  2847. return true;
  2848. return false;
  2849. },
  2850. /**
  2851. * A method to handle stopping of the stream.
  2852. * One point to handle the differences in various implementations.
  2853. * @param mediaStream MediaStream object to stop.
  2854. */
  2855. stopMediaStream: function (mediaStream) {
  2856. mediaStream.getTracks().forEach(function (track) {
  2857. // stop() not supported with IE
  2858. if (track.stop) {
  2859. track.stop();
  2860. }
  2861. });
  2862. // leave stop for implementation still using it
  2863. if (mediaStream.stop) {
  2864. mediaStream.stop();
  2865. }
  2866. }
  2867. };
  2868. module.exports = RTCUtils;
  2869. }).call(this,"/modules/RTC/RTCUtils.js")
  2870. },{"../../JitsiTrackErrors":9,"../../service/RTC/RTCEvents":80,"../../service/RTC/Resolutions":81,"../xmpp/SDPUtil":32,"./RTCBrowserType":17,"./ScreenObtainer":19,"./adapter.screenshare":20,"events":44,"jitsi-meet-logger":48}],19:[function(require,module,exports){
  2871. (function (__filename){
  2872. /* global chrome, $, alert */
  2873. /* jshint -W003 */
  2874. var logger = require("jitsi-meet-logger").getLogger(__filename);
  2875. var RTCBrowserType = require("./RTCBrowserType");
  2876. var AdapterJS = require("./adapter.screenshare");
  2877. var DesktopSharingEventTypes
  2878. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2879. /**
  2880. * Indicates whether the Chrome desktop sharing extension is installed.
  2881. * @type {boolean}
  2882. */
  2883. var chromeExtInstalled = false;
  2884. /**
  2885. * Indicates whether an update of the Chrome desktop sharing extension is
  2886. * required.
  2887. * @type {boolean}
  2888. */
  2889. var chromeExtUpdateRequired = false;
  2890. /**
  2891. * Whether the jidesha extension for firefox is installed for the domain on
  2892. * which we are running. Null designates an unknown value.
  2893. * @type {null}
  2894. */
  2895. var firefoxExtInstalled = null;
  2896. /**
  2897. * If set to true, detection of an installed firefox extension will be started
  2898. * again the next time obtainScreenOnFirefox is called (e.g. next time the
  2899. * user tries to enable screen sharing).
  2900. */
  2901. var reDetectFirefoxExtension = false;
  2902. var GUM = null;
  2903. /**
  2904. * Handles obtaining a stream from a screen capture on different browsers.
  2905. */
  2906. var ScreenObtainer = {
  2907. /**
  2908. * The EventEmitter to use to emit events.
  2909. * @type {null}
  2910. */
  2911. eventEmitter: null,
  2912. obtainStream: null,
  2913. /**
  2914. * Initializes the function used to obtain a screen capture
  2915. * (this.obtainStream).
  2916. *
  2917. * If the browser is Chrome, it uses the value of
  2918. * 'options.desktopSharingChromeMethod' (or 'options.desktopSharing') to
  2919. * decide whether to use the a Chrome extension (if the value is 'ext'),
  2920. * use the "screen" media source (if the value is 'webrtc'),
  2921. * or disable screen capture (if the value is other).
  2922. * Note that for the "screen" media source to work the
  2923. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be set.
  2924. */
  2925. init: function(eventEmitter, options, gum) {
  2926. this.eventEmitter = eventEmitter;
  2927. var obtainDesktopStream = null;
  2928. this.options = options = options || {};
  2929. GUM = gum;
  2930. if (RTCBrowserType.isFirefox())
  2931. initFirefoxExtensionDetection(options);
  2932. // TODO remove this, options.desktopSharing is deprecated.
  2933. var chromeMethod =
  2934. (options.desktopSharingChromeMethod || options.desktopSharing);
  2935. if (RTCBrowserType.isTemasysPluginUsed()) {
  2936. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  2937. logger.info("Screensharing not supported by this plugin " +
  2938. "version");
  2939. } else if(!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2940. logger.info(
  2941. "Screensharing not available with Temasys plugin on" +
  2942. " this site");
  2943. } else {
  2944. obtainDesktopStream = obtainWebRTCScreen;
  2945. logger.info("Using Temasys plugin for desktop sharing");
  2946. }
  2947. } else if (RTCBrowserType.isChrome()) {
  2948. if (chromeMethod == "ext") {
  2949. if (RTCBrowserType.getChromeVersion() >= 34) {
  2950. obtainDesktopStream =
  2951. this.obtainScreenFromExtension;
  2952. logger.info("Using Chrome extension for desktop sharing");
  2953. initChromeExtension(options);
  2954. } else {
  2955. logger.info("Chrome extension not supported until ver 34");
  2956. }
  2957. } else if (chromeMethod == "webrtc") {
  2958. obtainDesktopStream = obtainWebRTCScreen;
  2959. logger.info("Using Chrome WebRTC for desktop sharing");
  2960. }
  2961. } else if (RTCBrowserType.isFirefox()) {
  2962. if (options.desktopSharingFirefoxDisabled) {
  2963. obtainDesktopStream = null;
  2964. } else if (window.location.protocol === "http:"){
  2965. logger.log("Screen sharing is not supported over HTTP. " +
  2966. "Use of HTTPS is required.");
  2967. obtainDesktopStream = null;
  2968. } else {
  2969. obtainDesktopStream = this.obtainScreenOnFirefox;
  2970. }
  2971. }
  2972. if (!obtainDesktopStream) {
  2973. logger.info("Desktop sharing disabled");
  2974. }
  2975. this.obtainStream = obtainDesktopStream;
  2976. },
  2977. /**
  2978. * Checks whether obtaining a screen capture is supported in the current
  2979. * environment.
  2980. * @returns {boolean}
  2981. */
  2982. isSupported: function() {
  2983. return !!this.obtainStream;
  2984. },
  2985. /**
  2986. * Obtains a screen capture stream on Firefox.
  2987. * @param callback
  2988. * @param errorCallback
  2989. */
  2990. obtainScreenOnFirefox:
  2991. function (callback, errorCallback) {
  2992. var self = this;
  2993. var extensionRequired = false;
  2994. if (this.options.desktopSharingFirefoxMaxVersionExtRequired === -1 ||
  2995. (this.options.desktopSharingFirefoxMaxVersionExtRequired >= 0 &&
  2996. RTCBrowserType.getFirefoxVersion() <=
  2997. this.options.desktopSharingFirefoxMaxVersionExtRequired)) {
  2998. extensionRequired = true;
  2999. logger.log("Jidesha extension required on firefox version " +
  3000. RTCBrowserType.getFirefoxVersion());
  3001. }
  3002. if (!extensionRequired || firefoxExtInstalled === true) {
  3003. obtainWebRTCScreen(callback, errorCallback);
  3004. return;
  3005. }
  3006. if (reDetectFirefoxExtension) {
  3007. reDetectFirefoxExtension = false;
  3008. initFirefoxExtensionDetection(this.options);
  3009. }
  3010. // Give it some (more) time to initialize, and assume lack of
  3011. // extension if it hasn't.
  3012. if (firefoxExtInstalled === null) {
  3013. window.setTimeout(
  3014. function() {
  3015. if (firefoxExtInstalled === null)
  3016. firefoxExtInstalled = false;
  3017. self.obtainScreenOnFirefox(callback, errorCallback);
  3018. },
  3019. 300
  3020. );
  3021. logger.log("Waiting for detection of jidesha on firefox to " +
  3022. "finish.");
  3023. return;
  3024. }
  3025. // We need an extension and it isn't installed.
  3026. // Make sure we check for the extension when the user clicks again.
  3027. firefoxExtInstalled = null;
  3028. reDetectFirefoxExtension = true;
  3029. // Prompt the user to install the extension
  3030. this.eventEmitter.emit(
  3031. DesktopSharingEventTypes.FIREFOX_EXTENSION_NEEDED,
  3032. this.options.desktopSharingFirefoxExtensionURL);
  3033. // Make sure desktopsharing knows that we failed, so that it doesn't get
  3034. // stuck in 'switching' mode.
  3035. errorCallback('Firefox extension required.');
  3036. },
  3037. /**
  3038. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  3039. * 'desktop' stream for returned stream token.
  3040. */
  3041. obtainScreenFromExtension: function (streamCallback, failCallback) {
  3042. if (chromeExtInstalled) {
  3043. doGetStreamFromExtension(this.options, streamCallback,
  3044. failCallback);
  3045. } else {
  3046. if (chromeExtUpdateRequired) {
  3047. alert(
  3048. 'Jitsi Desktop Streamer requires update. ' +
  3049. 'Changes will take effect after next Chrome restart.');
  3050. }
  3051. chrome.webstore.install(
  3052. getWebStoreInstallUrl(this.options),
  3053. function (arg) {
  3054. logger.log("Extension installed successfully", arg);
  3055. chromeExtInstalled = true;
  3056. // We need to give a moment for the endpoint to become
  3057. // available
  3058. window.setTimeout(function () {
  3059. doGetStreamFromExtension(this.options, streamCallback,
  3060. failCallback);
  3061. }, 500);
  3062. },
  3063. function (arg) {
  3064. logger.log("Failed to install the extension", arg);
  3065. failCallback(arg);
  3066. }
  3067. );
  3068. }
  3069. }
  3070. };
  3071. /**
  3072. * Obtains a desktop stream using getUserMedia.
  3073. * For this to work on Chrome, the
  3074. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  3075. *
  3076. * On firefox, the document's domain must be white-listed in the
  3077. * 'media.getusermedia.screensharing.allowed_domains' preference in
  3078. * 'about:config'.
  3079. */
  3080. function obtainWebRTCScreen(streamCallback, failCallback) {
  3081. GUM(
  3082. ['screen'],
  3083. streamCallback,
  3084. failCallback
  3085. );
  3086. }
  3087. /**
  3088. * Constructs inline install URL for Chrome desktop streaming extension.
  3089. * The 'chromeExtensionId' must be defined in options parameter.
  3090. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3091. * @returns {string}
  3092. */
  3093. function getWebStoreInstallUrl(options)
  3094. {
  3095. //TODO remove chromeExtensionId (deprecated)
  3096. return "https://chrome.google.com/webstore/detail/" +
  3097. (options.desktopSharingChromeExtId || options.chromeExtensionId);
  3098. }
  3099. /**
  3100. * Checks whether an update of the Chrome extension is required.
  3101. * @param minVersion minimal required version
  3102. * @param extVersion current extension version
  3103. * @returns {boolean}
  3104. */
  3105. function isUpdateRequired(minVersion, extVersion) {
  3106. try {
  3107. var s1 = minVersion.split('.');
  3108. var s2 = extVersion.split('.');
  3109. var len = Math.max(s1.length, s2.length);
  3110. for (var i = 0; i < len; i++) {
  3111. var n1 = 0,
  3112. n2 = 0;
  3113. if (i < s1.length)
  3114. n1 = parseInt(s1[i]);
  3115. if (i < s2.length)
  3116. n2 = parseInt(s2[i]);
  3117. if (isNaN(n1) || isNaN(n2)) {
  3118. return true;
  3119. } else if (n1 !== n2) {
  3120. return n1 > n2;
  3121. }
  3122. }
  3123. // will happen if both versions have identical numbers in
  3124. // their components (even if one of them is longer, has more components)
  3125. return false;
  3126. }
  3127. catch (e) {
  3128. logger.error("Failed to parse extension version", e);
  3129. return true;
  3130. }
  3131. }
  3132. function checkChromeExtInstalled(callback, options) {
  3133. if (!chrome || !chrome.runtime) {
  3134. // No API, so no extension for sure
  3135. callback(false, false);
  3136. return;
  3137. }
  3138. chrome.runtime.sendMessage(
  3139. //TODO: remove chromeExtensionId (deprecated)
  3140. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3141. { getVersion: true },
  3142. function (response) {
  3143. if (!response || !response.version) {
  3144. // Communication failure - assume that no endpoint exists
  3145. logger.warn(
  3146. "Extension not installed?: ", chrome.runtime.lastError);
  3147. callback(false, false);
  3148. return;
  3149. }
  3150. // Check installed extension version
  3151. var extVersion = response.version;
  3152. logger.log('Extension version is: ' + extVersion);
  3153. //TODO: remove minChromeExtVersion (deprecated)
  3154. var updateRequired
  3155. = isUpdateRequired(
  3156. (options.desktopSharingChromeMinExtVersion ||
  3157. options.minChromeExtVersion),
  3158. extVersion);
  3159. callback(!updateRequired, updateRequired);
  3160. }
  3161. );
  3162. }
  3163. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  3164. // Sends 'getStream' msg to the extension.
  3165. // Extension id must be defined in the config.
  3166. chrome.runtime.sendMessage(
  3167. //TODO: remove chromeExtensionId (deprecated)
  3168. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3169. {
  3170. getStream: true,
  3171. //TODO: remove desktopSharingSources (deprecated).
  3172. sources: (options.desktopSharingChromeSources ||
  3173. options.desktopSharingSources)
  3174. },
  3175. function (response) {
  3176. if (!response) {
  3177. failCallback(chrome.runtime.lastError);
  3178. return;
  3179. }
  3180. logger.log("Response from extension: " + response);
  3181. if (response.streamId) {
  3182. GUM(
  3183. ['desktop'],
  3184. function (stream) {
  3185. streamCallback(stream);
  3186. },
  3187. failCallback,
  3188. {desktopStream: response.streamId});
  3189. } else {
  3190. failCallback("Extension failed to get the stream");
  3191. }
  3192. }
  3193. );
  3194. }
  3195. /**
  3196. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3197. * config.js to support inline installs. Host site must be selected as main
  3198. * website of published extension.
  3199. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3200. */
  3201. function initInlineInstalls(options)
  3202. {
  3203. $("link[rel=chrome-webstore-item]").attr("href",
  3204. getWebStoreInstallUrl(options));
  3205. }
  3206. function initChromeExtension(options) {
  3207. // Initialize Chrome extension inline installs
  3208. initInlineInstalls(options);
  3209. // Check if extension is installed
  3210. checkChromeExtInstalled(function (installed, updateRequired) {
  3211. chromeExtInstalled = installed;
  3212. chromeExtUpdateRequired = updateRequired;
  3213. logger.info(
  3214. "Chrome extension installed: " + chromeExtInstalled +
  3215. " updateRequired: " + chromeExtUpdateRequired);
  3216. }, options);
  3217. }
  3218. /**
  3219. * Starts the detection of an installed jidesha extension for firefox.
  3220. * @param options supports "desktopSharingFirefoxDisabled",
  3221. * "desktopSharingFirefoxExtId" and "chromeExtensionId"
  3222. */
  3223. function initFirefoxExtensionDetection(options) {
  3224. if (options.desktopSharingFirefoxDisabled) {
  3225. return;
  3226. }
  3227. if (firefoxExtInstalled === false || firefoxExtInstalled === true)
  3228. return;
  3229. if (!options.desktopSharingFirefoxExtId) {
  3230. firefoxExtInstalled = false;
  3231. return;
  3232. }
  3233. var img = document.createElement('img');
  3234. img.onload = function(){
  3235. logger.log("Detected firefox screen sharing extension.");
  3236. firefoxExtInstalled = true;
  3237. };
  3238. img.onerror = function(){
  3239. logger.log("Detected lack of firefox screen sharing extension.");
  3240. firefoxExtInstalled = false;
  3241. };
  3242. // The jidesha extension exposes an empty image file under the url:
  3243. // "chrome://EXT_ID/content/DOMAIN.png"
  3244. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  3245. // DOMAIN is a domain whitelisted by the extension.
  3246. var src = "chrome://" +
  3247. (options.desktopSharingFirefoxExtId.replace('@', '.')) +
  3248. "/content/" + document.location.hostname + ".png";
  3249. img.setAttribute('src', src);
  3250. }
  3251. module.exports = ScreenObtainer;
  3252. }).call(this,"/modules/RTC/ScreenObtainer.js")
  3253. },{"../../service/desktopsharing/DesktopSharingEventTypes":84,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":48}],20:[function(require,module,exports){
  3254. (function (__filename){
  3255. /*! adapterjs - v0.12.3 - 2015-11-16 */
  3256. var console = require("jitsi-meet-logger").getLogger(__filename);
  3257. // Adapter's interface.
  3258. var AdapterJS = AdapterJS || {};
  3259. // Browserify compatibility
  3260. if(typeof exports !== 'undefined') {
  3261. module.exports = AdapterJS;
  3262. }
  3263. AdapterJS.options = AdapterJS.options || {};
  3264. // uncomment to get virtual webcams
  3265. // AdapterJS.options.getAllCams = true;
  3266. // uncomment to prevent the install prompt when the plugin in not yet installed
  3267. // AdapterJS.options.hidePluginInstallPrompt = true;
  3268. // AdapterJS version
  3269. AdapterJS.VERSION = '0.12.3';
  3270. // This function will be called when the WebRTC API is ready to be used
  3271. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  3272. // the plugin
  3273. // You may Override this function to synchronise the start of your application
  3274. // with the WebRTC API being ready.
  3275. // If you decide not to override use this synchronisation, it may result in
  3276. // an extensive CPU usage on the plugin start (once per tab loaded)
  3277. // Params:
  3278. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  3279. //
  3280. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  3281. // The WebRTC API is ready.
  3282. // Override me and do whatever you want here
  3283. };
  3284. // Sets a callback function to be called when the WebRTC interface is ready.
  3285. // The first argument is the function to callback.\
  3286. // Throws an error if the first argument is not a function
  3287. AdapterJS.webRTCReady = function (callback) {
  3288. if (typeof callback !== 'function') {
  3289. throw new Error('Callback provided is not a function');
  3290. }
  3291. if (true === AdapterJS.onwebrtcreadyDone) {
  3292. // All WebRTC interfaces are ready, just call the callback
  3293. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  3294. } else {
  3295. // will be triggered automatically when your browser/plugin is ready.
  3296. AdapterJS.onwebrtcready = callback;
  3297. }
  3298. };
  3299. // Plugin namespace
  3300. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  3301. // The object to store plugin information
  3302. AdapterJS.WebRTCPlugin.pluginInfo = {
  3303. prefix : 'Tem',
  3304. plugName : 'TemWebRTCPlugin',
  3305. pluginId : 'plugin0',
  3306. type : 'application/x-temwebrtcplugin',
  3307. onload : '__TemWebRTCReady0',
  3308. portalLink : 'http://skylink.io/plugin/',
  3309. downloadLink : null, //set below
  3310. companyName: 'Temasys'
  3311. };
  3312. if(!!navigator.platform.match(/^Mac/i)) {
  3313. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  3314. }
  3315. else if(!!navigator.platform.match(/^Win/i)) {
  3316. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  3317. }
  3318. AdapterJS.WebRTCPlugin.TAGS = {
  3319. NONE : 'none',
  3320. AUDIO : 'audio',
  3321. VIDEO : 'video'
  3322. };
  3323. // Unique identifier of each opened page
  3324. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  3325. // Use this whenever you want to call the plugin.
  3326. AdapterJS.WebRTCPlugin.plugin = null;
  3327. // Set log level for the plugin once it is ready.
  3328. // The different values are
  3329. // This is an asynchronous function that will run when the plugin is ready
  3330. AdapterJS.WebRTCPlugin.setLogLevel = null;
  3331. // Defines webrtc's JS interface according to the plugin's implementation.
  3332. // Define plugin Browsers as WebRTC Interface.
  3333. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  3334. // This function detects whether or not a plugin is installed.
  3335. // Checks if Not IE (firefox, for example), else if it's IE,
  3336. // we're running IE and do something. If not it is not supported.
  3337. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  3338. // Lets adapter.js wait until the the document is ready before injecting the plugin
  3339. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  3340. // Inject the HTML DOM object element into the page.
  3341. AdapterJS.WebRTCPlugin.injectPlugin = null;
  3342. // States of readiness that the plugin goes through when
  3343. // being injected and stated
  3344. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  3345. NONE : 0, // no plugin use
  3346. INITIALIZING : 1, // Detected need for plugin
  3347. INJECTING : 2, // Injecting plugin
  3348. INJECTED: 3, // Plugin element injected but not usable yet
  3349. READY: 4 // Plugin ready to be used
  3350. };
  3351. // Current state of the plugin. You cannot use the plugin before this is
  3352. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  3353. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  3354. // True is AdapterJS.onwebrtcready was already called, false otherwise
  3355. // Used to make sure AdapterJS.onwebrtcready is only called once
  3356. AdapterJS.onwebrtcreadyDone = false;
  3357. // Log levels for the plugin.
  3358. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  3359. /*
  3360. Log outputs are prefixed in some cases.
  3361. INFO: Information reported by the plugin.
  3362. ERROR: Errors originating from within the plugin.
  3363. WEBRTC: Error originating from within the libWebRTC library
  3364. */
  3365. // From the least verbose to the most verbose
  3366. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  3367. NONE : 'NONE',
  3368. ERROR : 'ERROR',
  3369. WARNING : 'WARNING',
  3370. INFO: 'INFO',
  3371. VERBOSE: 'VERBOSE',
  3372. SENSITIVE: 'SENSITIVE'
  3373. };
  3374. // Does a waiting check before proceeding to load the plugin.
  3375. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  3376. // This methid will use an interval to wait for the plugin to be ready.
  3377. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  3378. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  3379. // This function will be called when plugin is ready. It sends necessary
  3380. // details to the plugin.
  3381. // The function will wait for the document to be ready and the set the
  3382. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  3383. // indicating that it can start being requested.
  3384. // This function is not in the IE/Safari condition brackets so that
  3385. // TemPluginLoaded function might be called on Chrome/Firefox.
  3386. // This function is the only private function that is not encapsulated to
  3387. // allow the plugin method to be called.
  3388. __TemWebRTCReady0 = function () {
  3389. if (document.readyState === 'complete') {
  3390. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3391. AdapterJS.maybeThroughWebRTCReady();
  3392. } else {
  3393. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  3394. if (document.readyState === 'complete') {
  3395. // TODO: update comments, we wait for the document to be ready
  3396. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  3397. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3398. AdapterJS.maybeThroughWebRTCReady();
  3399. }
  3400. }, 100);
  3401. }
  3402. };
  3403. AdapterJS.maybeThroughWebRTCReady = function() {
  3404. if (!AdapterJS.onwebrtcreadyDone) {
  3405. AdapterJS.onwebrtcreadyDone = true;
  3406. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  3407. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  3408. }
  3409. }
  3410. };
  3411. // Text namespace
  3412. AdapterJS.TEXT = {
  3413. PLUGIN: {
  3414. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  3415. 'to work on this browser.',
  3416. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  3417. BUTTON: 'Install Now'
  3418. },
  3419. REFRESH: {
  3420. REQUIRE_REFRESH: 'Please refresh page',
  3421. BUTTON: 'Refresh Page'
  3422. }
  3423. };
  3424. // The result of ice connection states.
  3425. // - starting: Ice connection is starting.
  3426. // - checking: Ice connection is checking.
  3427. // - connected Ice connection is connected.
  3428. // - completed Ice connection is connected.
  3429. // - done Ice connection has been completed.
  3430. // - disconnected Ice connection has been disconnected.
  3431. // - failed Ice connection has failed.
  3432. // - closed Ice connection is closed.
  3433. AdapterJS._iceConnectionStates = {
  3434. starting : 'starting',
  3435. checking : 'checking',
  3436. connected : 'connected',
  3437. completed : 'connected',
  3438. done : 'completed',
  3439. disconnected : 'disconnected',
  3440. failed : 'failed',
  3441. closed : 'closed'
  3442. };
  3443. //The IceConnection states that has been fired for each peer.
  3444. AdapterJS._iceConnectionFiredStates = [];
  3445. // Check if WebRTC Interface is defined.
  3446. AdapterJS.isDefined = null;
  3447. // This function helps to retrieve the webrtc detected browser information.
  3448. // This sets:
  3449. // - webrtcDetectedBrowser: The browser agent name.
  3450. // - webrtcDetectedVersion: The browser version.
  3451. // - webrtcDetectedType: The types of webRTC support.
  3452. // - 'moz': Mozilla implementation of webRTC.
  3453. // - 'webkit': WebKit implementation of webRTC.
  3454. // - 'plugin': Using the plugin implementation.
  3455. AdapterJS.parseWebrtcDetectedBrowser = function () {
  3456. var hasMatch, checkMatch = navigator.userAgent.match(
  3457. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  3458. if (/trident/i.test(checkMatch[1])) {
  3459. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  3460. webrtcDetectedBrowser = 'IE';
  3461. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  3462. } else if (checkMatch[1] === 'Chrome') {
  3463. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3464. if (hasMatch !== null) {
  3465. webrtcDetectedBrowser = 'opera';
  3466. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  3467. }
  3468. }
  3469. if (navigator.userAgent.indexOf('Safari')) {
  3470. if (typeof InstallTrigger !== 'undefined') {
  3471. webrtcDetectedBrowser = 'firefox';
  3472. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  3473. webrtcDetectedBrowser = 'IE';
  3474. } else if (
  3475. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  3476. webrtcDetectedBrowser = 'safari';
  3477. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  3478. webrtcDetectedBrowser = 'opera';
  3479. } else if (!!window.chrome) {
  3480. webrtcDetectedBrowser = 'chrome';
  3481. }
  3482. }
  3483. if (!webrtcDetectedBrowser) {
  3484. webrtcDetectedVersion = checkMatch[1];
  3485. }
  3486. if (!webrtcDetectedVersion) {
  3487. try {
  3488. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  3489. [navigator.appName, navigator.appVersion, '-?'];
  3490. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  3491. checkMatch.splice(1, 1, hasMatch[1]);
  3492. }
  3493. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  3494. } catch (error) { }
  3495. }
  3496. };
  3497. // To fix configuration as some browsers does not support
  3498. // the 'urls' attribute.
  3499. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  3500. if (pcConfig === null) {
  3501. return;
  3502. }
  3503. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  3504. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  3505. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  3506. delete pcConfig.iceServers[i].urls;
  3507. }
  3508. }
  3509. };
  3510. AdapterJS.addEvent = function(elem, evnt, func) {
  3511. if (elem.addEventListener) { // W3C DOM
  3512. elem.addEventListener(evnt, func, false);
  3513. } else if (elem.attachEvent) {// OLD IE DOM
  3514. elem.attachEvent('on'+evnt, func);
  3515. } else { // No much to do
  3516. elem[evnt] = func;
  3517. }
  3518. };
  3519. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  3520. // only inject once the page is ready
  3521. if (document.readyState !== 'complete') {
  3522. return;
  3523. }
  3524. var w = window;
  3525. var i = document.createElement('iframe');
  3526. i.style.position = 'fixed';
  3527. i.style.top = '-41px';
  3528. i.style.left = 0;
  3529. i.style.right = 0;
  3530. i.style.width = '100%';
  3531. i.style.height = '40px';
  3532. i.style.backgroundColor = '#ffffe1';
  3533. i.style.border = 'none';
  3534. i.style.borderBottom = '1px solid #888888';
  3535. i.style.zIndex = '9999999';
  3536. if(typeof i.style.webkitTransition === 'string') {
  3537. i.style.webkitTransition = 'all .5s ease-out';
  3538. } else if(typeof i.style.transition === 'string') {
  3539. i.style.transition = 'all .5s ease-out';
  3540. }
  3541. document.body.appendChild(i);
  3542. c = (i.contentWindow) ? i.contentWindow :
  3543. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  3544. c.document.open();
  3545. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  3546. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  3547. 'middle; cursor: default;">' + text + '</span>');
  3548. if(buttonText && buttonLink) {
  3549. c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
  3550. c.document.close();
  3551. // On click on okay
  3552. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  3553. if (!!displayRefreshBar) {
  3554. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  3555. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  3556. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  3557. }
  3558. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  3559. e.preventDefault();
  3560. try {
  3561. event.cancelBubble = true;
  3562. } catch(error) { }
  3563. var pluginInstallInterval = setInterval(function(){
  3564. if(! isIE) {
  3565. navigator.plugins.refresh(false);
  3566. }
  3567. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3568. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3569. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3570. function() { // plugin now installed
  3571. clearInterval(pluginInstallInterval);
  3572. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  3573. },
  3574. function() {
  3575. // still no plugin detected, nothing to do
  3576. });
  3577. } , 500);
  3578. });
  3579. // On click on Cancel
  3580. AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
  3581. w.document.body.removeChild(i);
  3582. });
  3583. } else {
  3584. c.document.close();
  3585. }
  3586. setTimeout(function() {
  3587. if(typeof i.style.webkitTransform === 'string') {
  3588. i.style.webkitTransform = 'translateY(40px)';
  3589. } else if(typeof i.style.transform === 'string') {
  3590. i.style.transform = 'translateY(40px)';
  3591. } else {
  3592. i.style.top = '0px';
  3593. }
  3594. }, 300);
  3595. };
  3596. // -----------------------------------------------------------
  3597. // Detected webrtc implementation. Types are:
  3598. // - 'moz': Mozilla implementation of webRTC.
  3599. // - 'webkit': WebKit implementation of webRTC.
  3600. // - 'plugin': Using the plugin implementation.
  3601. webrtcDetectedType = null;
  3602. // Detected webrtc datachannel support. Types are:
  3603. // - 'SCTP': SCTP datachannel support.
  3604. // - 'RTP': RTP datachannel support.
  3605. webrtcDetectedDCSupport = null;
  3606. // Set the settings for creating DataChannels, MediaStream for
  3607. // Cross-browser compability.
  3608. // - This is only for SCTP based support browsers.
  3609. // the 'urls' attribute.
  3610. checkMediaDataChannelSettings =
  3611. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  3612. if (typeof callback !== 'function') {
  3613. return;
  3614. }
  3615. var beOfferer = true;
  3616. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  3617. // Nightly version does not require MozDontOfferDataChannel for interop
  3618. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  3619. var isPeerFirefox = peerBrowserAgent === 'firefox';
  3620. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  3621. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  3622. // Resends an updated version of constraints for MozDataChannel to work
  3623. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  3624. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  3625. try {
  3626. delete constraints.mandatory.MozDontOfferDataChannel;
  3627. } catch (error) {
  3628. console.error('Failed deleting MozDontOfferDataChannel');
  3629. console.error(error);
  3630. }
  3631. } else if ((isLocalFirefox && !isPeerFirefox)) {
  3632. constraints.mandatory.MozDontOfferDataChannel = true;
  3633. }
  3634. if (!isLocalFirefox) {
  3635. // temporary measure to remove Moz* constraints in non Firefox browsers
  3636. for (var prop in constraints.mandatory) {
  3637. if (constraints.mandatory.hasOwnProperty(prop)) {
  3638. if (prop.indexOf('Moz') !== -1) {
  3639. delete constraints.mandatory[prop];
  3640. }
  3641. }
  3642. }
  3643. }
  3644. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  3645. // interopability of the media stream
  3646. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  3647. beOfferer = false;
  3648. }
  3649. callback(beOfferer, constraints);
  3650. };
  3651. // Handles the differences for all browsers ice connection state output.
  3652. // - Tested outcomes are:
  3653. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  3654. // - Chrome (answerer) : 'checking' > 'connected'
  3655. // - Firefox (offerer) : 'checking' > 'connected'
  3656. // - Firefox (answerer): 'checking' > 'connected'
  3657. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  3658. if (typeof callback !== 'function') {
  3659. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  3660. return;
  3661. }
  3662. peerId = (peerId) ? peerId : 'peer';
  3663. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  3664. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  3665. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  3666. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  3667. AdapterJS._iceConnectionFiredStates[peerId] = [];
  3668. }
  3669. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  3670. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  3671. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  3672. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  3673. setTimeout(function () {
  3674. AdapterJS._iceConnectionFiredStates[peerId]
  3675. .push(AdapterJS._iceConnectionStates.done);
  3676. callback(AdapterJS._iceConnectionStates.done);
  3677. }, 1000);
  3678. }
  3679. callback(iceConnectionState);
  3680. }
  3681. return;
  3682. };
  3683. // Firefox:
  3684. // - Creates iceServer from the url for Firefox.
  3685. // - Create iceServer with stun url.
  3686. // - Create iceServer with turn url.
  3687. // - Ignore the transport parameter from TURN url for FF version <=27.
  3688. // - Return null for createIceServer if transport=tcp.
  3689. // - FF 27 and above supports transport parameters in TURN url,
  3690. // - So passing in the full url to create iceServer.
  3691. // Chrome:
  3692. // - Creates iceServer from the url for Chrome M33 and earlier.
  3693. // - Create iceServer with stun url.
  3694. // - Chrome M28 & above uses below TURN format.
  3695. // Plugin:
  3696. // - Creates Ice Server for Plugin Browsers
  3697. // - If Stun - Create iceServer with stun url.
  3698. // - Else - Create iceServer with turn url
  3699. // - This is a WebRTC Function
  3700. createIceServer = null;
  3701. // Firefox:
  3702. // - Creates IceServers for Firefox
  3703. // - Use .url for FireFox.
  3704. // - Multiple Urls support
  3705. // Chrome:
  3706. // - Creates iceServers from the urls for Chrome M34 and above.
  3707. // - .urls is supported since Chrome M34.
  3708. // - Multiple Urls support
  3709. // Plugin:
  3710. // - Creates Ice Servers for Plugin Browsers
  3711. // - Multiple Urls support
  3712. // - This is a WebRTC Function
  3713. createIceServers = null;
  3714. //------------------------------------------------------------
  3715. //The RTCPeerConnection object.
  3716. RTCPeerConnection = null;
  3717. // Creates RTCSessionDescription object for Plugin Browsers
  3718. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  3719. RTCSessionDescription : null;
  3720. // Creates RTCIceCandidate object for Plugin Browsers
  3721. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  3722. RTCIceCandidate : null;
  3723. // Get UserMedia (only difference is the prefix).
  3724. // Code from Adam Barth.
  3725. getUserMedia = null;
  3726. // Attach a media stream to an element.
  3727. attachMediaStream = null;
  3728. // Re-attach a media stream to an element.
  3729. reattachMediaStream = null;
  3730. // Detected browser agent name. Types are:
  3731. // - 'firefox': Firefox browser.
  3732. // - 'chrome': Chrome browser.
  3733. // - 'opera': Opera browser.
  3734. // - 'safari': Safari browser.
  3735. // - 'IE' - Internet Explorer browser.
  3736. webrtcDetectedBrowser = null;
  3737. // Detected browser version.
  3738. webrtcDetectedVersion = null;
  3739. // Check for browser types and react accordingly
  3740. if (navigator.mozGetUserMedia) {
  3741. webrtcDetectedBrowser = 'firefox';
  3742. webrtcDetectedVersion = parseInt(navigator
  3743. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  3744. webrtcDetectedType = 'moz';
  3745. webrtcDetectedDCSupport = 'SCTP';
  3746. RTCPeerConnection = function (pcConfig, pcConstraints) {
  3747. AdapterJS.maybeFixConfiguration(pcConfig);
  3748. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  3749. };
  3750. // The RTCSessionDescription object.
  3751. RTCSessionDescription = mozRTCSessionDescription;
  3752. window.RTCSessionDescription = RTCSessionDescription;
  3753. // The RTCIceCandidate object.
  3754. RTCIceCandidate = mozRTCIceCandidate;
  3755. window.RTCIceCandidate = RTCIceCandidate;
  3756. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  3757. navigator.getUserMedia = window.getUserMedia;
  3758. // Shim for MediaStreamTrack.getSources.
  3759. MediaStreamTrack.getSources = function(successCb) {
  3760. setTimeout(function() {
  3761. var infos = [
  3762. { kind: 'audio', id: 'default', label:'', facing:'' },
  3763. { kind: 'video', id: 'default', label:'', facing:'' }
  3764. ];
  3765. successCb(infos);
  3766. }, 0);
  3767. };
  3768. createIceServer = function (url, username, password) {
  3769. var iceServer = null;
  3770. var url_parts = url.split(':');
  3771. if (url_parts[0].indexOf('stun') === 0) {
  3772. iceServer = { url : url };
  3773. } else if (url_parts[0].indexOf('turn') === 0) {
  3774. if (webrtcDetectedVersion < 27) {
  3775. var turn_url_parts = url.split('?');
  3776. if (turn_url_parts.length === 1 ||
  3777. turn_url_parts[1].indexOf('transport=udp') === 0) {
  3778. iceServer = {
  3779. url : turn_url_parts[0],
  3780. credential : password,
  3781. username : username
  3782. };
  3783. }
  3784. } else {
  3785. iceServer = {
  3786. url : url,
  3787. credential : password,
  3788. username : username
  3789. };
  3790. }
  3791. }
  3792. return iceServer;
  3793. };
  3794. createIceServers = function (urls, username, password) {
  3795. var iceServers = [];
  3796. for (var i = 0; i < urls.length; i++) {
  3797. var iceServer = createIceServer(urls[i], username, password);
  3798. if (iceServer !== null) {
  3799. iceServers.push(iceServer);
  3800. }
  3801. }
  3802. return iceServers;
  3803. };
  3804. attachMediaStream = function (element, stream) {
  3805. element.mozSrcObject = stream;
  3806. if (stream !== null)
  3807. element.play();
  3808. return element;
  3809. };
  3810. reattachMediaStream = function (to, from) {
  3811. to.mozSrcObject = from.mozSrcObject;
  3812. to.play();
  3813. return to;
  3814. };
  3815. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  3816. if (!callback) {
  3817. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  3818. ': 1 argument required, but only 0 present.');
  3819. }
  3820. return callback([]);
  3821. };
  3822. // Fake get{Video,Audio}Tracks
  3823. if (!MediaStream.prototype.getVideoTracks) {
  3824. MediaStream.prototype.getVideoTracks = function () {
  3825. return [];
  3826. };
  3827. }
  3828. if (!MediaStream.prototype.getAudioTracks) {
  3829. MediaStream.prototype.getAudioTracks = function () {
  3830. return [];
  3831. };
  3832. }
  3833. AdapterJS.maybeThroughWebRTCReady();
  3834. } else if (navigator.webkitGetUserMedia) {
  3835. webrtcDetectedBrowser = 'chrome';
  3836. webrtcDetectedType = 'webkit';
  3837. webrtcDetectedVersion = parseInt(navigator
  3838. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  3839. // check if browser is opera 20+
  3840. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3841. if (checkIfOpera !== null) {
  3842. webrtcDetectedBrowser = 'opera';
  3843. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  3844. }
  3845. // check browser datachannel support
  3846. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  3847. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  3848. webrtcDetectedDCSupport = 'SCTP';
  3849. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  3850. webrtcDetectedVersion > 24) {
  3851. webrtcDetectedDCSupport = 'RTP';
  3852. } else {
  3853. webrtcDetectedDCSupport = '';
  3854. }
  3855. createIceServer = function (url, username, password) {
  3856. var iceServer = null;
  3857. var url_parts = url.split(':');
  3858. if (url_parts[0].indexOf('stun') === 0) {
  3859. iceServer = { 'url' : url };
  3860. } else if (url_parts[0].indexOf('turn') === 0) {
  3861. iceServer = {
  3862. 'url' : url,
  3863. 'credential' : password,
  3864. 'username' : username
  3865. };
  3866. }
  3867. return iceServer;
  3868. };
  3869. createIceServers = function (urls, username, password) {
  3870. var iceServers = [];
  3871. if (webrtcDetectedVersion >= 34) {
  3872. iceServers = {
  3873. 'urls' : urls,
  3874. 'credential' : password,
  3875. 'username' : username
  3876. };
  3877. } else {
  3878. for (var i = 0; i < urls.length; i++) {
  3879. var iceServer = createIceServer(urls[i], username, password);
  3880. if (iceServer !== null) {
  3881. iceServers.push(iceServer);
  3882. }
  3883. }
  3884. }
  3885. return iceServers;
  3886. };
  3887. RTCPeerConnection = function (pcConfig, pcConstraints) {
  3888. if (webrtcDetectedVersion < 34) {
  3889. AdapterJS.maybeFixConfiguration(pcConfig);
  3890. }
  3891. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  3892. };
  3893. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  3894. navigator.getUserMedia = window.getUserMedia;
  3895. attachMediaStream = function (element, stream) {
  3896. if (typeof element.srcObject !== 'undefined') {
  3897. element.srcObject = stream;
  3898. } else if (typeof element.mozSrcObject !== 'undefined') {
  3899. element.mozSrcObject = stream;
  3900. } else if (typeof element.src !== 'undefined') {
  3901. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  3902. } else {
  3903. console.log('Error attaching stream to element.');
  3904. }
  3905. return element;
  3906. };
  3907. reattachMediaStream = function (to, from) {
  3908. to.src = from.src;
  3909. return to;
  3910. };
  3911. AdapterJS.maybeThroughWebRTCReady();
  3912. } else if (navigator.mediaDevices && navigator.userAgent.match(
  3913. /Edge\/(\d+).(\d+)$/)) {
  3914. webrtcDetectedBrowser = 'edge';
  3915. webrtcDetectedVersion =
  3916. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  3917. // the minimum version still supported by adapter.
  3918. webrtcMinimumVersion = 12;
  3919. window.getUserMedia = navigator.getUserMedia.bind(navigator);
  3920. attachMediaStream = function(element, stream) {
  3921. element.srcObject = stream;
  3922. return element;
  3923. };
  3924. reattachMediaStream = function(to, from) {
  3925. to.srcObject = from.srcObject;
  3926. return to;
  3927. };
  3928. AdapterJS.maybeThroughWebRTCReady();
  3929. } else { // TRY TO USE PLUGIN
  3930. // IE 9 is not offering an implementation of console.log until you open a console
  3931. if (typeof console !== 'object' || typeof console.log !== 'function') {
  3932. /* jshint -W020 */
  3933. console = {} || console;
  3934. // Implemented based on console specs from MDN
  3935. // You may override these functions
  3936. console.log = function (arg) {};
  3937. console.info = function (arg) {};
  3938. console.error = function (arg) {};
  3939. console.dir = function (arg) {};
  3940. console.exception = function (arg) {};
  3941. console.trace = function (arg) {};
  3942. console.warn = function (arg) {};
  3943. console.count = function (arg) {};
  3944. console.debug = function (arg) {};
  3945. console.count = function (arg) {};
  3946. console.time = function (arg) {};
  3947. console.timeEnd = function (arg) {};
  3948. console.group = function (arg) {};
  3949. console.groupCollapsed = function (arg) {};
  3950. console.groupEnd = function (arg) {};
  3951. /* jshint +W020 */
  3952. }
  3953. webrtcDetectedType = 'plugin';
  3954. webrtcDetectedDCSupport = 'plugin';
  3955. AdapterJS.parseWebrtcDetectedBrowser();
  3956. isIE = webrtcDetectedBrowser === 'IE';
  3957. /* jshint -W035 */
  3958. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  3959. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3960. /* empty because it needs to prevent the function from running. */
  3961. }
  3962. };
  3963. /* jshint +W035 */
  3964. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  3965. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3966. // Call immediately if possible
  3967. // Once the plugin is set, the code will always take this path
  3968. callback();
  3969. } else {
  3970. // otherwise start a 100ms interval
  3971. var checkPluginReadyState = setInterval(function () {
  3972. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3973. clearInterval(checkPluginReadyState);
  3974. callback();
  3975. }
  3976. }, 100);
  3977. }
  3978. };
  3979. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  3980. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3981. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  3982. });
  3983. };
  3984. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  3985. // only inject once the page is ready
  3986. if (document.readyState !== 'complete') {
  3987. return;
  3988. }
  3989. // Prevent multiple injections
  3990. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  3991. return;
  3992. }
  3993. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  3994. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  3995. var frag = document.createDocumentFragment();
  3996. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  3997. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  3998. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  3999. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  4000. '<param name="pluginId" value="' +
  4001. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  4002. '<param name="windowless" value="false" /> ' +
  4003. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4004. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  4005. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  4006. // uncomment to be able to use virtual cams
  4007. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4008. '</object>';
  4009. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  4010. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  4011. }
  4012. document.body.appendChild(frag);
  4013. // Need to re-fetch the plugin
  4014. AdapterJS.WebRTCPlugin.plugin =
  4015. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  4016. } else {
  4017. // Load Plugin
  4018. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  4019. AdapterJS.WebRTCPlugin.plugin.id =
  4020. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  4021. // IE will only start the plugin if it's ACTUALLY visible
  4022. if (isIE) {
  4023. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  4024. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  4025. } else { // The size of the plugin on Safari should be 0x0px
  4026. // so that the autorisation prompt is at the top
  4027. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  4028. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  4029. }
  4030. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  4031. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  4032. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  4033. '<param name="pluginId" value="' +
  4034. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  4035. '<param name="windowless" value="false" /> ' +
  4036. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4037. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  4038. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  4039. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  4040. }
  4041. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  4042. };
  4043. AdapterJS.WebRTCPlugin.isPluginInstalled =
  4044. function (comName, plugName, installedCb, notInstalledCb) {
  4045. if (!isIE) {
  4046. var pluginArray = navigator.plugins;
  4047. for (var i = 0; i < pluginArray.length; i++) {
  4048. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  4049. installedCb();
  4050. return;
  4051. }
  4052. }
  4053. notInstalledCb();
  4054. } else {
  4055. try {
  4056. var axo = new ActiveXObject(comName + '.' + plugName);
  4057. } catch (e) {
  4058. notInstalledCb();
  4059. return;
  4060. }
  4061. installedCb();
  4062. }
  4063. };
  4064. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  4065. if (AdapterJS.WebRTCPlugin.pluginState ===
  4066. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4067. console.error("AdapterJS - WebRTC interface has already been defined");
  4068. return;
  4069. }
  4070. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  4071. AdapterJS.isDefined = function (variable) {
  4072. return variable !== null && variable !== undefined;
  4073. };
  4074. createIceServer = function (url, username, password) {
  4075. var iceServer = null;
  4076. var url_parts = url.split(':');
  4077. if (url_parts[0].indexOf('stun') === 0) {
  4078. iceServer = {
  4079. 'url' : url,
  4080. 'hasCredentials' : false
  4081. };
  4082. } else if (url_parts[0].indexOf('turn') === 0) {
  4083. iceServer = {
  4084. 'url' : url,
  4085. 'hasCredentials' : true,
  4086. 'credential' : password,
  4087. 'username' : username
  4088. };
  4089. }
  4090. return iceServer;
  4091. };
  4092. createIceServers = function (urls, username, password) {
  4093. var iceServers = [];
  4094. for (var i = 0; i < urls.length; ++i) {
  4095. iceServers.push(createIceServer(urls[i], username, password));
  4096. }
  4097. return iceServers;
  4098. };
  4099. RTCSessionDescription = function (info) {
  4100. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4101. return AdapterJS.WebRTCPlugin.plugin.
  4102. ConstructSessionDescription(info.type, info.sdp);
  4103. };
  4104. RTCPeerConnection = function (servers, constraints) {
  4105. var iceServers = null;
  4106. if (servers) {
  4107. iceServers = servers.iceServers;
  4108. for (var i = 0; i < iceServers.length; i++) {
  4109. if (iceServers[i].urls && !iceServers[i].url) {
  4110. iceServers[i].url = iceServers[i].urls;
  4111. }
  4112. iceServers[i].hasCredentials = AdapterJS.
  4113. isDefined(iceServers[i].username) &&
  4114. AdapterJS.isDefined(iceServers[i].credential);
  4115. }
  4116. }
  4117. var mandatory = (constraints && constraints.mandatory) ?
  4118. constraints.mandatory : null;
  4119. var optional = (constraints && constraints.optional) ?
  4120. constraints.optional : null;
  4121. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4122. return AdapterJS.WebRTCPlugin.plugin.
  4123. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  4124. iceServers, mandatory, optional);
  4125. };
  4126. MediaStreamTrack = {};
  4127. MediaStreamTrack.getSources = function (callback) {
  4128. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4129. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  4130. });
  4131. };
  4132. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  4133. constraints.audio = constraints.audio || false;
  4134. constraints.video = constraints.video || false;
  4135. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4136. AdapterJS.WebRTCPlugin.plugin.
  4137. getUserMedia(constraints, successCallback, failureCallback);
  4138. });
  4139. };
  4140. window.navigator.getUserMedia = window.getUserMedia;
  4141. attachMediaStream = function (element, stream) {
  4142. if (!element || !element.parentNode) {
  4143. return;
  4144. }
  4145. var streamId;
  4146. if (stream === null) {
  4147. streamId = '';
  4148. } else {
  4149. if (typeof stream.enableSoundTracks !== 'undefined') {
  4150. stream.enableSoundTracks(true);
  4151. }
  4152. streamId = stream.id;
  4153. }
  4154. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  4155. var nodeName = element.nodeName.toLowerCase();
  4156. if (nodeName !== 'object') { // not a plugin <object> tag yet
  4157. var tag;
  4158. switch(nodeName) {
  4159. case 'audio':
  4160. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  4161. break;
  4162. case 'video':
  4163. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  4164. break;
  4165. default:
  4166. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  4167. }
  4168. var frag = document.createDocumentFragment();
  4169. var temp = document.createElement('div');
  4170. var classHTML = '';
  4171. if (element.className) {
  4172. classHTML = 'class="' + element.className + '" ';
  4173. } else if (element.attributes && element.attributes['class']) {
  4174. classHTML = 'class="' + element.attributes['class'].value + '" ';
  4175. }
  4176. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  4177. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  4178. '<param name="pluginId" value="' + elementId + '" /> ' +
  4179. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4180. '<param name="windowless" value="true" /> ' +
  4181. '<param name="streamId" value="' + streamId + '" /> ' +
  4182. '<param name="tag" value="' + tag + '" /> ' +
  4183. '</object>';
  4184. while (temp.firstChild) {
  4185. frag.appendChild(temp.firstChild);
  4186. }
  4187. var height = '';
  4188. var width = '';
  4189. if (element.clientWidth || element.clientHeight) {
  4190. width = element.clientWidth;
  4191. height = element.clientHeight;
  4192. }
  4193. else if (element.width || element.height) {
  4194. width = element.width;
  4195. height = element.height;
  4196. }
  4197. element.parentNode.insertBefore(frag, element);
  4198. frag = document.getElementById(elementId);
  4199. frag.width = width;
  4200. frag.height = height;
  4201. element.parentNode.removeChild(element);
  4202. } else { // already an <object> tag, just change the stream id
  4203. var children = element.children;
  4204. for (var i = 0; i !== children.length; ++i) {
  4205. if (children[i].name === 'streamId') {
  4206. children[i].value = streamId;
  4207. break;
  4208. }
  4209. }
  4210. element.setStreamId(streamId);
  4211. }
  4212. var newElement = document.getElementById(elementId);
  4213. AdapterJS.forwardEventHandlers(newElement, element, Object.getPrototypeOf(element));
  4214. return newElement;
  4215. };
  4216. reattachMediaStream = function (to, from) {
  4217. var stream = null;
  4218. var children = from.children;
  4219. for (var i = 0; i !== children.length; ++i) {
  4220. if (children[i].name === 'streamId') {
  4221. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4222. stream = AdapterJS.WebRTCPlugin.plugin
  4223. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  4224. break;
  4225. }
  4226. }
  4227. if (stream !== null) {
  4228. return attachMediaStream(to, stream);
  4229. } else {
  4230. console.log('Could not find the stream associated with this element');
  4231. }
  4232. };
  4233. AdapterJS.forwardEventHandlers = function (destElem, srcElem, prototype) {
  4234. properties = Object.getOwnPropertyNames( prototype );
  4235. for(prop in properties) {
  4236. propName = properties[prop];
  4237. if (typeof(propName.slice) === 'function') {
  4238. if (propName.slice(0,2) == 'on' && srcElem[propName] != null) {
  4239. if (isIE) {
  4240. destElem.attachEvent(propName,srcElem[propName]);
  4241. } else {
  4242. destElem.addEventListener(propName.slice(2), srcElem[propName], false)
  4243. }
  4244. } else {
  4245. //TODO (http://jira.temasys.com.sg/browse/TWP-328) Forward non-event properties ?
  4246. }
  4247. }
  4248. }
  4249. var subPrototype = Object.getPrototypeOf(prototype)
  4250. if(subPrototype != null) {
  4251. AdapterJS.forwardEventHandlers(destElem, srcElem, subPrototype);
  4252. }
  4253. }
  4254. RTCIceCandidate = function (candidate) {
  4255. if (!candidate.sdpMid) {
  4256. candidate.sdpMid = '';
  4257. }
  4258. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4259. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  4260. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  4261. );
  4262. };
  4263. // inject plugin
  4264. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  4265. AdapterJS.WebRTCPlugin.injectPlugin();
  4266. };
  4267. // This function will be called if the plugin is needed (browser different
  4268. // from Chrome or Firefox), but the plugin is not installed.
  4269. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  4270. function() {
  4271. AdapterJS.addEvent(document,
  4272. 'readystatechange',
  4273. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  4274. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  4275. };
  4276. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  4277. if (AdapterJS.options.hidePluginInstallPrompt) {
  4278. return;
  4279. }
  4280. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  4281. if(downloadLink) { // if download link
  4282. var popupString;
  4283. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  4284. popupString = 'This website requires you to install the ' +
  4285. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  4286. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  4287. ' WebRTC Plugin</a>' +
  4288. ' to work on this browser.';
  4289. } else { // no portal link, just print a generic explanation
  4290. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  4291. }
  4292. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  4293. } else { // no download link, just print a generic explanation
  4294. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  4295. }
  4296. };
  4297. // Try to detect the plugin and act accordingly
  4298. AdapterJS.WebRTCPlugin.isPluginInstalled(
  4299. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  4300. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  4301. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  4302. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  4303. }
  4304. }).call(this,"/modules/RTC/adapter.screenshare.js")
  4305. },{"jitsi-meet-logger":48}],21:[function(require,module,exports){
  4306. (function (__filename){
  4307. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4308. function supportsLocalStorage() {
  4309. try {
  4310. return 'localStorage' in window && window.localStorage !== null;
  4311. } catch (e) {
  4312. logger.log("localstorage is not supported");
  4313. return false;
  4314. }
  4315. }
  4316. function generateUniqueId() {
  4317. function _p8() {
  4318. return (Math.random().toString(16) + "000000000").substr(2, 8);
  4319. }
  4320. return _p8() + _p8() + _p8() + _p8();
  4321. }
  4322. function Settings(conferenceID) {
  4323. this.email = '';
  4324. this.displayName = '';
  4325. this.userId;
  4326. this.language = null;
  4327. this.confSettings = null;
  4328. this.conferenceID = conferenceID;
  4329. if (supportsLocalStorage()) {
  4330. if(!window.localStorage.getItem(conferenceID))
  4331. this.confSettings = {};
  4332. else
  4333. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  4334. if(!this.confSettings.jitsiMeetId) {
  4335. this.confSettings.jitsiMeetId = generateUniqueId();
  4336. logger.log("generated id",
  4337. this.confSettings.jitsiMeetId);
  4338. this.save();
  4339. }
  4340. this.userId = this.confSettings.jitsiMeetId || '';
  4341. this.email = this.confSettings.email || '';
  4342. this.displayName = this.confSettings.displayname || '';
  4343. this.language = this.confSettings.language;
  4344. } else {
  4345. logger.log("local storage is not supported");
  4346. this.userId = generateUniqueId();
  4347. }
  4348. }
  4349. Settings.prototype.save = function () {
  4350. if(!supportsLocalStorage())
  4351. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  4352. }
  4353. Settings.prototype.setDisplayName = function (newDisplayName) {
  4354. this.displayName = newDisplayName;
  4355. if(this.confSettings != null)
  4356. this.confSettings.displayname = displayName;
  4357. this.save();
  4358. return this.displayName;
  4359. },
  4360. Settings.prototype.setEmail = function (newEmail) {
  4361. this.email = newEmail;
  4362. if(this.confSettings != null)
  4363. this.confSettings.email = newEmail;
  4364. this.save();
  4365. return this.email;
  4366. },
  4367. Settings.prototype.getSettings = function () {
  4368. return {
  4369. email: this.email,
  4370. displayName: this.displayName,
  4371. uid: this.userId,
  4372. language: this.language
  4373. };
  4374. },
  4375. Settings.prototype.setLanguage = function (lang) {
  4376. this.language = lang;
  4377. if(this.confSettings != null)
  4378. this.confSettings.language = lang;
  4379. this.save();
  4380. }
  4381. module.exports = Settings;
  4382. }).call(this,"/modules/settings/Settings.js")
  4383. },{"jitsi-meet-logger":48}],22:[function(require,module,exports){
  4384. /* global config */
  4385. /**
  4386. * Provides statistics for the local stream.
  4387. */
  4388. var RTCBrowserType = require('../RTC/RTCBrowserType');
  4389. /**
  4390. * Size of the webaudio analyzer buffer.
  4391. * @type {number}
  4392. */
  4393. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  4394. /**
  4395. * Value of the webaudio analyzer smoothing time parameter.
  4396. * @type {number}
  4397. */
  4398. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  4399. /**
  4400. * Converts time domain data array to audio level.
  4401. * @param samples the time domain data array.
  4402. * @returns {number} the audio level
  4403. */
  4404. function timeDomainDataToAudioLevel(samples) {
  4405. var maxVolume = 0;
  4406. var length = samples.length;
  4407. for (var i = 0; i < length; i++) {
  4408. if (maxVolume < samples[i])
  4409. maxVolume = samples[i];
  4410. }
  4411. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  4412. }
  4413. /**
  4414. * Animates audio level change
  4415. * @param newLevel the new audio level
  4416. * @param lastLevel the last audio level
  4417. * @returns {Number} the audio level to be set
  4418. */
  4419. function animateLevel(newLevel, lastLevel) {
  4420. var value = 0;
  4421. var diff = lastLevel - newLevel;
  4422. if(diff > 0.2) {
  4423. value = lastLevel - 0.2;
  4424. }
  4425. else if(diff < -0.4) {
  4426. value = lastLevel + 0.4;
  4427. }
  4428. else {
  4429. value = newLevel;
  4430. }
  4431. return parseFloat(value.toFixed(3));
  4432. }
  4433. /**
  4434. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  4435. *
  4436. * @param stream the local stream
  4437. * @param interval stats refresh interval given in ms.
  4438. * @param callback function that receives the audio levels.
  4439. * @constructor
  4440. */
  4441. function LocalStatsCollector(stream, interval, callback) {
  4442. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  4443. this.stream = stream;
  4444. this.intervalId = null;
  4445. this.intervalMilis = interval;
  4446. this.audioLevel = 0;
  4447. this.callback = callback;
  4448. }
  4449. /**
  4450. * Starts the collecting the statistics.
  4451. */
  4452. LocalStatsCollector.prototype.start = function () {
  4453. if (!window.AudioContext ||
  4454. RTCBrowserType.isTemasysPluginUsed())
  4455. return;
  4456. var context = new AudioContext();
  4457. var analyser = context.createAnalyser();
  4458. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  4459. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  4460. var source = context.createMediaStreamSource(this.stream);
  4461. source.connect(analyser);
  4462. var self = this;
  4463. this.intervalId = setInterval(
  4464. function () {
  4465. var array = new Uint8Array(analyser.frequencyBinCount);
  4466. analyser.getByteTimeDomainData(array);
  4467. var audioLevel = timeDomainDataToAudioLevel(array);
  4468. if (audioLevel != self.audioLevel) {
  4469. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  4470. self.callback(self.audioLevel);
  4471. }
  4472. },
  4473. this.intervalMilis
  4474. );
  4475. };
  4476. /**
  4477. * Stops collecting the statistics.
  4478. */
  4479. LocalStatsCollector.prototype.stop = function () {
  4480. if (this.intervalId) {
  4481. clearInterval(this.intervalId);
  4482. this.intervalId = null;
  4483. }
  4484. };
  4485. module.exports = LocalStatsCollector;
  4486. },{"../RTC/RTCBrowserType":17}],23:[function(require,module,exports){
  4487. (function (__filename){
  4488. /* global require, ssrc2jid */
  4489. /* jshint -W117 */
  4490. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4491. var RTCBrowserType = require("../RTC/RTCBrowserType");
  4492. var StatisticsEvents = require("../../service/statistics/Events");
  4493. /* Whether we support the browser we are running into for logging statistics */
  4494. var browserSupported = RTCBrowserType.isChrome() ||
  4495. RTCBrowserType.isOpera();
  4496. var keyMap = {};
  4497. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  4498. "ssrc": "ssrc",
  4499. "packetsReceived": "packetsReceived",
  4500. "packetsLost": "packetsLost",
  4501. "packetsSent": "packetsSent",
  4502. "bytesReceived": "bytesReceived",
  4503. "bytesSent": "bytesSent"
  4504. };
  4505. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  4506. "receiveBandwidth": "googAvailableReceiveBandwidth",
  4507. "sendBandwidth": "googAvailableSendBandwidth",
  4508. "remoteAddress": "googRemoteAddress",
  4509. "transportType": "googTransportType",
  4510. "localAddress": "googLocalAddress",
  4511. "activeConnection": "googActiveConnection",
  4512. "ssrc": "ssrc",
  4513. "packetsReceived": "packetsReceived",
  4514. "packetsSent": "packetsSent",
  4515. "packetsLost": "packetsLost",
  4516. "bytesReceived": "bytesReceived",
  4517. "bytesSent": "bytesSent",
  4518. "googFrameHeightReceived": "googFrameHeightReceived",
  4519. "googFrameWidthReceived": "googFrameWidthReceived",
  4520. "googFrameHeightSent": "googFrameHeightSent",
  4521. "googFrameWidthSent": "googFrameWidthSent",
  4522. "audioInputLevel": "audioInputLevel",
  4523. "audioOutputLevel": "audioOutputLevel"
  4524. };
  4525. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  4526. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  4527. /**
  4528. * Calculates packet lost percent using the number of lost packets and the
  4529. * number of all packet.
  4530. * @param lostPackets the number of lost packets
  4531. * @param totalPackets the number of all packets.
  4532. * @returns {number} packet loss percent
  4533. */
  4534. function calculatePacketLoss(lostPackets, totalPackets) {
  4535. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  4536. return 0;
  4537. return Math.round((lostPackets/totalPackets)*100);
  4538. }
  4539. function getStatValue(item, name) {
  4540. var browserType = RTCBrowserType.getBrowserType();
  4541. if (!keyMap[browserType][name])
  4542. throw "The property isn't supported!";
  4543. var key = keyMap[browserType][name];
  4544. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  4545. item.stat(key) : item[key];
  4546. }
  4547. function formatAudioLevel(audioLevel) {
  4548. return Math.min(Math.max(audioLevel, 0), 1);
  4549. }
  4550. /**
  4551. * Checks whether a certain record should be included in the logged statistics.
  4552. */
  4553. function acceptStat(reportId, reportType, statName) {
  4554. if (reportType == "googCandidatePair" && statName == "googChannelId")
  4555. return false;
  4556. if (reportType == "ssrc") {
  4557. if (statName == "googTrackId" ||
  4558. statName == "transportId" ||
  4559. statName == "ssrc")
  4560. return false;
  4561. }
  4562. return true;
  4563. }
  4564. /**
  4565. * Checks whether a certain record should be included in the logged statistics.
  4566. */
  4567. function acceptReport(id, type) {
  4568. if (id.substring(0, 15) == "googCertificate" ||
  4569. id.substring(0, 9) == "googTrack" ||
  4570. id.substring(0, 20) == "googLibjingleSession")
  4571. return false;
  4572. if (type == "googComponent")
  4573. return false;
  4574. return true;
  4575. }
  4576. /**
  4577. * Peer statistics data holder.
  4578. * @constructor
  4579. */
  4580. function PeerStats()
  4581. {
  4582. this.ssrc2Loss = {};
  4583. this.ssrc2AudioLevel = {};
  4584. this.ssrc2bitrate = {};
  4585. this.ssrc2resolution = {};
  4586. }
  4587. /**
  4588. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  4589. * represented by this instance.
  4590. * @param lossRate new packet loss rate value to be set.
  4591. */
  4592. PeerStats.prototype.setSsrcLoss = function (lossRate)
  4593. {
  4594. this.ssrc2Loss = lossRate;
  4595. };
  4596. /**
  4597. * Sets resolution that belong to the ssrc
  4598. * represented by this instance.
  4599. * @param resolution new resolution value to be set.
  4600. */
  4601. PeerStats.prototype.setSsrcResolution = function (resolution)
  4602. {
  4603. if(resolution === null && this.ssrc2resolution[ssrc])
  4604. {
  4605. delete this.ssrc2resolution[ssrc];
  4606. }
  4607. else if(resolution !== null)
  4608. this.ssrc2resolution[ssrc] = resolution;
  4609. };
  4610. /**
  4611. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  4612. * represented by this instance.
  4613. * @param ssrc audio or video RTP stream SSRC.
  4614. * @param bitrate new bitrate value to be set.
  4615. */
  4616. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  4617. {
  4618. if(this.ssrc2bitrate[ssrc])
  4619. {
  4620. this.ssrc2bitrate[ssrc].download += bitrate.download;
  4621. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  4622. }
  4623. else {
  4624. this.ssrc2bitrate[ssrc] = bitrate;
  4625. }
  4626. };
  4627. /**
  4628. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  4629. * the stream which belongs to the peer represented by this instance.
  4630. * @param ssrc RTP stream SSRC for which current audio level value will be
  4631. * updated.
  4632. * @param audioLevel the new audio level value to be set. Value is truncated to
  4633. * fit the range from 0 to 1.
  4634. */
  4635. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  4636. {
  4637. // Range limit 0 - 1
  4638. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  4639. };
  4640. function ConferenceStats() {
  4641. /**
  4642. * The bandwidth
  4643. * @type {{}}
  4644. */
  4645. this.bandwidth = {};
  4646. /**
  4647. * The bit rate
  4648. * @type {{}}
  4649. */
  4650. this.bitrate = {};
  4651. /**
  4652. * The packet loss rate
  4653. * @type {{}}
  4654. */
  4655. this.packetLoss = null;
  4656. /**
  4657. * Array with the transport information.
  4658. * @type {Array}
  4659. */
  4660. this.transport = [];
  4661. }
  4662. /**
  4663. * <tt>StatsCollector</tt> registers for stats updates of given
  4664. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  4665. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  4666. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  4667. * instance as an event source.
  4668. *
  4669. * @param peerconnection webRTC peer connection object.
  4670. * @param interval stats refresh interval given in ms.
  4671. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  4672. * called on stats update.
  4673. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  4674. * @constructor
  4675. */
  4676. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  4677. {
  4678. this.peerconnection = peerconnection;
  4679. this.baselineAudioLevelsReport = null;
  4680. this.currentAudioLevelsReport = null;
  4681. this.currentStatsReport = null;
  4682. this.baselineStatsReport = null;
  4683. this.audioLevelsIntervalId = null;
  4684. this.eventEmitter = eventEmitter;
  4685. this.config = config || {};
  4686. this.conferenceStats = new ConferenceStats();
  4687. /**
  4688. * Gather PeerConnection stats once every this many milliseconds.
  4689. */
  4690. this.GATHER_INTERVAL = 15000;
  4691. /**
  4692. * Log stats via the focus once every this many milliseconds.
  4693. */
  4694. this.LOG_INTERVAL = 60000;
  4695. /**
  4696. * Gather stats and store them in this.statsToBeLogged.
  4697. */
  4698. this.gatherStatsIntervalId = null;
  4699. /**
  4700. * Send the stats already saved in this.statsToBeLogged to be logged via
  4701. * the focus.
  4702. */
  4703. this.logStatsIntervalId = null;
  4704. /**
  4705. * Stores the statistics which will be send to the focus to be logged.
  4706. */
  4707. this.statsToBeLogged =
  4708. {
  4709. timestamps: [],
  4710. stats: {}
  4711. };
  4712. // Updates stats interval
  4713. this.audioLevelsIntervalMilis = audioLevelsInterval;
  4714. this.statsIntervalId = null;
  4715. this.statsIntervalMilis = statsInterval;
  4716. // Map of ssrcs to PeerStats
  4717. this.ssrc2stats = {};
  4718. }
  4719. module.exports = StatsCollector;
  4720. /**
  4721. * Stops stats updates.
  4722. */
  4723. StatsCollector.prototype.stop = function () {
  4724. if (this.audioLevelsIntervalId) {
  4725. clearInterval(this.audioLevelsIntervalId);
  4726. this.audioLevelsIntervalId = null;
  4727. }
  4728. if (this.statsIntervalId)
  4729. {
  4730. clearInterval(this.statsIntervalId);
  4731. this.statsIntervalId = null;
  4732. }
  4733. if(this.logStatsIntervalId)
  4734. {
  4735. clearInterval(this.logStatsIntervalId);
  4736. this.logStatsIntervalId = null;
  4737. }
  4738. if(this.gatherStatsIntervalId)
  4739. {
  4740. clearInterval(this.gatherStatsIntervalId);
  4741. this.gatherStatsIntervalId = null;
  4742. }
  4743. };
  4744. /**
  4745. * Callback passed to <tt>getStats</tt> method.
  4746. * @param error an error that occurred on <tt>getStats</tt> call.
  4747. */
  4748. StatsCollector.prototype.errorCallback = function (error)
  4749. {
  4750. logger.error("Get stats error", error);
  4751. this.stop();
  4752. };
  4753. /**
  4754. * Starts stats updates.
  4755. */
  4756. StatsCollector.prototype.start = function ()
  4757. {
  4758. var self = this;
  4759. this.audioLevelsIntervalId = setInterval(
  4760. function () {
  4761. // Interval updates
  4762. self.peerconnection.getStats(
  4763. function (report) {
  4764. var results = null;
  4765. if (!report || !report.result ||
  4766. typeof report.result != 'function') {
  4767. results = report;
  4768. }
  4769. else {
  4770. results = report.result();
  4771. }
  4772. //logger.error("Got interval report", results);
  4773. self.currentAudioLevelsReport = results;
  4774. self.processAudioLevelReport();
  4775. self.baselineAudioLevelsReport =
  4776. self.currentAudioLevelsReport;
  4777. },
  4778. self.errorCallback
  4779. );
  4780. },
  4781. self.audioLevelsIntervalMilis
  4782. );
  4783. // if (!this.config.disableStats && browserSupported) {
  4784. // this.statsIntervalId = setInterval(
  4785. // function () {
  4786. // // Interval updates
  4787. // self.peerconnection.getStats(
  4788. // function (report) {
  4789. // var results = null;
  4790. // if (!report || !report.result ||
  4791. // typeof report.result != 'function') {
  4792. // //firefox
  4793. // results = report;
  4794. // }
  4795. // else {
  4796. // //chrome
  4797. // results = report.result();
  4798. // }
  4799. // //logger.error("Got interval report", results);
  4800. // self.currentStatsReport = results;
  4801. // try {
  4802. // self.processStatsReport();
  4803. // }
  4804. // catch (e) {
  4805. // logger.error("Unsupported key:" + e, e);
  4806. // }
  4807. //
  4808. // self.baselineStatsReport = self.currentStatsReport;
  4809. // },
  4810. // self.errorCallback
  4811. // );
  4812. // },
  4813. // self.statsIntervalMilis
  4814. // );
  4815. // }
  4816. //
  4817. // if (this.config.logStats && browserSupported) {
  4818. // this.gatherStatsIntervalId = setInterval(
  4819. // function () {
  4820. // self.peerconnection.getStats(
  4821. // function (report) {
  4822. // self.addStatsToBeLogged(report.result());
  4823. // },
  4824. // function () {
  4825. // }
  4826. // );
  4827. // },
  4828. // this.GATHER_INTERVAL
  4829. // );
  4830. //
  4831. // this.logStatsIntervalId = setInterval(
  4832. // function() { self.logStats(); },
  4833. // this.LOG_INTERVAL);
  4834. // }
  4835. };
  4836. /**
  4837. * Converts the stats to the format used for logging, and saves the data in
  4838. * this.statsToBeLogged.
  4839. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  4840. */
  4841. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  4842. var self = this;
  4843. var num_records = this.statsToBeLogged.timestamps.length;
  4844. this.statsToBeLogged.timestamps.push(new Date().getTime());
  4845. reports.map(function (report) {
  4846. if (!acceptReport(report.id, report.type))
  4847. return;
  4848. var stat = self.statsToBeLogged.stats[report.id];
  4849. if (!stat) {
  4850. stat = self.statsToBeLogged.stats[report.id] = {};
  4851. }
  4852. stat.type = report.type;
  4853. report.names().map(function (name) {
  4854. if (!acceptStat(report.id, report.type, name))
  4855. return;
  4856. var values = stat[name];
  4857. if (!values) {
  4858. values = stat[name] = [];
  4859. }
  4860. while (values.length < num_records) {
  4861. values.push(null);
  4862. }
  4863. values.push(report.stat(name));
  4864. });
  4865. });
  4866. };
  4867. //FIXME:
  4868. //StatsCollector.prototype.logStats = function () {
  4869. //
  4870. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  4871. // return;
  4872. // // Reset the stats
  4873. // this.statsToBeLogged.stats = {};
  4874. // this.statsToBeLogged.timestamps = [];
  4875. //};
  4876. /**
  4877. * Stats processing logic.
  4878. */
  4879. StatsCollector.prototype.processStatsReport = function () {
  4880. if (!this.baselineStatsReport) {
  4881. return;
  4882. }
  4883. for (var idx in this.currentStatsReport) {
  4884. var now = this.currentStatsReport[idx];
  4885. try {
  4886. if (getStatValue(now, 'receiveBandwidth') ||
  4887. getStatValue(now, 'sendBandwidth')) {
  4888. this.conferenceStats.bandwidth = {
  4889. "download": Math.round(
  4890. (getStatValue(now, 'receiveBandwidth')) / 1000),
  4891. "upload": Math.round(
  4892. (getStatValue(now, 'sendBandwidth')) / 1000)
  4893. };
  4894. }
  4895. }
  4896. catch(e){/*not supported*/}
  4897. if(now.type == 'googCandidatePair')
  4898. {
  4899. var ip, type, localIP, active;
  4900. try {
  4901. ip = getStatValue(now, 'remoteAddress');
  4902. type = getStatValue(now, "transportType");
  4903. localIP = getStatValue(now, "localAddress");
  4904. active = getStatValue(now, "activeConnection");
  4905. }
  4906. catch(e){/*not supported*/}
  4907. if(!ip || !type || !localIP || active != "true")
  4908. continue;
  4909. var addressSaved = false;
  4910. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  4911. {
  4912. if(this.conferenceStats.transport[i].ip == ip &&
  4913. this.conferenceStats.transport[i].type == type &&
  4914. this.conferenceStats.transport[i].localip == localIP)
  4915. {
  4916. addressSaved = true;
  4917. }
  4918. }
  4919. if(addressSaved)
  4920. continue;
  4921. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  4922. continue;
  4923. }
  4924. if(now.type == "candidatepair")
  4925. {
  4926. if(now.state == "succeeded")
  4927. continue;
  4928. var local = this.currentStatsReport[now.localCandidateId];
  4929. var remote = this.currentStatsReport[now.remoteCandidateId];
  4930. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  4931. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  4932. }
  4933. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  4934. now.type != "inboundrtp") {
  4935. continue;
  4936. }
  4937. var before = this.baselineStatsReport[idx];
  4938. if (!before) {
  4939. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  4940. continue;
  4941. }
  4942. var ssrc = getStatValue(now, 'ssrc');
  4943. if(!ssrc)
  4944. continue;
  4945. var ssrcStats = this.ssrc2stats[ssrc];
  4946. if (!ssrcStats) {
  4947. ssrcStats = new PeerStats();
  4948. this.ssrc2stats[ssrc] = ssrcStats;
  4949. }
  4950. var isDownloadStream = true;
  4951. var key = 'packetsReceived';
  4952. var packetsNow = getStatValue(now, key);
  4953. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  4954. isDownloadStream = false;
  4955. key = 'packetsSent';
  4956. packetsNow = getStatValue(now, key);
  4957. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  4958. console.warn("No packetsReceived nor packetsSent stat found");
  4959. continue;
  4960. }
  4961. }
  4962. if (!packetsNow || packetsNow < 0)
  4963. packetsNow = 0;
  4964. var packetsBefore = getStatValue(before, key);
  4965. if (!packetsBefore || packetsBefore < 0)
  4966. packetsBefore = 0;
  4967. var packetRate = packetsNow - packetsBefore;
  4968. if (!packetRate || packetRate < 0)
  4969. packetRate = 0;
  4970. var currentLoss = getStatValue(now, 'packetsLost');
  4971. if (!currentLoss || currentLoss < 0)
  4972. currentLoss = 0;
  4973. var previousLoss = getStatValue(before, 'packetsLost');
  4974. if (!previousLoss || previousLoss < 0)
  4975. previousLoss = 0;
  4976. var lossRate = currentLoss - previousLoss;
  4977. if (!lossRate || lossRate < 0)
  4978. lossRate = 0;
  4979. var packetsTotal = (packetRate + lossRate);
  4980. ssrcStats.setSsrcLoss(ssrc,
  4981. {"packetsTotal": packetsTotal,
  4982. "packetsLost": lossRate,
  4983. "isDownloadStream": isDownloadStream});
  4984. var bytesReceived = 0, bytesSent = 0;
  4985. if(getStatValue(now, "bytesReceived")) {
  4986. bytesReceived = getStatValue(now, "bytesReceived") -
  4987. getStatValue(before, "bytesReceived");
  4988. }
  4989. if (getStatValue(now, "bytesSent")) {
  4990. bytesSent = getStatValue(now, "bytesSent") -
  4991. getStatValue(before, "bytesSent");
  4992. }
  4993. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  4994. if (bytesReceived <= 0 || time <= 0) {
  4995. bytesReceived = 0;
  4996. } else {
  4997. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  4998. }
  4999. if (bytesSent <= 0 || time <= 0) {
  5000. bytesSent = 0;
  5001. } else {
  5002. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  5003. }
  5004. ssrcStats.setSsrcBitrate(ssrc, {
  5005. "download": bytesReceived,
  5006. "upload": bytesSent});
  5007. var resolution = {height: null, width: null};
  5008. try {
  5009. if (getStatValue(now, "googFrameHeightReceived") &&
  5010. getStatValue(now, "googFrameWidthReceived")) {
  5011. resolution.height =
  5012. getStatValue(now, "googFrameHeightReceived");
  5013. resolution.width = getStatValue(now, "googFrameWidthReceived");
  5014. }
  5015. else if (getStatValue(now, "googFrameHeightSent") &&
  5016. getStatValue(now, "googFrameWidthSent")) {
  5017. resolution.height = getStatValue(now, "googFrameHeightSent");
  5018. resolution.width = getStatValue(now, "googFrameWidthSent");
  5019. }
  5020. }
  5021. catch(e){/*not supported*/}
  5022. if (resolution.height && resolution.width) {
  5023. ssrcStats.setSsrcResolution(ssrc, resolution);
  5024. } else {
  5025. ssrcStats.setSsrcResolution(ssrc, null);
  5026. }
  5027. }
  5028. var self = this;
  5029. // Jid stats
  5030. var totalPackets = {download: 0, upload: 0};
  5031. var lostPackets = {download: 0, upload: 0};
  5032. var bitrateDownload = 0;
  5033. var bitrateUpload = 0;
  5034. var resolutions = {};
  5035. Object.keys(this.ssrc2stats).forEach(
  5036. function (jid) {
  5037. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  5038. function (ssrc) {
  5039. var type = "upload";
  5040. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  5041. type = "download";
  5042. totalPackets[type] +=
  5043. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  5044. lostPackets[type] +=
  5045. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  5046. }
  5047. );
  5048. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  5049. function (ssrc) {
  5050. bitrateDownload +=
  5051. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  5052. bitrateUpload +=
  5053. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  5054. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  5055. }
  5056. );
  5057. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  5058. }
  5059. );
  5060. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  5061. this.conferenceStats.packetLoss = {
  5062. total:
  5063. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  5064. totalPackets.download + totalPackets.upload),
  5065. download:
  5066. calculatePacketLoss(lostPackets.download, totalPackets.download),
  5067. upload:
  5068. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  5069. };
  5070. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS,
  5071. {
  5072. "bitrate": this.conferenceStats.bitrate,
  5073. "packetLoss": this.conferenceStats.packetLoss,
  5074. "bandwidth": this.conferenceStats.bandwidth,
  5075. "resolution": resolutions,
  5076. "transport": this.conferenceStats.transport
  5077. });
  5078. this.conferenceStats.transport = [];
  5079. };
  5080. /**
  5081. * Stats processing logic.
  5082. */
  5083. StatsCollector.prototype.processAudioLevelReport = function () {
  5084. if (!this.baselineAudioLevelsReport) {
  5085. return;
  5086. }
  5087. for (var idx in this.currentAudioLevelsReport) {
  5088. var now = this.currentAudioLevelsReport[idx];
  5089. //if we don't have "packetsReceived" this is local stream
  5090. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  5091. continue;
  5092. }
  5093. var before = this.baselineAudioLevelsReport[idx];
  5094. if (!before) {
  5095. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5096. continue;
  5097. }
  5098. var ssrc = getStatValue(now, 'ssrc');
  5099. if (!ssrc) {
  5100. if((Date.now() - now.timestamp) < 3000)
  5101. logger.warn("No ssrc: ");
  5102. continue;
  5103. }
  5104. var ssrcStats = this.ssrc2stats[ssrc];
  5105. if (!ssrcStats) {
  5106. ssrcStats = new PeerStats();
  5107. this.ssrc2stats[ssrc] = ssrcStats;
  5108. }
  5109. // Audio level
  5110. var audioLevel = null;
  5111. try {
  5112. audioLevel = getStatValue(now, 'audioInputLevel');
  5113. if (!audioLevel)
  5114. audioLevel = getStatValue(now, 'audioOutputLevel');
  5115. }
  5116. catch(e) {/*not supported*/
  5117. logger.warn("Audio Levels are not available in the statistics.");
  5118. clearInterval(this.audioLevelsIntervalId);
  5119. return;
  5120. }
  5121. if (audioLevel) {
  5122. // TODO: can't find specs about what this value really is,
  5123. // but it seems to vary between 0 and around 32k.
  5124. audioLevel = audioLevel / 32767;
  5125. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  5126. this.eventEmitter.emit(
  5127. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel);
  5128. }
  5129. }
  5130. };
  5131. }).call(this,"/modules/statistics/RTPStatsCollector.js")
  5132. },{"../../service/statistics/Events":85,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":48}],24:[function(require,module,exports){
  5133. /* global require, APP */
  5134. var LocalStats = require("./LocalStatsCollector.js");
  5135. var RTPStats = require("./RTPStatsCollector.js");
  5136. var EventEmitter = require("events");
  5137. var StatisticsEvents = require("../../service/statistics/Events");
  5138. //var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  5139. //var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5140. //var CallStats = require("./CallStats");
  5141. //var RTCEvents = require("../../service/RTC/RTCEvents");
  5142. //
  5143. //function onDisposeConference(onUnload) {
  5144. // CallStats.sendTerminateEvent();
  5145. // stopRemote();
  5146. // if(onUnload) {
  5147. // stopLocal();
  5148. // eventEmitter.removeAllListeners();
  5149. // }
  5150. //}
  5151. var eventEmitter = new EventEmitter();
  5152. function Statistics() {
  5153. this.rtpStats = null;
  5154. this.eventEmitter = new EventEmitter();
  5155. }
  5156. Statistics.prototype.startRemoteStats = function (peerconnection) {
  5157. if (this.rtpStats) {
  5158. this.rtpStats.stop();
  5159. }
  5160. this.rtpStats = new RTPStats(peerconnection, 200, 2000, this.eventEmitter);
  5161. this.rtpStats.start();
  5162. }
  5163. Statistics.localStats = [];
  5164. Statistics.startLocalStats = function (stream, callback) {
  5165. var localStats = new LocalStats(stream, 200, callback);
  5166. this.localStats.push(localStats);
  5167. localStats.start();
  5168. }
  5169. Statistics.prototype.addAudioLevelListener = function(listener)
  5170. {
  5171. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  5172. }
  5173. Statistics.prototype.removeAudioLevelListener = function(listener)
  5174. {
  5175. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  5176. }
  5177. Statistics.prototype.dispose = function () {
  5178. Statistics.stopAllLocalStats();
  5179. this.stopRemote();
  5180. if(this.eventEmitter)
  5181. this.eventEmitter.removeAllListeners();
  5182. if(eventEmitter)
  5183. eventEmitter.removeAllListeners();
  5184. }
  5185. Statistics.stopAllLocalStats = function () {
  5186. for(var i = 0; i < this.localStats.length; i++)
  5187. this.localStats[i].stop();
  5188. this.localStats = [];
  5189. }
  5190. Statistics.stopLocalStats = function (stream) {
  5191. for(var i = 0; i < Statistics.localStats.length; i++)
  5192. if(Statistics.localStats[i].stream === stream){
  5193. var localStats = Statistics.localStats.splice(i, 1);
  5194. localStats.stop();
  5195. break;
  5196. }
  5197. }
  5198. Statistics.prototype.stopRemote = function () {
  5199. if (this.rtpStats) {
  5200. this.rtpStats.stop();
  5201. this.eventEmitter.emit(StatisticsEvents.STOP);
  5202. this.rtpStats = null;
  5203. }
  5204. };
  5205. /**
  5206. * Obtains audio level reported in the stats for specified peer.
  5207. * @param peerJid full MUC jid of the user for whom we want to obtain last
  5208. * audio level.
  5209. * @param ssrc the SSRC of audio stream for which we want to obtain audio
  5210. * level.
  5211. * @returns {*} a float form 0 to 1 that represents current audio level or
  5212. * <tt>null</tt> if for any reason the value is not available
  5213. * at this time.
  5214. */
  5215. Statistics.prototype.getPeerSSRCAudioLevel = function (peerJid, ssrc) {
  5216. var peerStats = this.rtpStats.jid2stats[peerJid];
  5217. return peerStats ? peerStats.ssrc2AudioLevel[ssrc] : null;
  5218. };
  5219. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  5220. //
  5221. //var statistics = {
  5222. // /**
  5223. // * Indicates that this audio level is for local jid.
  5224. // * @type {string}
  5225. // */
  5226. // LOCAL_JID: 'local',
  5227. //
  5228. // addConnectionStatsListener: function(listener)
  5229. // {
  5230. // eventEmitter.on("statistics.connectionstats", listener);
  5231. // },
  5232. //
  5233. // removeConnectionStatsListener: function(listener)
  5234. // {
  5235. // eventEmitter.removeListener("statistics.connectionstats", listener);
  5236. // },
  5237. //
  5238. //
  5239. // addRemoteStatsStopListener: function(listener)
  5240. // {
  5241. // eventEmitter.on("statistics.stop", listener);
  5242. // },
  5243. //
  5244. // removeRemoteStatsStopListener: function(listener)
  5245. // {
  5246. // eventEmitter.removeListener("statistics.stop", listener);
  5247. // },
  5248. //
  5249. //
  5250. // stopRemoteStatistics: function()
  5251. // {
  5252. // stopRemote();
  5253. // },
  5254. //
  5255. //// Already implemented with the constructor
  5256. // start: function () {
  5257. // APP.RTC.addStreamListener(onStreamCreated,
  5258. // StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  5259. // APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  5260. // //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  5261. // APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  5262. // startRemoteStats(event.peerconnection);
  5263. //// CallStats.init(event);
  5264. // });
  5265. //// APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  5266. //// CallStats.init(session);
  5267. //// });
  5268. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  5269. //// APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  5270. //// CallStats.sendMuteEvent(mute, "audio");
  5271. //// });
  5272. //// APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  5273. //// CallStats.sendSetupFailedEvent();
  5274. //// });
  5275. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  5276. //// APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  5277. //// CallStats.sendMuteEvent(mute, "video");
  5278. //// });
  5279. // }
  5280. //};
  5281. module.exports = Statistics;
  5282. },{"../../service/statistics/Events":85,"../../service/statistics/constants":86,"./LocalStatsCollector.js":22,"./RTPStatsCollector.js":23,"events":44}],25:[function(require,module,exports){
  5283. /**
  5284. /**
  5285. * @const
  5286. */
  5287. var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  5288. /**
  5289. * Hexadecimal digits.
  5290. * @const
  5291. */
  5292. var HEX_DIGITS = '0123456789abcdef';
  5293. /**
  5294. * Generates random int within the range [min, max]
  5295. * @param min the minimum value for the generated number
  5296. * @param max the maximum value for the generated number
  5297. * @returns random int number
  5298. */
  5299. function randomInt(min, max) {
  5300. return Math.floor(Math.random() * (max - min + 1)) + min;
  5301. }
  5302. /**
  5303. * Get random element from array or string.
  5304. * @param {Array|string} arr source
  5305. * @returns array element or string character
  5306. */
  5307. function randomElement(arr) {
  5308. return arr[randomInt(0, arr.length - 1)];
  5309. }
  5310. /**
  5311. * Generate random alphanumeric string.
  5312. * @param {number} length expected string length
  5313. * @returns {string} random string of specified length
  5314. */
  5315. function randomAlphanumStr(length) {
  5316. var result = '';
  5317. for (var i = 0; i < length; i += 1) {
  5318. result += randomElement(ALPHANUM);
  5319. }
  5320. return result;
  5321. }
  5322. /**
  5323. * Exported interface.
  5324. */
  5325. var RandomUtil = {
  5326. /**
  5327. * Returns a random hex digit.
  5328. * @returns {*}
  5329. */
  5330. randomHexDigit: function() {
  5331. return randomElement(HEX_DIGITS);
  5332. },
  5333. /**
  5334. * Returns a random string of hex digits with length 'len'.
  5335. * @param len the length.
  5336. */
  5337. randomHexString: function (len) {
  5338. var ret = '';
  5339. while (len--) {
  5340. ret += this.randomHexDigit();
  5341. }
  5342. return ret;
  5343. },
  5344. randomElement: randomElement,
  5345. randomAlphanumStr: randomAlphanumStr
  5346. };
  5347. module.exports = RandomUtil;
  5348. },{}],26:[function(require,module,exports){
  5349. (function (__filename){
  5350. /* global Strophe, $, $pres, $iq, $msg */
  5351. /* jshint -W101,-W069 */
  5352. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5353. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5354. var Moderator = require("./moderator");
  5355. var EventEmitter = require("events");
  5356. var Recorder = require("./recording");
  5357. var JIBRI_XMLNS = 'http://jitsi.org/protocol/jibri';
  5358. var parser = {
  5359. packet2JSON: function (packet, nodes) {
  5360. var self = this;
  5361. $(packet).children().each(function (index) {
  5362. var tagName = $(this).prop("tagName");
  5363. var node = {
  5364. tagName: tagName
  5365. };
  5366. node.attributes = {};
  5367. $($(this)[0].attributes).each(function( index, attr ) {
  5368. node.attributes[ attr.name ] = attr.value;
  5369. });
  5370. var text = Strophe.getText($(this)[0]);
  5371. if (text) {
  5372. node.value = text;
  5373. }
  5374. node.children = [];
  5375. nodes.push(node);
  5376. self.packet2JSON($(this), node.children);
  5377. });
  5378. },
  5379. JSON2packet: function (nodes, packet) {
  5380. for(var i = 0; i < nodes.length; i++) {
  5381. var node = nodes[i];
  5382. if(!node || node === null){
  5383. continue;
  5384. }
  5385. packet.c(node.tagName, node.attributes);
  5386. if(node.value)
  5387. packet.t(node.value);
  5388. if(node.children)
  5389. this.JSON2packet(node.children, packet);
  5390. packet.up();
  5391. }
  5392. // packet.up();
  5393. }
  5394. };
  5395. /**
  5396. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  5397. * @param pres the presence JSON
  5398. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  5399. */
  5400. function filterNodeFromPresenceJSON(pres, nodeName){
  5401. var res = [];
  5402. for(var i = 0; i < pres.length; i++)
  5403. if(pres[i].tagName === nodeName)
  5404. res.push(pres[i]);
  5405. return res;
  5406. }
  5407. function ChatRoom(connection, jid, password, XMPP, options) {
  5408. this.eventEmitter = new EventEmitter();
  5409. this.xmpp = XMPP;
  5410. this.connection = connection;
  5411. this.roomjid = Strophe.getBareJidFromJid(jid);
  5412. this.myroomjid = jid;
  5413. this.password = password;
  5414. logger.info("Joined MUC as " + this.myroomjid);
  5415. this.members = {};
  5416. this.presMap = {};
  5417. this.presHandlers = {};
  5418. this.joined = false;
  5419. this.role = 'none';
  5420. this.focusMucJid = null;
  5421. this.bridgeIsDown = false;
  5422. this.options = options || {};
  5423. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter);
  5424. this.initPresenceMap();
  5425. this.session = null;
  5426. var self = this;
  5427. this.lastPresences = {};
  5428. this.phoneNumber = null;
  5429. this.phonePin = null;
  5430. }
  5431. ChatRoom.prototype.initPresenceMap = function () {
  5432. this.presMap['to'] = this.myroomjid;
  5433. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  5434. this.presMap["nodes"] = [];
  5435. this.presMap["nodes"].push( {
  5436. "tagName": "user-agent",
  5437. "value": navigator.userAgent,
  5438. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  5439. });
  5440. };
  5441. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  5442. this.presMap["nodes"].push( {
  5443. "tagName": "devices",
  5444. "children": [
  5445. {
  5446. "tagName": "audio",
  5447. "value": devices.audio,
  5448. },
  5449. {
  5450. "tagName": "video",
  5451. "value": devices.video,
  5452. }
  5453. ]
  5454. });
  5455. };
  5456. ChatRoom.prototype.join = function (password) {
  5457. if(password)
  5458. this.password = password;
  5459. var self = this;
  5460. this.moderator.allocateConferenceFocus(function()
  5461. {
  5462. self.sendPresence();
  5463. }.bind(this));
  5464. };
  5465. ChatRoom.prototype.sendPresence = function () {
  5466. if (!this.presMap['to']) {
  5467. // Too early to send presence - not initialized
  5468. return;
  5469. }
  5470. var pres = $pres({to: this.presMap['to'] });
  5471. pres.c('x', {xmlns: this.presMap['xns']});
  5472. if (this.password) {
  5473. pres.c('password').t(this.password).up();
  5474. }
  5475. pres.up();
  5476. // Send XEP-0115 'c' stanza that contains our capabilities info
  5477. if (this.connection.caps) {
  5478. this.connection.caps.node = this.xmpp.options.clientNode;
  5479. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  5480. }
  5481. parser.JSON2packet(this.presMap.nodes, pres);
  5482. this.connection.send(pres);
  5483. };
  5484. ChatRoom.prototype.doLeave = function () {
  5485. logger.log("do leave", this.myroomjid);
  5486. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  5487. this.presMap.length = 0;
  5488. this.connection.send(pres);
  5489. };
  5490. ChatRoom.prototype.createNonAnonymousRoom = function () {
  5491. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  5492. var getForm = $iq({type: 'get', to: this.roomjid})
  5493. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  5494. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5495. var self = this;
  5496. this.connection.sendIQ(getForm, function (form) {
  5497. if (!$(form).find(
  5498. '>query>x[xmlns="jabber:x:data"]' +
  5499. '>field[var="muc#roomconfig_whois"]').length) {
  5500. logger.error('non-anonymous rooms not supported');
  5501. return;
  5502. }
  5503. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  5504. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5505. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5506. formSubmit.c('field', {'var': 'FORM_TYPE'})
  5507. .c('value')
  5508. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5509. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  5510. .c('value').t('anyone').up().up();
  5511. self.connection.sendIQ(formSubmit);
  5512. }, function (error) {
  5513. logger.error("Error getting room configuration form");
  5514. });
  5515. };
  5516. ChatRoom.prototype.onPresence = function (pres) {
  5517. console.log(pres);
  5518. var from = pres.getAttribute('from');
  5519. // Parse roles.
  5520. var member = {};
  5521. member.show = $(pres).find('>show').text();
  5522. member.status = $(pres).find('>status').text();
  5523. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  5524. member.affiliation = tmp.attr('affiliation');
  5525. member.role = tmp.attr('role');
  5526. // Focus recognition
  5527. member.jid = tmp.attr('jid');
  5528. member.isFocus = false;
  5529. if (member.jid
  5530. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") === 0) {
  5531. member.isFocus = true;
  5532. }
  5533. $(pres).find(">x").remove();
  5534. var nodes = [];
  5535. parser.packet2JSON(pres, nodes);
  5536. this.lastPresences[from] = nodes;
  5537. var jibri = null;
  5538. for(var i = 0; i < nodes.length; i++)
  5539. {
  5540. var node = nodes[i];
  5541. switch(node.tagName)
  5542. {
  5543. case "nick":
  5544. member.nick = node.value;
  5545. if(!member.isFocus) {
  5546. var displayName = !this.xmpp.options.displayJids
  5547. ? member.nick : Strophe.getResourceFromJid(from);
  5548. if (displayName && displayName.length > 0) {
  5549. this.eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  5550. }
  5551. logger.info("Display name: " + displayName, pres);
  5552. }
  5553. break;
  5554. case "userId":
  5555. member.id = node.value;
  5556. break;
  5557. case "email":
  5558. member.email = node.value;
  5559. break;
  5560. case "bridgeIsDown":
  5561. if(!this.bridgeIsDown) {
  5562. this.bridgeIsDown = true;
  5563. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  5564. }
  5565. break;
  5566. case "jibri-recording-status":
  5567. var jibri = node;
  5568. break;
  5569. case "call-control":
  5570. console.log(pres);
  5571. var att = node.attributes;
  5572. if(!att)
  5573. break;
  5574. this.phoneNumber = att.phone || null;
  5575. this.phonePin = att.pin || null;
  5576. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  5577. break;
  5578. default :
  5579. this.processNode(node, from);
  5580. }
  5581. }
  5582. if (from == this.myroomjid) {
  5583. if (member.affiliation == 'owner')
  5584. if (this.role !== member.role) {
  5585. this.role = member.role;
  5586. this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED, this.role);
  5587. }
  5588. if (!this.joined) {
  5589. this.joined = true;
  5590. console.log("(TIME) MUC joined:\t", window.performance.now());
  5591. this.eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  5592. }
  5593. } else if (this.members[from] === undefined) {
  5594. // new participant
  5595. this.members[from] = member;
  5596. logger.log('entered', from, member);
  5597. if (member.isFocus) {
  5598. this.focusMucJid = from;
  5599. if(!this.recording) {
  5600. this.recording = new Recorder(this.eventEmitter, this.connection,
  5601. this.focusMucJid);
  5602. if(this.lastJibri)
  5603. this.recording.handleJibriPresence(this.lastJibri);
  5604. }
  5605. logger.info("Ignore focus: " + from + ", real JID: " + member.jid);
  5606. }
  5607. else {
  5608. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, member.id || member.email, member.nick);
  5609. }
  5610. } else {
  5611. // Presence update for existing participant
  5612. // Watch role change:
  5613. if (this.members[from].role != member.role) {
  5614. this.members[from].role = member.role;
  5615. this.eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  5616. }
  5617. // store the new display name
  5618. if(member.displayName)
  5619. this.members[from].displayName = member.displayName;
  5620. }
  5621. if(!member.isFocus)
  5622. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id || member.email);
  5623. // Trigger status message update
  5624. if (member.status) {
  5625. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  5626. }
  5627. if(jibri)
  5628. {
  5629. this.lastJibri = jibri;
  5630. if(this.recording)
  5631. this.recording.handleJibriPresence(jibri);
  5632. }
  5633. };
  5634. ChatRoom.prototype.processNode = function (node, from) {
  5635. if(this.presHandlers[node.tagName])
  5636. this.presHandlers[node.tagName](node, from);
  5637. };
  5638. ChatRoom.prototype.sendMessage = function (body, nickname) {
  5639. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5640. msg.c('body', body).up();
  5641. if (nickname) {
  5642. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  5643. }
  5644. this.connection.send(msg);
  5645. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  5646. };
  5647. ChatRoom.prototype.setSubject = function (subject) {
  5648. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5649. msg.c('subject', subject);
  5650. this.connection.send(msg);
  5651. logger.log("topic changed to " + subject);
  5652. };
  5653. ChatRoom.prototype.onParticipantLeft = function (jid) {
  5654. delete this.lastPresences[jid];
  5655. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  5656. this.moderator.onMucMemberLeft(jid);
  5657. };
  5658. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  5659. // room destroyed ?
  5660. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5661. '>destroy').length) {
  5662. var reason;
  5663. var reasonSelect = $(pres).find(
  5664. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5665. '>destroy>reason');
  5666. if (reasonSelect.length) {
  5667. reason = reasonSelect.text();
  5668. }
  5669. this.xmpp.leaveRoom(this.roomjid);
  5670. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  5671. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(from)];
  5672. return true;
  5673. }
  5674. // Status code 110 indicates that this notification is "self-presence".
  5675. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  5676. delete this.members[from];
  5677. this.onParticipantLeft(from);
  5678. }
  5679. // If the status code is 110 this means we're leaving and we would like
  5680. // to remove everyone else from our view, so we trigger the event.
  5681. else if (Object.keys(this.members).length > 1) {
  5682. for (var i in this.members) {
  5683. var member = this.members[i];
  5684. delete this.members[i];
  5685. this.onParticipantLeft(member);
  5686. }
  5687. }
  5688. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  5689. if (this.myroomjid === from) {
  5690. this.xmpp.leaveRoom(this.roomjid);
  5691. this.eventEmitter.emit(XMPPEvents.KICKED);
  5692. }
  5693. }
  5694. };
  5695. ChatRoom.prototype.onMessage = function (msg, from) {
  5696. var nick =
  5697. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  5698. .text() ||
  5699. Strophe.getResourceFromJid(from);
  5700. var txt = $(msg).find('>body').text();
  5701. var type = msg.getAttribute("type");
  5702. if (type == "error") {
  5703. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  5704. $(msg).find('>text').text(), txt);
  5705. return true;
  5706. }
  5707. var subject = $(msg).find('>subject');
  5708. if (subject.length) {
  5709. var subjectText = subject.text();
  5710. if (subjectText || subjectText === "") {
  5711. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  5712. logger.log("Subject is changed to " + subjectText);
  5713. }
  5714. }
  5715. // xep-0203 delay
  5716. var stamp = $(msg).find('>delay').attr('stamp');
  5717. if (!stamp) {
  5718. // or xep-0091 delay, UTC timestamp
  5719. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  5720. if (stamp) {
  5721. // the format is CCYYMMDDThh:mm:ss
  5722. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  5723. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  5724. }
  5725. }
  5726. if (txt) {
  5727. logger.log('chat', nick, txt);
  5728. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  5729. from, nick, txt, this.myroomjid, stamp);
  5730. }
  5731. };
  5732. ChatRoom.prototype.onPresenceError = function (pres, from) {
  5733. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5734. logger.log('on password required', from);
  5735. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  5736. } else if ($(pres).find(
  5737. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5738. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  5739. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  5740. // enter the room by replying with 'not-authorized'. This would
  5741. // result in reconnection from authorized domain.
  5742. // We're either missing Jicofo/Prosody config for anonymous
  5743. // domains or something is wrong.
  5744. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  5745. } else {
  5746. logger.warn('onPresError ', pres);
  5747. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5748. }
  5749. } else {
  5750. logger.warn('onPresError ', pres);
  5751. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5752. }
  5753. };
  5754. ChatRoom.prototype.kick = function (jid) {
  5755. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  5756. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  5757. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  5758. .c('reason').t('You have been kicked.').up().up().up();
  5759. this.connection.sendIQ(
  5760. kickIQ,
  5761. function (result) {
  5762. logger.log('Kick participant with jid: ', jid, result);
  5763. },
  5764. function (error) {
  5765. logger.log('Kick participant error: ', error);
  5766. });
  5767. };
  5768. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  5769. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  5770. var ob = this;
  5771. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  5772. function (res) {
  5773. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  5774. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5775. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5776. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5777. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  5778. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  5779. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  5780. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  5781. ob.connection.sendIQ(formsubmit,
  5782. onSuccess,
  5783. onError);
  5784. } else {
  5785. onNotSupported();
  5786. }
  5787. }, onError);
  5788. };
  5789. ChatRoom.prototype.addToPresence = function (key, values) {
  5790. values.tagName = key;
  5791. this.presMap["nodes"].push(values);
  5792. };
  5793. ChatRoom.prototype.removeFromPresence = function (key) {
  5794. for(var i = 0; i < this.presMap.nodes.length; i++)
  5795. {
  5796. if(key === this.presMap.nodes[i].tagName)
  5797. this.presMap.nodes.splice(i, 1);
  5798. }
  5799. };
  5800. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  5801. this.presHandlers[name] = handler;
  5802. };
  5803. ChatRoom.prototype.removePresenceListener = function (name) {
  5804. delete this.presHandlers[name];
  5805. };
  5806. ChatRoom.prototype.isModerator = function () {
  5807. return this.role === 'moderator';
  5808. };
  5809. ChatRoom.prototype.getMemberRole = function (peerJid) {
  5810. if (this.members[peerJid]) {
  5811. return this.members[peerJid].role;
  5812. }
  5813. return null;
  5814. };
  5815. ChatRoom.prototype.setJingleSession = function(session){
  5816. this.session = session;
  5817. this.session.room = this;
  5818. };
  5819. ChatRoom.prototype.removeStream = function (stream, callback) {
  5820. if(!this.session)
  5821. return;
  5822. this.session.removeStream(stream, callback);
  5823. };
  5824. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  5825. if(this.session) {
  5826. // FIXME: will block switchInProgress on true value in case of exception
  5827. this.session.switchStreams(stream, oldStream, callback, isAudio);
  5828. } else {
  5829. // We are done immediately
  5830. logger.warn("No conference handler or conference not started yet");
  5831. callback();
  5832. }
  5833. };
  5834. ChatRoom.prototype.addStream = function (stream, callback) {
  5835. if(this.session) {
  5836. // FIXME: will block switchInProgress on true value in case of exception
  5837. this.session.addStream(stream, callback);
  5838. } else {
  5839. // We are done immediately
  5840. logger.warn("No conference handler or conference not started yet");
  5841. callback();
  5842. }
  5843. };
  5844. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  5845. var self = this;
  5846. var localCallback = function (mute) {
  5847. self.sendVideoInfoPresence(mute);
  5848. if(callback)
  5849. callback(mute);
  5850. };
  5851. if(this.session)
  5852. {
  5853. this.session.setVideoMute(
  5854. mute, localCallback, options);
  5855. }
  5856. else {
  5857. localCallback(mute);
  5858. }
  5859. };
  5860. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  5861. //This will be for remote streams only
  5862. // if (this.forceMuted && !mute) {
  5863. // logger.info("Asking focus for unmute");
  5864. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  5865. // // FIXME: wait for result before resetting muted status
  5866. // this.forceMuted = false;
  5867. // }
  5868. return this.sendAudioInfoPresence(mute, callback);
  5869. };
  5870. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  5871. this.removeFromPresence("audiomuted");
  5872. this.addToPresence("audiomuted",
  5873. {attributes:
  5874. {"audions": "http://jitsi.org/jitmeet/audio"},
  5875. value: mute.toString()});
  5876. };
  5877. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  5878. this.addAudioInfoToPresence(mute);
  5879. if(this.connection) {
  5880. this.sendPresence();
  5881. }
  5882. if(callback)
  5883. callback();
  5884. };
  5885. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  5886. this.removeFromPresence("videomuted");
  5887. this.addToPresence("videomuted",
  5888. {attributes:
  5889. {"videons": "http://jitsi.org/jitmeet/video"},
  5890. value: mute.toString()});
  5891. };
  5892. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  5893. this.addVideoInfoToPresence(mute);
  5894. if(!this.connection)
  5895. return;
  5896. this.sendPresence();
  5897. };
  5898. ChatRoom.prototype.addListener = function(type, listener) {
  5899. this.eventEmitter.on(type, listener);
  5900. };
  5901. ChatRoom.prototype.removeListener = function (type, listener) {
  5902. this.eventEmitter.removeListener(type, listener);
  5903. };
  5904. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  5905. if(this.lastPresences[data.peerjid])
  5906. {
  5907. var pres = this.lastPresences[data.peerjid];
  5908. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  5909. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  5910. data.videomuted = ((videomuted.length > 0
  5911. && videomuted[0]
  5912. && videomuted[0]["value"] === "true")? true : false);
  5913. data.audiomuted = ((audiomuted.length > 0
  5914. && audiomuted[0]
  5915. && audiomuted[0]["value"] === "true")? true : false);
  5916. }
  5917. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  5918. };
  5919. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  5920. if (!this.session)
  5921. return null;
  5922. return this.session.getSsrcOwner(ssrc);
  5923. };
  5924. /**
  5925. * Returns true if the recording is supproted and false if not.
  5926. */
  5927. ChatRoom.prototype.isRecordingSupported = function () {
  5928. if(this.recording)
  5929. return this.recording.isSupported();
  5930. return false;
  5931. };
  5932. /**
  5933. * Returns null if the recording is not supported, "on" if the recording started
  5934. * and "off" if the recording is not started.
  5935. */
  5936. ChatRoom.prototype.getRecordingState = function () {
  5937. if(this.recording)
  5938. return this.recording.getState();
  5939. return "off";
  5940. }
  5941. /**
  5942. * Returns the url of the recorded video.
  5943. */
  5944. ChatRoom.prototype.getRecordingURL = function () {
  5945. if(this.recording)
  5946. return this.recording.getURL();
  5947. return null;
  5948. }
  5949. /**
  5950. * Starts/stops the recording
  5951. * @param token token for authentication
  5952. */
  5953. ChatRoom.prototype.toggleRecording = function (token, followEntity) {
  5954. if(this.recording)
  5955. return this.recording.toggleRecording(token, followEntity);
  5956. return new Promise(function(resolve, reject){
  5957. reject(new Error("The conference is not created yet!"))});
  5958. }
  5959. /**
  5960. * Dials a number.
  5961. * @param number the number
  5962. */
  5963. ChatRoom.prototype.dial = function (number) {
  5964. return this.connection.rayo.dial(number, "fromnumber",
  5965. Strophe.getNodeFromJid(this.myroomjid), this.password,
  5966. this.focusMucJid);
  5967. }
  5968. /**
  5969. * Hangup an existing call
  5970. */
  5971. ChatRoom.prototype.hangup = function () {
  5972. return this.connection.rayo.hangup();
  5973. }
  5974. /**
  5975. * Returns the phone number for joining the conference.
  5976. */
  5977. ChatRoom.prototype.getPhoneNumber = function () {
  5978. return this.phoneNumber;
  5979. }
  5980. /**
  5981. * Returns the pin for joining the conference with phone.
  5982. */
  5983. ChatRoom.prototype.getPhonePin = function () {
  5984. return this.phonePin;
  5985. }
  5986. /**
  5987. * Returns the connection state for the current session.
  5988. */
  5989. ChatRoom.prototype.getConnectionState = function () {
  5990. if(!this.session)
  5991. return null;
  5992. return this.session.getIceConnectionState();
  5993. }
  5994. module.exports = ChatRoom;
  5995. }).call(this,"/modules/xmpp/ChatRoom.js")
  5996. },{"../../service/xmpp/XMPPEvents":87,"./moderator":34,"./recording":35,"events":44,"jitsi-meet-logger":48}],27:[function(require,module,exports){
  5997. (function (__filename){
  5998. /*
  5999. * JingleSession provides an API to manage a single Jingle session. We will
  6000. * have different implementations depending on the underlying interface used
  6001. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  6002. */
  6003. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6004. function JingleSession(me, sid, connection, service, eventEmitter) {
  6005. /**
  6006. * Our JID.
  6007. */
  6008. this.me = me;
  6009. /**
  6010. * The Jingle session identifier.
  6011. */
  6012. this.sid = sid;
  6013. /**
  6014. * The XMPP connection.
  6015. */
  6016. this.connection = connection;
  6017. /**
  6018. * The XMPP service.
  6019. */
  6020. this.service = service;
  6021. /**
  6022. * The event emitter.
  6023. */
  6024. this.eventEmitter = eventEmitter;
  6025. /**
  6026. * Whether to use dripping or not. Dripping is sending trickle candidates
  6027. * not one-by-one.
  6028. * Note: currently we do not support 'false'.
  6029. */
  6030. this.usedrip = true;
  6031. /**
  6032. * When dripping is used, stores ICE candidates which are to be sent.
  6033. */
  6034. this.drip_container = [];
  6035. // Media constraints. Is this WebRTC only?
  6036. this.media_constraints = null;
  6037. // ICE servers config (RTCConfiguration?).
  6038. this.ice_config = {};
  6039. // The chat room instance associated with the session.
  6040. this.room = null;
  6041. }
  6042. /**
  6043. * Prepares this object to initiate a session.
  6044. * @param peerjid the JID of the remote peer.
  6045. * @param isInitiator whether we will be the Jingle initiator.
  6046. * @param media_constraints
  6047. * @param ice_config
  6048. */
  6049. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  6050. media_constraints, ice_config) {
  6051. this.media_constraints = media_constraints;
  6052. this.ice_config = ice_config;
  6053. if (this.state !== null) {
  6054. logger.error('attempt to initiate on session ' + this.sid +
  6055. 'in state ' + this.state);
  6056. return;
  6057. }
  6058. this.state = 'pending';
  6059. this.initiator = isInitiator ? this.me : peerjid;
  6060. this.responder = !isInitiator ? this.me : peerjid;
  6061. this.peerjid = peerjid;
  6062. this.doInitialize();
  6063. };
  6064. /**
  6065. * Finishes initialization.
  6066. */
  6067. JingleSession.prototype.doInitialize = function() {};
  6068. /**
  6069. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  6070. * Note: currently only used on transport-info
  6071. */
  6072. JingleSession.prototype.addIceCandidates = function(contents) {};
  6073. /**
  6074. * Handles an 'add-source' event.
  6075. *
  6076. * @param contents an array of Jingle 'content' elements.
  6077. */
  6078. JingleSession.prototype.addSources = function(contents) {};
  6079. /**
  6080. * Handles a 'remove-source' event.
  6081. *
  6082. * @param contents an array of Jingle 'content' elements.
  6083. */
  6084. JingleSession.prototype.removeSources = function(contents) {};
  6085. /**
  6086. * Terminates this Jingle session (stops sending media and closes the streams?)
  6087. */
  6088. JingleSession.prototype.terminate = function() {};
  6089. /**
  6090. * Sends a Jingle session-terminate message to the peer and terminates the
  6091. * session.
  6092. * @param reason
  6093. * @param text
  6094. */
  6095. JingleSession.prototype.sendTerminate = function(reason, text) {};
  6096. /**
  6097. * Handles an offer from the remote peer (prepares to accept a session).
  6098. * @param jingle the 'jingle' XML element.
  6099. */
  6100. JingleSession.prototype.setOffer = function(jingle) {};
  6101. /**
  6102. * Handles an answer from the remote peer (prepares to accept a session).
  6103. * @param jingle the 'jingle' XML element.
  6104. */
  6105. JingleSession.prototype.setAnswer = function(jingle) {};
  6106. module.exports = JingleSession;
  6107. }).call(this,"/modules/xmpp/JingleSession.js")
  6108. },{"jitsi-meet-logger":48}],28:[function(require,module,exports){
  6109. (function (__filename){
  6110. /* jshint -W117 */
  6111. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6112. var JingleSession = require("./JingleSession");
  6113. var TraceablePeerConnection = require("./TraceablePeerConnection");
  6114. var SDPDiffer = require("./SDPDiffer");
  6115. var SDPUtil = require("./SDPUtil");
  6116. var SDP = require("./SDP");
  6117. var async = require("async");
  6118. var transform = require("sdp-transform");
  6119. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  6120. var RTCBrowserType = require("../RTC/RTCBrowserType");
  6121. var SSRCReplacement = require("./LocalSSRCReplacement");
  6122. var RTC = require("../RTC/RTC");
  6123. // Jingle stuff
  6124. function JingleSessionPC(me, sid, connection, service) {
  6125. JingleSession.call(this, me, sid, connection, service);
  6126. this.initiator = null;
  6127. this.responder = null;
  6128. this.peerjid = null;
  6129. this.state = null;
  6130. this.localSDP = null;
  6131. this.remoteSDP = null;
  6132. this.relayedStreams = [];
  6133. this.usetrickle = true;
  6134. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  6135. this.hadstuncandidate = false;
  6136. this.hadturncandidate = false;
  6137. this.lasticecandidate = false;
  6138. this.statsinterval = null;
  6139. this.reason = null;
  6140. this.addssrc = [];
  6141. this.removessrc = [];
  6142. this.pendingop = null;
  6143. this.switchstreams = false;
  6144. this.addingStreams = false;
  6145. this.wait = true;
  6146. /**
  6147. * A map that stores SSRCs of local streams
  6148. * @type {{}} maps media type('audio' or 'video') to SSRC number
  6149. */
  6150. this.localStreamsSSRC = {};
  6151. this.ssrcOwners = {};
  6152. this.ssrcVideoTypes = {};
  6153. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  6154. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  6155. /**
  6156. * The indicator which determines whether the (local) video has been muted
  6157. * in response to a user command in contrast to an automatic decision made
  6158. * by the application logic.
  6159. */
  6160. this.videoMuteByUser = false;
  6161. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  6162. // We start with the queue paused. We resume it when the signaling state is
  6163. // stable and the ice connection state is connected.
  6164. this.modifySourcesQueue.pause();
  6165. }
  6166. //XXX this is badly broken...
  6167. JingleSessionPC.prototype = JingleSession.prototype;
  6168. JingleSessionPC.prototype.constructor = JingleSessionPC;
  6169. JingleSessionPC.prototype.setOffer = function(offer) {
  6170. this.setRemoteDescription(offer, 'offer');
  6171. };
  6172. JingleSessionPC.prototype.setAnswer = function(answer) {
  6173. this.setRemoteDescription(answer, 'answer');
  6174. };
  6175. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  6176. var signalingState = this.peerconnection.signalingState;
  6177. var iceConnectionState = this.peerconnection.iceConnectionState;
  6178. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  6179. this.modifySourcesQueue.resume();
  6180. } else {
  6181. this.modifySourcesQueue.pause();
  6182. }
  6183. };
  6184. JingleSessionPC.prototype.doInitialize = function () {
  6185. var self = this;
  6186. this.hadstuncandidate = false;
  6187. this.hadturncandidate = false;
  6188. this.lasticecandidate = false;
  6189. // True if reconnect is in progress
  6190. this.isreconnect = false;
  6191. // Set to true if the connection was ever stable
  6192. this.wasstable = false;
  6193. this.peerconnection = new TraceablePeerConnection(
  6194. this.connection.jingle.ice_config,
  6195. RTC.getPCConstraints(),
  6196. this);
  6197. this.peerconnection.onicecandidate = function (event) {
  6198. var protocol;
  6199. if (event && event.candidate) {
  6200. protocol = (typeof event.candidate.protocol === 'string')
  6201. ? event.candidate.protocol.toLowerCase() : '';
  6202. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  6203. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  6204. return;
  6205. }
  6206. }
  6207. self.sendIceCandidate(event.candidate);
  6208. };
  6209. this.peerconnection.onaddstream = function (event) {
  6210. if (event.stream.id !== 'default') {
  6211. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  6212. self.remoteStreamAdded(event);
  6213. } else {
  6214. // This is a recvonly stream. Clients that implement Unified Plan,
  6215. // such as Firefox use recvonly "streams/channels/tracks" for
  6216. // receiving remote stream/tracks, as opposed to Plan B where there
  6217. // are only 3 channels: audio, video and data.
  6218. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  6219. }
  6220. };
  6221. this.peerconnection.onremovestream = function (event) {
  6222. // Remove the stream from remoteStreams
  6223. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  6224. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  6225. };
  6226. this.peerconnection.onsignalingstatechange = function (event) {
  6227. if (!(self && self.peerconnection)) return;
  6228. if (self.peerconnection.signalingState === 'stable') {
  6229. self.wasstable = true;
  6230. }
  6231. self.updateModifySourcesQueue();
  6232. };
  6233. /**
  6234. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  6235. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  6236. * RTCPeerConnection.iceConnectionState changes.
  6237. *
  6238. * @param event the event containing information about the change
  6239. */
  6240. this.peerconnection.oniceconnectionstatechange = function (event) {
  6241. if (!(self && self.peerconnection)) return;
  6242. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  6243. ":\t", window.performance.now());
  6244. self.updateModifySourcesQueue();
  6245. switch (self.peerconnection.iceConnectionState) {
  6246. case 'connected':
  6247. // Informs interested parties that the connection has been restored.
  6248. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  6249. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  6250. self.isreconnect = false;
  6251. break;
  6252. case 'disconnected':
  6253. self.isreconnect = true;
  6254. // Informs interested parties that the connection has been interrupted.
  6255. if (self.wasstable)
  6256. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  6257. break;
  6258. case 'failed':
  6259. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6260. break;
  6261. }
  6262. onIceConnectionStateChange(self.sid, self);
  6263. };
  6264. this.peerconnection.onnegotiationneeded = function (event) {
  6265. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  6266. };
  6267. this.relayedStreams.forEach(function(stream) {
  6268. self.peerconnection.addStream(stream);
  6269. });
  6270. };
  6271. function onIceConnectionStateChange(sid, session) {
  6272. switch (session.peerconnection.iceConnectionState) {
  6273. case 'checking':
  6274. session.timeChecking = (new Date()).getTime();
  6275. session.firstconnect = true;
  6276. break;
  6277. case 'completed': // on caller side
  6278. case 'connected':
  6279. if (session.firstconnect) {
  6280. session.firstconnect = false;
  6281. var metadata = {};
  6282. metadata.setupTime
  6283. = (new Date()).getTime() - session.timeChecking;
  6284. session.peerconnection.getStats(function (res) {
  6285. if(res && res.result) {
  6286. res.result().forEach(function (report) {
  6287. if (report.type == 'googCandidatePair' &&
  6288. report.stat('googActiveConnection') == 'true') {
  6289. metadata.localCandidateType
  6290. = report.stat('googLocalCandidateType');
  6291. metadata.remoteCandidateType
  6292. = report.stat('googRemoteCandidateType');
  6293. // log pair as well so we can get nice pie
  6294. // charts
  6295. metadata.candidatePair
  6296. = report.stat('googLocalCandidateType') +
  6297. ';' +
  6298. report.stat('googRemoteCandidateType');
  6299. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  6300. {
  6301. metadata.ipv6 = true;
  6302. }
  6303. }
  6304. });
  6305. }
  6306. });
  6307. }
  6308. break;
  6309. }
  6310. }
  6311. JingleSessionPC.prototype.accept = function () {
  6312. this.state = 'active';
  6313. var pranswer = this.peerconnection.localDescription;
  6314. if (!pranswer || pranswer.type != 'pranswer') {
  6315. return;
  6316. }
  6317. logger.log('going from pranswer to answer');
  6318. if (this.usetrickle) {
  6319. // remove candidates already sent from session-accept
  6320. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  6321. for (var i = 0; i < lines.length; i++) {
  6322. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  6323. }
  6324. }
  6325. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  6326. // FIXME: change any inactive to sendrecv or whatever they were originally
  6327. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  6328. }
  6329. var prsdp = new SDP(pranswer.sdp);
  6330. if (self.webrtcIceTcpDisable) {
  6331. prsdp.removeTcpCandidates = true;
  6332. }
  6333. if (self.webrtcIceUdpDisable) {
  6334. prsdp.removeUdpCandidates = true;
  6335. }
  6336. var accept = $iq({to: this.peerjid,
  6337. type: 'set'})
  6338. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6339. action: 'session-accept',
  6340. initiator: this.initiator,
  6341. responder: this.responder,
  6342. sid: this.sid });
  6343. // FIXME why do we generate session-accept in 3 different places ?
  6344. prsdp.toJingle(
  6345. accept,
  6346. this.initiator == this.me ? 'initiator' : 'responder');
  6347. var sdp = this.peerconnection.localDescription.sdp;
  6348. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  6349. // FIXME: change any inactive to sendrecv or whatever they were originally
  6350. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  6351. }
  6352. var self = this;
  6353. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  6354. function () {
  6355. //logger.log('setLocalDescription success');
  6356. self.setLocalDescription();
  6357. SSRCReplacement.processSessionInit(accept);
  6358. self.connection.sendIQ(accept,
  6359. function () {
  6360. var ack = {};
  6361. ack.source = 'answer';
  6362. $(document).trigger('ack.jingle', [self.sid, ack]);
  6363. },
  6364. function (stanza) {
  6365. var error = ($(stanza).find('error').length) ? {
  6366. code: $(stanza).find('error').attr('code'),
  6367. reason: $(stanza).find('error :first')[0].tagName
  6368. }:{};
  6369. error.source = 'answer';
  6370. JingleSessionPC.onJingleError(self.sid, error);
  6371. },
  6372. 10000);
  6373. },
  6374. function (e) {
  6375. logger.error('setLocalDescription failed', e);
  6376. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6377. }
  6378. );
  6379. };
  6380. JingleSessionPC.prototype.terminate = function (reason) {
  6381. this.state = 'ended';
  6382. this.reason = reason;
  6383. this.peerconnection.close();
  6384. if (this.statsinterval !== null) {
  6385. window.clearInterval(this.statsinterval);
  6386. this.statsinterval = null;
  6387. }
  6388. };
  6389. JingleSessionPC.prototype.active = function () {
  6390. return this.state == 'active';
  6391. };
  6392. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  6393. var self = this;
  6394. if (candidate && !this.lasticecandidate) {
  6395. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  6396. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  6397. if (!(ice && jcand)) {
  6398. logger.error('failed to get ice && jcand');
  6399. return;
  6400. }
  6401. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6402. if (jcand.type === 'srflx') {
  6403. this.hadstuncandidate = true;
  6404. } else if (jcand.type === 'relay') {
  6405. this.hadturncandidate = true;
  6406. }
  6407. if (this.usetrickle) {
  6408. if (this.usedrip) {
  6409. if (this.drip_container.length === 0) {
  6410. // start 20ms callout
  6411. window.setTimeout(function () {
  6412. if (self.drip_container.length === 0) return;
  6413. self.sendIceCandidates(self.drip_container);
  6414. self.drip_container = [];
  6415. }, 20);
  6416. }
  6417. this.drip_container.push(candidate);
  6418. return;
  6419. } else {
  6420. self.sendIceCandidate([candidate]);
  6421. }
  6422. }
  6423. } else {
  6424. //logger.log('sendIceCandidate: last candidate.');
  6425. if (!this.usetrickle) {
  6426. //logger.log('should send full offer now...');
  6427. //FIXME why do we generate session-accept in 3 different places ?
  6428. var init = $iq({to: this.peerjid,
  6429. type: 'set'})
  6430. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6431. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  6432. initiator: this.initiator,
  6433. sid: this.sid});
  6434. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  6435. if (self.webrtcIceTcpDisable) {
  6436. this.localSDP.removeTcpCandidates = true;
  6437. }
  6438. if (self.webrtcIceUdpDisable) {
  6439. this.localSDP.removeUdpCandidates = true;
  6440. }
  6441. var sendJingle = function (ssrc) {
  6442. if(!ssrc)
  6443. ssrc = {};
  6444. self.localSDP.toJingle(
  6445. init,
  6446. self.initiator == self.me ? 'initiator' : 'responder',
  6447. ssrc);
  6448. SSRCReplacement.processSessionInit(init);
  6449. self.connection.sendIQ(init,
  6450. function () {
  6451. //logger.log('session initiate ack');
  6452. var ack = {};
  6453. ack.source = 'offer';
  6454. $(document).trigger('ack.jingle', [self.sid, ack]);
  6455. },
  6456. function (stanza) {
  6457. self.state = 'error';
  6458. self.peerconnection.close();
  6459. var error = ($(stanza).find('error').length) ? {
  6460. code: $(stanza).find('error').attr('code'),
  6461. reason: $(stanza).find('error :first')[0].tagName,
  6462. }:{};
  6463. error.source = 'offer';
  6464. JingleSessionPC.onJingleError(self.sid, error);
  6465. },
  6466. 10000);
  6467. };
  6468. sendJingle();
  6469. }
  6470. this.lasticecandidate = true;
  6471. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  6472. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  6473. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  6474. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  6475. }
  6476. }
  6477. };
  6478. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  6479. logger.log('sendIceCandidates', candidates);
  6480. var cand = $iq({to: this.peerjid, type: 'set'})
  6481. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6482. action: 'transport-info',
  6483. initiator: this.initiator,
  6484. sid: this.sid});
  6485. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  6486. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  6487. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  6488. if (cands.length > 0) {
  6489. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  6490. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6491. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  6492. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  6493. }).c('transport', ice);
  6494. for (var i = 0; i < cands.length; i++) {
  6495. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  6496. }
  6497. // add fingerprint
  6498. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  6499. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  6500. tmp.required = true;
  6501. cand.c(
  6502. 'fingerprint',
  6503. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  6504. .t(tmp.fingerprint);
  6505. delete tmp.fingerprint;
  6506. cand.attrs(tmp);
  6507. cand.up();
  6508. }
  6509. cand.up(); // transport
  6510. cand.up(); // content
  6511. }
  6512. }
  6513. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  6514. //logger.log('was this the last candidate', this.lasticecandidate);
  6515. this.connection.sendIQ(cand,
  6516. function () {
  6517. var ack = {};
  6518. ack.source = 'transportinfo';
  6519. $(document).trigger('ack.jingle', [this.sid, ack]);
  6520. },
  6521. function (stanza) {
  6522. var error = ($(stanza).find('error').length) ? {
  6523. code: $(stanza).find('error').attr('code'),
  6524. reason: $(stanza).find('error :first')[0].tagName,
  6525. }:{};
  6526. error.source = 'transportinfo';
  6527. JingleSessionPC.onJingleError(this.sid, error);
  6528. },
  6529. 10000);
  6530. };
  6531. JingleSessionPC.prototype.sendOffer = function () {
  6532. //logger.log('sendOffer...');
  6533. var self = this;
  6534. this.peerconnection.createOffer(function (sdp) {
  6535. self.createdOffer(sdp);
  6536. },
  6537. function (e) {
  6538. logger.error('createOffer failed', e);
  6539. },
  6540. this.media_constraints
  6541. );
  6542. };
  6543. // FIXME createdOffer is never used in jitsi-meet
  6544. JingleSessionPC.prototype.createdOffer = function (sdp) {
  6545. //logger.log('createdOffer', sdp);
  6546. var self = this;
  6547. this.localSDP = new SDP(sdp.sdp);
  6548. //this.localSDP.mangle();
  6549. var sendJingle = function () {
  6550. var init = $iq({to: this.peerjid,
  6551. type: 'set'})
  6552. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6553. action: 'session-initiate',
  6554. initiator: this.initiator,
  6555. sid: this.sid});
  6556. self.localSDP.toJingle(
  6557. init,
  6558. this.initiator == this.me ? 'initiator' : 'responder');
  6559. SSRCReplacement.processSessionInit(init);
  6560. self.connection.sendIQ(init,
  6561. function () {
  6562. var ack = {};
  6563. ack.source = 'offer';
  6564. $(document).trigger('ack.jingle', [self.sid, ack]);
  6565. },
  6566. function (stanza) {
  6567. self.state = 'error';
  6568. self.peerconnection.close();
  6569. var error = ($(stanza).find('error').length) ? {
  6570. code: $(stanza).find('error').attr('code'),
  6571. reason: $(stanza).find('error :first')[0].tagName,
  6572. }:{};
  6573. error.source = 'offer';
  6574. JingleSessionPC.onJingleError(self.sid, error);
  6575. },
  6576. 10000);
  6577. }
  6578. sdp.sdp = this.localSDP.raw;
  6579. this.peerconnection.setLocalDescription(sdp,
  6580. function () {
  6581. if(self.usetrickle)
  6582. {
  6583. sendJingle();
  6584. }
  6585. self.setLocalDescription();
  6586. //logger.log('setLocalDescription success');
  6587. },
  6588. function (e) {
  6589. logger.error('setLocalDescription failed', e);
  6590. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6591. }
  6592. );
  6593. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6594. for (var i = 0; i < cands.length; i++) {
  6595. var cand = SDPUtil.parse_icecandidate(cands[i]);
  6596. if (cand.type == 'srflx') {
  6597. this.hadstuncandidate = true;
  6598. } else if (cand.type == 'relay') {
  6599. this.hadturncandidate = true;
  6600. }
  6601. }
  6602. };
  6603. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  6604. var self = this;
  6605. $(contents).each(function (idx, content) {
  6606. var name = $(content).attr('name');
  6607. var mediaType = this.getAttribute('name');
  6608. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  6609. ssrcs.each(function () {
  6610. var ssrc = this.getAttribute('ssrc');
  6611. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  6612. function () {
  6613. var owner = this.getAttribute('owner');
  6614. self.ssrcOwners[ssrc] = owner;
  6615. }
  6616. );
  6617. });
  6618. });
  6619. };
  6620. /**
  6621. * Returns the SSRC of local audio stream.
  6622. * @param mediaType 'audio' or 'video' media type
  6623. * @returns {*} the SSRC number of local audio or video stream.
  6624. */
  6625. JingleSessionPC.prototype.getLocalSSRC = function (mediaType) {
  6626. return this.localStreamsSSRC[mediaType];
  6627. };
  6628. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  6629. return this.ssrcOwners[ssrc];
  6630. };
  6631. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  6632. //logger.log('setting remote description... ', desctype);
  6633. this.remoteSDP = new SDP('');
  6634. if (self.webrtcIceTcpDisable) {
  6635. this.remoteSDP.removeTcpCandidates = true;
  6636. }
  6637. if (self.webrtcIceUdpDisable) {
  6638. this.remoteSDP.removeUdpCandidates = true;
  6639. }
  6640. this.remoteSDP.fromJingle(elem);
  6641. this.readSsrcInfo($(elem).find(">content"));
  6642. if (this.peerconnection.remoteDescription) {
  6643. logger.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  6644. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  6645. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  6646. for (var i = 0; i < pranswer.media.length; i++) {
  6647. // make sure we have ice ufrag and pwd
  6648. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  6649. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  6650. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  6651. } else {
  6652. logger.warn('no ice ufrag?');
  6653. }
  6654. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  6655. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  6656. } else {
  6657. logger.warn('no ice pwd?');
  6658. }
  6659. }
  6660. // copy over candidates
  6661. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  6662. for (var j = 0; j < lines.length; j++) {
  6663. this.remoteSDP.media[i] += lines[j] + '\r\n';
  6664. }
  6665. }
  6666. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6667. }
  6668. }
  6669. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  6670. this.peerconnection.setRemoteDescription(remotedesc,
  6671. function () {
  6672. //logger.log('setRemoteDescription success');
  6673. },
  6674. function (e) {
  6675. logger.error('setRemoteDescription error', e);
  6676. JingleSessionPC.onJingleFatalError(self, e);
  6677. }
  6678. );
  6679. };
  6680. /**
  6681. * Adds remote ICE candidates to this Jingle session.
  6682. * @param elem An array of Jingle "content" elements?
  6683. */
  6684. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  6685. var self = this;
  6686. if (this.peerconnection.signalingState == 'closed') {
  6687. return;
  6688. }
  6689. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  6690. logger.log('trickle ice candidate arriving before session accept...');
  6691. // create a PRANSWER for setRemoteDescription
  6692. if (!this.remoteSDP) {
  6693. var cobbled = 'v=0\r\n' +
  6694. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  6695. 's=-\r\n' +
  6696. 't=0 0\r\n';
  6697. // first, take some things from the local description
  6698. for (var i = 0; i < this.localSDP.media.length; i++) {
  6699. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  6700. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  6701. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  6702. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  6703. }
  6704. cobbled += 'a=inactive\r\n';
  6705. }
  6706. this.remoteSDP = new SDP(cobbled);
  6707. }
  6708. // then add things like ice and dtls from remote candidate
  6709. elem.each(function () {
  6710. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  6711. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6712. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6713. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  6714. var tmp = $(this).find('transport');
  6715. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  6716. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  6717. tmp = $(this).find('transport>fingerprint');
  6718. if (tmp.length) {
  6719. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  6720. } else {
  6721. logger.log('no dtls fingerprint (webrtc issue #1718?)');
  6722. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  6723. }
  6724. break;
  6725. }
  6726. }
  6727. }
  6728. });
  6729. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6730. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  6731. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  6732. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  6733. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  6734. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  6735. }).length == this.remoteSDP.media.length;
  6736. if (iscomplete) {
  6737. logger.log('setting pranswer');
  6738. try {
  6739. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  6740. function() {
  6741. },
  6742. function(e) {
  6743. logger.log('setRemoteDescription pranswer failed', e.toString());
  6744. });
  6745. } catch (e) {
  6746. logger.error('setting pranswer failed', e);
  6747. }
  6748. } else {
  6749. //logger.log('not yet setting pranswer');
  6750. }
  6751. }
  6752. // operate on each content element
  6753. elem.each(function () {
  6754. // would love to deactivate this, but firefox still requires it
  6755. var idx = -1;
  6756. var i;
  6757. for (i = 0; i < self.remoteSDP.media.length; i++) {
  6758. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6759. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6760. idx = i;
  6761. break;
  6762. }
  6763. }
  6764. if (idx == -1) { // fall back to localdescription
  6765. for (i = 0; i < self.localSDP.media.length; i++) {
  6766. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6767. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6768. idx = i;
  6769. break;
  6770. }
  6771. }
  6772. }
  6773. var name = $(this).attr('name');
  6774. // TODO: check ice-pwd and ice-ufrag?
  6775. $(this).find('transport>candidate').each(function () {
  6776. var line, candidate;
  6777. var protocol = this.getAttribute('protocol');
  6778. protocol =
  6779. (typeof protocol === 'string') ? protocol.toLowerCase() : '';
  6780. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  6781. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  6782. return;
  6783. }
  6784. line = SDPUtil.candidateFromJingle(this);
  6785. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  6786. sdpMid: name,
  6787. candidate: line});
  6788. try {
  6789. self.peerconnection.addIceCandidate(candidate);
  6790. } catch (e) {
  6791. logger.error('addIceCandidate failed', e.toString(), line);
  6792. }
  6793. });
  6794. });
  6795. };
  6796. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  6797. //logger.log('createAnswer', provisional);
  6798. var self = this;
  6799. this.peerconnection.createAnswer(
  6800. function (sdp) {
  6801. self.createdAnswer(sdp, provisional);
  6802. },
  6803. function (e) {
  6804. logger.error('createAnswer failed', e);
  6805. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6806. },
  6807. this.media_constraints
  6808. );
  6809. };
  6810. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  6811. //logger.log('createAnswer callback');
  6812. var self = this;
  6813. this.localSDP = new SDP(sdp.sdp);
  6814. //this.localSDP.mangle();
  6815. this.usepranswer = provisional === true;
  6816. if (this.usetrickle) {
  6817. if (this.usepranswer) {
  6818. sdp.type = 'pranswer';
  6819. for (var i = 0; i < this.localSDP.media.length; i++) {
  6820. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  6821. }
  6822. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  6823. }
  6824. }
  6825. var self = this;
  6826. var sendJingle = function (ssrcs) {
  6827. // FIXME why do we generate session-accept in 3 different places ?
  6828. var accept = $iq({to: self.peerjid,
  6829. type: 'set'})
  6830. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6831. action: 'session-accept',
  6832. initiator: self.initiator,
  6833. responder: self.responder,
  6834. sid: self.sid });
  6835. if (self.webrtcIceTcpDisable) {
  6836. self.localSDP.removeTcpCandidates = true;
  6837. }
  6838. if (self.webrtcIceUdpDisable) {
  6839. self.localSDP.removeUdpCandidates = true;
  6840. }
  6841. self.localSDP.toJingle(
  6842. accept,
  6843. self.initiator == self.me ? 'initiator' : 'responder',
  6844. ssrcs);
  6845. SSRCReplacement.processSessionInit(accept);
  6846. self.connection.sendIQ(accept,
  6847. function () {
  6848. var ack = {};
  6849. ack.source = 'answer';
  6850. $(document).trigger('ack.jingle', [self.sid, ack]);
  6851. },
  6852. function (stanza) {
  6853. var error = ($(stanza).find('error').length) ? {
  6854. code: $(stanza).find('error').attr('code'),
  6855. reason: $(stanza).find('error :first')[0].tagName,
  6856. }:{};
  6857. error.source = 'answer';
  6858. JingleSessionPC.onJingleError(self.sid, error);
  6859. },
  6860. 10000);
  6861. }
  6862. sdp.sdp = this.localSDP.raw;
  6863. this.peerconnection.setLocalDescription(sdp,
  6864. function () {
  6865. //logger.log('setLocalDescription success');
  6866. if (self.usetrickle && !self.usepranswer) {
  6867. sendJingle();
  6868. }
  6869. self.setLocalDescription();
  6870. },
  6871. function (e) {
  6872. logger.error('setLocalDescription failed', e);
  6873. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6874. }
  6875. );
  6876. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6877. for (var j = 0; j < cands.length; j++) {
  6878. var cand = SDPUtil.parse_icecandidate(cands[j]);
  6879. if (cand.type == 'srflx') {
  6880. this.hadstuncandidate = true;
  6881. } else if (cand.type == 'relay') {
  6882. this.hadturncandidate = true;
  6883. }
  6884. }
  6885. };
  6886. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  6887. var self = this,
  6888. term = $iq({to: this.peerjid,
  6889. type: 'set'})
  6890. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6891. action: 'session-terminate',
  6892. initiator: this.initiator,
  6893. sid: this.sid})
  6894. .c('reason')
  6895. .c(reason || 'success');
  6896. if (text) {
  6897. term.up().c('text').t(text);
  6898. }
  6899. this.connection.sendIQ(term,
  6900. function () {
  6901. self.peerconnection.close();
  6902. self.peerconnection = null;
  6903. self.terminate();
  6904. var ack = {};
  6905. ack.source = 'terminate';
  6906. $(document).trigger('ack.jingle', [self.sid, ack]);
  6907. },
  6908. function (stanza) {
  6909. var error = ($(stanza).find('error').length) ? {
  6910. code: $(stanza).find('error').attr('code'),
  6911. reason: $(stanza).find('error :first')[0].tagName,
  6912. }:{};
  6913. $(document).trigger('ack.jingle', [self.sid, error]);
  6914. },
  6915. 10000);
  6916. if (this.statsinterval !== null) {
  6917. window.clearInterval(this.statsinterval);
  6918. this.statsinterval = null;
  6919. }
  6920. };
  6921. /**
  6922. * Handles a Jingle source-add message for this Jingle session.
  6923. * @param elem An array of Jingle "content" elements.
  6924. */
  6925. JingleSessionPC.prototype.addSource = function (elem) {
  6926. var self = this;
  6927. // FIXME: dirty waiting
  6928. if (!this.peerconnection.localDescription)
  6929. {
  6930. logger.warn("addSource - localDescription not ready yet")
  6931. setTimeout(function()
  6932. {
  6933. self.addSource(elem);
  6934. },
  6935. 200
  6936. );
  6937. return;
  6938. }
  6939. logger.log('addssrc', new Date().getTime());
  6940. logger.log('ice', this.peerconnection.iceConnectionState);
  6941. this.readSsrcInfo(elem);
  6942. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6943. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  6944. $(elem).each(function (idx, content) {
  6945. var name = $(content).attr('name');
  6946. var lines = '';
  6947. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6948. var semantics = this.getAttribute('semantics');
  6949. var ssrcs = $(this).find('>source').map(function () {
  6950. return this.getAttribute('ssrc');
  6951. }).get();
  6952. if (ssrcs.length) {
  6953. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6954. }
  6955. });
  6956. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  6957. tmp.each(function () {
  6958. var ssrc = $(this).attr('ssrc');
  6959. if(mySdp.containsSSRC(ssrc)){
  6960. /**
  6961. * This happens when multiple participants change their streams at the same time and
  6962. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  6963. * addssrc are scheduled for update IQ. See
  6964. */
  6965. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  6966. return;
  6967. }
  6968. if (sdp.containsSSRC(ssrc)) {
  6969. logger.warn("Source-add request for existing SSRC: " + ssrc);
  6970. return;
  6971. }
  6972. $(this).find('>parameter').each(function () {
  6973. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  6974. if ($(this).attr('value') && $(this).attr('value').length)
  6975. lines += ':' + $(this).attr('value');
  6976. lines += '\r\n';
  6977. });
  6978. });
  6979. sdp.media.forEach(function(media, idx) {
  6980. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  6981. return;
  6982. sdp.media[idx] += lines;
  6983. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  6984. self.addssrc[idx] += lines;
  6985. });
  6986. sdp.raw = sdp.session + sdp.media.join('');
  6987. });
  6988. this.modifySourcesQueue.push(function() {
  6989. // When a source is added and if this is FF, a new channel is allocated
  6990. // for receiving the added source. We need to diffuse the SSRC of this
  6991. // new recvonly channel to the rest of the peers.
  6992. logger.log('modify sources done');
  6993. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6994. logger.log("SDPs", mySdp, newSdp);
  6995. self.notifyMySSRCUpdate(mySdp, newSdp);
  6996. });
  6997. };
  6998. /**
  6999. * Handles a Jingle source-remove message for this Jingle session.
  7000. * @param elem An array of Jingle "content" elements.
  7001. */
  7002. JingleSessionPC.prototype.removeSource = function (elem) {
  7003. var self = this;
  7004. // FIXME: dirty waiting
  7005. if (!this.peerconnection.localDescription) {
  7006. logger.warn("removeSource - localDescription not ready yet");
  7007. setTimeout(function() {
  7008. self.removeSource(elem);
  7009. },
  7010. 200
  7011. );
  7012. return;
  7013. }
  7014. logger.log('removessrc', new Date().getTime());
  7015. logger.log('ice', this.peerconnection.iceConnectionState);
  7016. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  7017. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  7018. $(elem).each(function (idx, content) {
  7019. var name = $(content).attr('name');
  7020. var lines = '';
  7021. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  7022. var semantics = this.getAttribute('semantics');
  7023. var ssrcs = $(this).find('>source').map(function () {
  7024. return this.getAttribute('ssrc');
  7025. }).get();
  7026. if (ssrcs.length) {
  7027. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  7028. }
  7029. });
  7030. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  7031. tmp.each(function () {
  7032. var ssrc = $(this).attr('ssrc');
  7033. // This should never happen, but can be useful for bug detection
  7034. if(mySdp.containsSSRC(ssrc)){
  7035. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  7036. return;
  7037. }
  7038. $(this).find('>parameter').each(function () {
  7039. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  7040. if ($(this).attr('value') && $(this).attr('value').length)
  7041. lines += ':' + $(this).attr('value');
  7042. lines += '\r\n';
  7043. });
  7044. });
  7045. sdp.media.forEach(function(media, idx) {
  7046. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  7047. return;
  7048. sdp.media[idx] += lines;
  7049. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  7050. self.removessrc[idx] += lines;
  7051. });
  7052. sdp.raw = sdp.session + sdp.media.join('');
  7053. });
  7054. this.modifySourcesQueue.push(function() {
  7055. // When a source is removed and if this is FF, the recvonly channel that
  7056. // receives the remote stream is deactivated . We need to diffuse the
  7057. // recvonly SSRC removal to the rest of the peers.
  7058. logger.log('modify sources done');
  7059. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7060. logger.log("SDPs", mySdp, newSdp);
  7061. self.notifyMySSRCUpdate(mySdp, newSdp);
  7062. });
  7063. };
  7064. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  7065. var self = this;
  7066. if (this.peerconnection.signalingState == 'closed') return;
  7067. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  7068. || this.switchstreams || this.addingStreams)){
  7069. // There is nothing to do since scheduled job might have been executed by another succeeding call
  7070. this.setLocalDescription();
  7071. if(successCallback){
  7072. successCallback();
  7073. }
  7074. queueCallback();
  7075. return;
  7076. }
  7077. // Reset switch streams flags
  7078. this.switchstreams = false;
  7079. this.addingStreams = false;
  7080. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  7081. // add sources
  7082. this.addssrc.forEach(function(lines, idx) {
  7083. sdp.media[idx] += lines;
  7084. });
  7085. this.addssrc = [];
  7086. // remove sources
  7087. this.removessrc.forEach(function(lines, idx) {
  7088. lines = lines.split('\r\n');
  7089. lines.pop(); // remove empty last element;
  7090. lines.forEach(function(line) {
  7091. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  7092. });
  7093. });
  7094. this.removessrc = [];
  7095. sdp.raw = sdp.session + sdp.media.join('');
  7096. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  7097. function() {
  7098. if(self.signalingState == 'closed') {
  7099. logger.error("createAnswer attempt on closed state");
  7100. queueCallback("createAnswer attempt on closed state");
  7101. return;
  7102. }
  7103. self.peerconnection.createAnswer(
  7104. function(modifiedAnswer) {
  7105. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  7106. if (self.pendingop !== null) {
  7107. var sdp = new SDP(modifiedAnswer.sdp);
  7108. if (sdp.media.length > 1) {
  7109. switch(self.pendingop) {
  7110. case 'mute':
  7111. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  7112. break;
  7113. case 'unmute':
  7114. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  7115. break;
  7116. }
  7117. sdp.raw = sdp.session + sdp.media.join('');
  7118. modifiedAnswer.sdp = sdp.raw;
  7119. }
  7120. self.pendingop = null;
  7121. }
  7122. // FIXME: pushing down an answer while ice connection state
  7123. // is still checking is bad...
  7124. //logger.log(self.peerconnection.iceConnectionState);
  7125. // trying to work around another chrome bug
  7126. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  7127. self.peerconnection.setLocalDescription(modifiedAnswer,
  7128. function() {
  7129. //logger.log('modified setLocalDescription ok');
  7130. self.setLocalDescription();
  7131. if(successCallback){
  7132. successCallback();
  7133. }
  7134. queueCallback();
  7135. },
  7136. function(error) {
  7137. logger.error('modified setLocalDescription failed', error);
  7138. queueCallback(error);
  7139. }
  7140. );
  7141. },
  7142. function(error) {
  7143. logger.error('modified answer failed', error);
  7144. queueCallback(error);
  7145. }
  7146. );
  7147. },
  7148. function(error) {
  7149. logger.error('modify failed', error);
  7150. queueCallback(error);
  7151. }
  7152. );
  7153. };
  7154. /**
  7155. * Switches video streams.
  7156. * @param newStream new stream that will be used as video of this session.
  7157. * @param oldStream old video stream of this session.
  7158. * @param successCallback callback executed after successful stream switch.
  7159. * @param isAudio whether the streams are audio (if true) or video (if false).
  7160. */
  7161. JingleSessionPC.prototype.switchStreams =
  7162. function (newStream, oldStream, successCallback, isAudio) {
  7163. var self = this;
  7164. var sender, newTrack;
  7165. var senderKind = isAudio ? 'audio' : 'video';
  7166. // Remember SDP to figure out added/removed SSRCs
  7167. var oldSdp = null;
  7168. if (self.peerconnection) {
  7169. if (self.peerconnection.localDescription) {
  7170. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  7171. }
  7172. if (RTCBrowserType.getBrowserType() ===
  7173. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  7174. // On Firefox we don't replace MediaStreams as this messes up the
  7175. // m-lines (which can't be removed in Plan Unified) and brings a lot
  7176. // of complications. Instead, we use the RTPSender and replace just
  7177. // the track.
  7178. // Find the right sender (for audio or video)
  7179. self.peerconnection.peerconnection.getSenders().some(function (s) {
  7180. if (s.track && s.track.kind === senderKind) {
  7181. sender = s;
  7182. return true;
  7183. }
  7184. });
  7185. if (sender) {
  7186. // We assume that our streams have a single track, either audio
  7187. // or video.
  7188. newTrack = isAudio ? newStream.getAudioTracks()[0] :
  7189. newStream.getVideoTracks()[0];
  7190. sender.replaceTrack(newTrack)
  7191. .then(function() {
  7192. console.log("Replaced a track, isAudio=" + isAudio);
  7193. })
  7194. .catch(function(err) {
  7195. console.log("Failed to replace a track: " + err);
  7196. });
  7197. } else {
  7198. console.log("Cannot switch tracks: no RTPSender.");
  7199. }
  7200. } else {
  7201. self.peerconnection.removeStream(oldStream, true);
  7202. if (newStream) {
  7203. self.peerconnection.addStream(newStream);
  7204. }
  7205. }
  7206. }
  7207. // Conference is not active
  7208. if (!oldSdp) {
  7209. successCallback();
  7210. return;
  7211. }
  7212. self.switchstreams = true;
  7213. self.modifySourcesQueue.push(function() {
  7214. logger.log('modify sources done');
  7215. successCallback();
  7216. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7217. logger.log("SDPs", oldSdp, newSdp);
  7218. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7219. });
  7220. };
  7221. /**
  7222. * Adds streams.
  7223. * @param stream new stream that will be added.
  7224. * @param success_callback callback executed after successful stream addition.
  7225. */
  7226. JingleSessionPC.prototype.addStream = function (stream, callback) {
  7227. var self = this;
  7228. // Remember SDP to figure out added/removed SSRCs
  7229. var oldSdp = null;
  7230. if(this.peerconnection) {
  7231. if(this.peerconnection.localDescription) {
  7232. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  7233. }
  7234. if(stream)
  7235. this.peerconnection.addStream(stream);
  7236. }
  7237. // Conference is not active
  7238. if(!oldSdp || !this.peerconnection) {
  7239. callback();
  7240. return;
  7241. }
  7242. this.addingStreams = true;
  7243. this.modifySourcesQueue.push(function() {
  7244. logger.log('modify sources done');
  7245. callback();
  7246. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7247. logger.log("SDPs", oldSdp, newSdp);
  7248. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7249. });
  7250. }
  7251. /**
  7252. * Remove streams.
  7253. * @param stream stream that will be removed.
  7254. * @param success_callback callback executed after successful stream addition.
  7255. */
  7256. JingleSessionPC.prototype.removeStream = function (stream, callback) {
  7257. var self = this;
  7258. // Remember SDP to figure out added/removed SSRCs
  7259. var oldSdp = null;
  7260. if(this.peerconnection) {
  7261. if(this.peerconnection.localDescription) {
  7262. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  7263. }
  7264. if(stream)
  7265. this.peerconnection.removeStream(stream);
  7266. }
  7267. // Conference is not active
  7268. if(!oldSdp || !this.peerconnection) {
  7269. callback();
  7270. return;
  7271. }
  7272. this.addingStreams = true;
  7273. this.modifySourcesQueue.push(function() {
  7274. logger.log('modify sources done');
  7275. callback();
  7276. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7277. logger.log("SDPs", oldSdp, newSdp);
  7278. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7279. });
  7280. }
  7281. /**
  7282. * Figures out added/removed ssrcs and send update IQs.
  7283. * @param old_sdp SDP object for old description.
  7284. * @param new_sdp SDP object for new description.
  7285. */
  7286. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  7287. if (!(this.peerconnection.signalingState == 'stable' &&
  7288. this.peerconnection.iceConnectionState == 'connected')){
  7289. logger.log("Too early to send updates");
  7290. return;
  7291. }
  7292. // send source-remove IQ.
  7293. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  7294. var remove = $iq({to: this.peerjid, type: 'set'})
  7295. .c('jingle', {
  7296. xmlns: 'urn:xmpp:jingle:1',
  7297. action: 'source-remove',
  7298. initiator: this.initiator,
  7299. sid: this.sid
  7300. }
  7301. );
  7302. var removed = sdpDiffer.toJingle(remove);
  7303. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  7304. // it in the current form
  7305. if (removed)
  7306. remove = SSRCReplacement.processSourceRemove(remove);
  7307. if (removed && remove) {
  7308. logger.info("Sending source-remove", remove);
  7309. this.connection.sendIQ(remove,
  7310. function (res) {
  7311. logger.info('got remove result', res);
  7312. },
  7313. function (err) {
  7314. logger.error('got remove error', err);
  7315. }
  7316. );
  7317. } else {
  7318. logger.log('removal not necessary');
  7319. }
  7320. // send source-add IQ.
  7321. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  7322. var add = $iq({to: this.peerjid, type: 'set'})
  7323. .c('jingle', {
  7324. xmlns: 'urn:xmpp:jingle:1',
  7325. action: 'source-add',
  7326. initiator: this.initiator,
  7327. sid: this.sid
  7328. }
  7329. );
  7330. var added = sdpDiffer.toJingle(add);
  7331. // Let 'source-add' IQ through the hack and see if we're allowed to send
  7332. // it in the current form
  7333. if (added)
  7334. add = SSRCReplacement.processSourceAdd(add);
  7335. if (added && add) {
  7336. logger.info("Sending source-add", add);
  7337. this.connection.sendIQ(add,
  7338. function (res) {
  7339. logger.info('got add result', res);
  7340. },
  7341. function (err) {
  7342. logger.error('got add error', err);
  7343. }
  7344. );
  7345. } else {
  7346. logger.log('addition not necessary');
  7347. }
  7348. };
  7349. /**
  7350. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  7351. *
  7352. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  7353. * tracks; otherwise, <tt>false</tt>
  7354. * @param callback a function to be invoked with <tt>mute</tt> after all video
  7355. * tracks have been enabled/disabled. The function may, optionally, return
  7356. * another function which is to be invoked after the whole mute/unmute operation
  7357. * has completed successfully.
  7358. * @param options an object which specifies optional arguments such as the
  7359. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  7360. * specifies whether the method was initiated in response to a user command (in
  7361. * contrast to an automatic decision made by the application logic)
  7362. */
  7363. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  7364. var byUser;
  7365. if (options) {
  7366. byUser = options.byUser;
  7367. if (typeof byUser === 'undefined') {
  7368. byUser = true;
  7369. }
  7370. } else {
  7371. byUser = true;
  7372. }
  7373. // The user's command to mute the (local) video takes precedence over any
  7374. // automatic decision made by the application logic.
  7375. if (byUser) {
  7376. this.videoMuteByUser = mute;
  7377. } else if (this.videoMuteByUser) {
  7378. return;
  7379. }
  7380. this.hardMuteVideo(mute);
  7381. var self = this;
  7382. var oldSdp = null;
  7383. if(self.peerconnection) {
  7384. if(self.peerconnection.localDescription) {
  7385. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  7386. }
  7387. }
  7388. this.modifySourcesQueue.push(function() {
  7389. logger.log('modify sources done');
  7390. callback(mute);
  7391. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7392. logger.log("SDPs", oldSdp, newSdp);
  7393. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7394. });
  7395. };
  7396. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  7397. this.pendingop = muted ? 'mute' : 'unmute';
  7398. };
  7399. JingleSessionPC.prototype.sendMute = function (muted, content) {
  7400. var info = $iq({to: this.peerjid,
  7401. type: 'set'})
  7402. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7403. action: 'session-info',
  7404. initiator: this.initiator,
  7405. sid: this.sid });
  7406. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  7407. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  7408. if (content) {
  7409. info.attrs({'name': content});
  7410. }
  7411. this.connection.send(info);
  7412. };
  7413. JingleSessionPC.prototype.sendRinging = function () {
  7414. var info = $iq({to: this.peerjid,
  7415. type: 'set'})
  7416. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7417. action: 'session-info',
  7418. initiator: this.initiator,
  7419. sid: this.sid });
  7420. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  7421. this.connection.send(info);
  7422. };
  7423. JingleSessionPC.prototype.getStats = function (interval) {
  7424. var self = this;
  7425. var recv = {audio: 0, video: 0};
  7426. var lost = {audio: 0, video: 0};
  7427. var lastrecv = {audio: 0, video: 0};
  7428. var lastlost = {audio: 0, video: 0};
  7429. var loss = {audio: 0, video: 0};
  7430. var delta = {audio: 0, video: 0};
  7431. this.statsinterval = window.setInterval(function () {
  7432. if (self && self.peerconnection && self.peerconnection.getStats) {
  7433. self.peerconnection.getStats(function (stats) {
  7434. var results = stats.result();
  7435. // TODO: there are so much statistics you can get from this..
  7436. for (var i = 0; i < results.length; ++i) {
  7437. if (results[i].type == 'ssrc') {
  7438. var packetsrecv = results[i].stat('packetsReceived');
  7439. var packetslost = results[i].stat('packetsLost');
  7440. if (packetsrecv && packetslost) {
  7441. packetsrecv = parseInt(packetsrecv, 10);
  7442. packetslost = parseInt(packetslost, 10);
  7443. if (results[i].stat('googFrameRateReceived')) {
  7444. lastlost.video = lost.video;
  7445. lastrecv.video = recv.video;
  7446. recv.video = packetsrecv;
  7447. lost.video = packetslost;
  7448. } else {
  7449. lastlost.audio = lost.audio;
  7450. lastrecv.audio = recv.audio;
  7451. recv.audio = packetsrecv;
  7452. lost.audio = packetslost;
  7453. }
  7454. }
  7455. }
  7456. }
  7457. delta.audio = recv.audio - lastrecv.audio;
  7458. delta.video = recv.video - lastrecv.video;
  7459. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  7460. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  7461. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  7462. });
  7463. }
  7464. }, interval || 3000);
  7465. return this.statsinterval;
  7466. };
  7467. JingleSessionPC.onJingleError = function (session, error)
  7468. {
  7469. logger.error("Jingle error", error);
  7470. }
  7471. JingleSessionPC.onJingleFatalError = function (session, error)
  7472. {
  7473. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7474. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  7475. }
  7476. JingleSessionPC.prototype.setLocalDescription = function () {
  7477. var self = this;
  7478. var newssrcs = [];
  7479. if(!this.peerconnection.localDescription)
  7480. return;
  7481. var session = transform.parse(this.peerconnection.localDescription.sdp);
  7482. var i;
  7483. session.media.forEach(function (media) {
  7484. if (media.ssrcs && media.ssrcs.length > 0) {
  7485. // TODO(gp) maybe exclude FID streams?
  7486. media.ssrcs.forEach(function (ssrc) {
  7487. if (ssrc.attribute !== 'cname') {
  7488. return;
  7489. }
  7490. newssrcs.push({
  7491. 'ssrc': ssrc.id,
  7492. 'type': media.type
  7493. });
  7494. // FIXME allows for only one SSRC per media type
  7495. self.localStreamsSSRC[media.type] = ssrc.id;
  7496. });
  7497. }
  7498. });
  7499. logger.log('new ssrcs', newssrcs);
  7500. // Bind us as local SSRCs owner
  7501. if (newssrcs.length > 0) {
  7502. for (i = 0; i < newssrcs.length; i++) {
  7503. var ssrc = newssrcs[i].ssrc;
  7504. var myJid = self.connection.emuc.myroomjid;
  7505. self.ssrcOwners[ssrc] = myJid;
  7506. }
  7507. }
  7508. }
  7509. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7510. JingleSessionPC.prototype.sendKeyframe = function () {
  7511. var pc = this.peerconnection;
  7512. logger.log('sendkeyframe', pc.iceConnectionState);
  7513. if (pc.iceConnectionState !== 'connected') return; // safe...
  7514. var self = this;
  7515. pc.setRemoteDescription(
  7516. pc.remoteDescription,
  7517. function () {
  7518. pc.createAnswer(
  7519. function (modifiedAnswer) {
  7520. pc.setLocalDescription(
  7521. modifiedAnswer,
  7522. function () {
  7523. // noop
  7524. },
  7525. function (error) {
  7526. logger.log('triggerKeyframe setLocalDescription failed', error);
  7527. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  7528. }
  7529. );
  7530. },
  7531. function (error) {
  7532. logger.log('triggerKeyframe createAnswer failed', error);
  7533. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  7534. }
  7535. );
  7536. },
  7537. function (error) {
  7538. logger.log('triggerKeyframe setRemoteDescription failed', error);
  7539. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  7540. }
  7541. );
  7542. }
  7543. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  7544. var self = this;
  7545. var thessrc;
  7546. var streamId = RTC.getStreamID(data.stream);
  7547. // look up an associated JID for a stream id
  7548. if (!streamId) {
  7549. logger.error("No stream ID for", data.stream);
  7550. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  7551. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  7552. var ssrclines = this.peerconnection.remoteDescription?
  7553. SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:') : [];
  7554. ssrclines = ssrclines.filter(function (line) {
  7555. // NOTE(gp) previously we filtered on the mslabel, but that property
  7556. // is not always present.
  7557. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  7558. if (RTCBrowserType.isTemasysPluginUsed()) {
  7559. return ((line.indexOf('mslabel:' + streamId) !== -1));
  7560. } else {
  7561. return ((line.indexOf('msid:' + streamId) !== -1));
  7562. }
  7563. });
  7564. if (ssrclines.length) {
  7565. thessrc = ssrclines[0].substring(7).split(' ')[0];
  7566. if (!self.ssrcOwners[thessrc]) {
  7567. logger.error("No SSRC owner known for: " + thessrc);
  7568. return;
  7569. }
  7570. data.peerjid = self.ssrcOwners[thessrc];
  7571. logger.log('associated jid', self.ssrcOwners[thessrc]);
  7572. } else {
  7573. logger.error("No SSRC lines for ", streamId);
  7574. }
  7575. }
  7576. this.room.remoteStreamAdded(data, this.sid, thessrc);
  7577. var isVideo = data.stream.getVideoTracks().length > 0;
  7578. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7579. if (isVideo &&
  7580. data.peerjid && this.peerjid === data.peerjid &&
  7581. data.stream.getVideoTracks().length === 0 &&
  7582. RTC.localVideo.getTracks().length > 0) {
  7583. window.setTimeout(function () {
  7584. self.sendKeyframe();
  7585. }, 3000);
  7586. }
  7587. }
  7588. /**
  7589. * Returns the ice connection state for the peer connection.
  7590. * @returns the ice connection state for the peer connection.
  7591. */
  7592. JingleSessionPC.prototype.getIceConnectionState = function () {
  7593. return this.peerconnection.iceConnectionState;
  7594. }
  7595. module.exports = JingleSessionPC;
  7596. }).call(this,"/modules/xmpp/JingleSessionPC.js")
  7597. },{"../../service/xmpp/XMPPEvents":87,"../RTC/RTC":16,"../RTC/RTCBrowserType":17,"./JingleSession":27,"./LocalSSRCReplacement":29,"./SDP":30,"./SDPDiffer":31,"./SDPUtil":32,"./TraceablePeerConnection":33,"async":43,"jitsi-meet-logger":48,"sdp-transform":76}],29:[function(require,module,exports){
  7598. (function (__filename){
  7599. /* global $ */
  7600. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7601. /*
  7602. Here we do modifications of local video SSRCs. There are 2 situations we have
  7603. to handle:
  7604. 1. We generate SSRC for local recvonly video stream. This is the case when we
  7605. have no local camera and it is not generated automatically, but SSRC=1 is
  7606. used implicitly. If that happens RTCP packets will be dropped by the JVB
  7607. and we won't be able to request video key frames correctly.
  7608. 2. A hack to re-use SSRC of the first video stream for any new stream created
  7609. in future. It turned out that Chrome may keep on using the SSRC of removed
  7610. video stream in RTCP even though a new one has been created. So we just
  7611. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  7612. notifications are blocked once first video SSRC is advertised to the focus.
  7613. What this hack does:
  7614. 1. Stores the SSRC of the first video stream created by
  7615. a) scanning Jingle session-accept/session-invite for existing video SSRC
  7616. b) watching for 'source-add' for new video stream if it has not been
  7617. created in step a)
  7618. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  7619. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  7620. returned to the other parts of the application.
  7621. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  7622. blocks those notifications. This makes Jicofo and all participants think
  7623. that it exists all the time even if the video stream has been removed or
  7624. replaced locally. Thanks to that there is no additional signaling activity
  7625. on video mute or when switching to the desktop stream.
  7626. */
  7627. var SDP = require('./SDP');
  7628. var RandomUtil = require('../util/RandomUtil');
  7629. var RTCBrowserType = require('../RTC/RTCBrowserType');
  7630. /**
  7631. * The hack is enabled on all browsers except FF by default
  7632. * FIXME finish the hack once removeStream method is implemented in FF
  7633. * @type {boolean}
  7634. */
  7635. var isEnabled = !RTCBrowserType.isFirefox();
  7636. /**
  7637. * Stored SSRC of local video stream.
  7638. */
  7639. var localVideoSSRC;
  7640. /**
  7641. * SSRC used for recvonly video stream when we have no local camera.
  7642. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  7643. * instead of 1.
  7644. */
  7645. var localRecvOnlySSRC, localRecvOnlyMSID, localRecvOnlyMSLabel, localRecvOnlyLabel;
  7646. /**
  7647. * cname for <tt>localRecvOnlySSRC</tt>
  7648. */
  7649. var localRecvOnlyCName;
  7650. /**
  7651. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  7652. * from given Jingle IQ.
  7653. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  7654. * @param actionName display name of the action which will be printed in log
  7655. * messages.
  7656. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  7657. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  7658. * other SSRCs left to be signaled after removing it.
  7659. */
  7660. var filterOutSource = function (modifyIq, actionName) {
  7661. var modifyIqTree = $(modifyIq.tree());
  7662. if (!localVideoSSRC)
  7663. return modifyIqTree[0];
  7664. var videoSSRC = modifyIqTree.find(
  7665. '>jingle>content[name="video"]' +
  7666. '>description>source[ssrc="' + localVideoSSRC + '"]');
  7667. if (!videoSSRC.length) {
  7668. return modifyIqTree[0];
  7669. }
  7670. logger.info(
  7671. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  7672. videoSSRC.remove();
  7673. // Check if any sources still left to be added/removed
  7674. if (modifyIqTree.find('>jingle>content>description>source').length) {
  7675. return modifyIqTree[0];
  7676. } else {
  7677. return null;
  7678. }
  7679. };
  7680. /**
  7681. * Scans given Jingle IQ for video SSRC and stores it.
  7682. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  7683. */
  7684. var storeLocalVideoSSRC = function (jingleIq) {
  7685. var videoSSRCs =
  7686. $(jingleIq.tree())
  7687. .find('>jingle>content[name="video"]>description>source');
  7688. videoSSRCs.each(function (idx, ssrcElem) {
  7689. if (localVideoSSRC)
  7690. return;
  7691. // We consider SSRC real only if it has msid attribute
  7692. // recvonly streams in FF do not have it as well as local SSRCs
  7693. // we generate for recvonly streams in Chrome
  7694. var ssrSel = $(ssrcElem);
  7695. var msid = ssrSel.find('>parameter[name="msid"]');
  7696. if (msid.length) {
  7697. var ssrcVal = ssrSel.attr('ssrc');
  7698. if (ssrcVal) {
  7699. localVideoSSRC = ssrcVal;
  7700. logger.info('Stored local video SSRC' +
  7701. ' for future re-use: ' + localVideoSSRC);
  7702. }
  7703. }
  7704. });
  7705. };
  7706. /**
  7707. * Generates new label/mslabel attribute
  7708. * @returns {string} label/mslabel attribute
  7709. */
  7710. function generateLabel() {
  7711. return RandomUtil.randomHexString(8) + "-" + RandomUtil.randomHexString(4) +
  7712. "-" + RandomUtil.randomHexString(4) + "-" +
  7713. RandomUtil.randomHexString(4) + "-" + RandomUtil.randomHexString(12);
  7714. }
  7715. /**
  7716. * Generates new SSRC for local video recvonly stream.
  7717. * FIXME what about eventual SSRC collision ?
  7718. */
  7719. function generateRecvonlySSRC() {
  7720. localVideoSSRC = localRecvOnlySSRC =
  7721. localVideoSSRC ?
  7722. localVideoSSRC : Math.random().toString(10).substring(2, 11);
  7723. localRecvOnlyCName =
  7724. Math.random().toString(36).substring(2);
  7725. localRecvOnlyMSLabel = generateLabel();
  7726. localRecvOnlyLabel = generateLabel();
  7727. localRecvOnlyMSID = localRecvOnlyMSLabel + " " + localRecvOnlyLabel;
  7728. logger.info(
  7729. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  7730. ", cname: " + localRecvOnlyCName);
  7731. }
  7732. var LocalSSRCReplacement = {
  7733. /**
  7734. * Method must be called before 'session-initiate' or 'session-invite' is
  7735. * sent. Scans the IQ for local video SSRC and stores it if detected.
  7736. *
  7737. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  7738. * which will be scanned for local video SSRC.
  7739. */
  7740. processSessionInit: function (sessionInit) {
  7741. if (!isEnabled)
  7742. return;
  7743. if (localVideoSSRC) {
  7744. logger.error("Local SSRC stored already: " + localVideoSSRC);
  7745. return;
  7746. }
  7747. storeLocalVideoSSRC(sessionInit);
  7748. },
  7749. /**
  7750. * If we have local video SSRC stored searched given
  7751. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  7752. * with the stored one.
  7753. * @param localDescription local description object that will have local
  7754. * video SSRC replaced with the stored one
  7755. * @returns modified <tt>localDescription</tt> object.
  7756. */
  7757. mungeLocalVideoSSRC: function (localDescription) {
  7758. if (!isEnabled)
  7759. return localDescription;
  7760. if (!localDescription) {
  7761. logger.warn("localDescription is null or undefined");
  7762. return localDescription;
  7763. }
  7764. // IF we have local video SSRC stored make sure it is replaced
  7765. // with old SSRC
  7766. var sdp = new SDP(localDescription.sdp);
  7767. if (sdp.media.length < 2)
  7768. return;
  7769. if (localVideoSSRC && sdp.media[1].indexOf("a=ssrc:") !== -1 &&
  7770. !sdp.containsSSRC(localVideoSSRC)) {
  7771. // Get new video SSRC
  7772. var map = sdp.getMediaSsrcMap();
  7773. var videoPart = map[1];
  7774. var videoSSRCs = videoPart.ssrcs;
  7775. var newSSRC = Object.keys(videoSSRCs)[0];
  7776. logger.info(
  7777. "Replacing new video SSRC: " + newSSRC +
  7778. " with " + localVideoSSRC);
  7779. localDescription.sdp =
  7780. sdp.raw.replace(
  7781. new RegExp('a=ssrc:' + newSSRC, 'g'),
  7782. 'a=ssrc:' + localVideoSSRC);
  7783. }
  7784. else if (sdp.media[1].indexOf('a=ssrc:') === -1 &&
  7785. sdp.media[1].indexOf('a=recvonly') !== -1) {
  7786. // Make sure we have any SSRC for recvonly video stream
  7787. if (!localRecvOnlySSRC) {
  7788. generateRecvonlySSRC();
  7789. }
  7790. logger.info('No SSRC in video recvonly stream' +
  7791. ' - adding SSRC: ' + localRecvOnlySSRC);
  7792. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  7793. ' cname:' + localRecvOnlyCName + '\r\n' +
  7794. 'a=ssrc:' + localRecvOnlySSRC +
  7795. ' msid:' + localRecvOnlyMSID + '\r\n' +
  7796. 'a=ssrc:' + localRecvOnlySSRC +
  7797. ' mslabel:' + localRecvOnlyMSLabel + '\r\n' +
  7798. 'a=ssrc:' + localRecvOnlySSRC +
  7799. ' label:' + localRecvOnlyLabel + '\r\n';
  7800. localDescription.sdp = sdp.session + sdp.media.join('');
  7801. }
  7802. return localDescription;
  7803. },
  7804. /**
  7805. * Method must be called before 'source-add' notification is sent. In case
  7806. * we have local video SSRC advertised already it will be removed from the
  7807. * notification. If no other SSRCs are described by given IQ null will be
  7808. * returned which means that there is no point in sending the notification.
  7809. * @param sourceAdd 'source-add' Jingle IQ to be processed
  7810. * @returns modified 'source-add' IQ which can be sent to the focus or
  7811. * <tt>null</tt> if no notification shall be sent. It is no longer
  7812. * a Strophe IQ Builder instance, but DOM element tree.
  7813. */
  7814. processSourceAdd: function (sourceAdd) {
  7815. if (!isEnabled)
  7816. return sourceAdd;
  7817. if (!localVideoSSRC) {
  7818. // Store local SSRC if available
  7819. storeLocalVideoSSRC(sourceAdd);
  7820. return sourceAdd;
  7821. } else {
  7822. return filterOutSource(sourceAdd, 'source-add');
  7823. }
  7824. },
  7825. /**
  7826. * Method must be called before 'source-remove' notification is sent.
  7827. * Removes local video SSRC from the notification. If there are no other
  7828. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  7829. * means that there is no point in sending the notification.
  7830. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  7831. * @returns modified 'source-remove' IQ which can be sent to the focus or
  7832. * <tt>null</tt> if no notification shall be sent. It is no longer
  7833. * a Strophe IQ Builder instance, but DOM element tree.
  7834. */
  7835. processSourceRemove: function (sourceRemove) {
  7836. if (!isEnabled)
  7837. return sourceRemove;
  7838. return filterOutSource(sourceRemove, 'source-remove');
  7839. },
  7840. /**
  7841. * Turns the hack on or off
  7842. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  7843. * to disable it
  7844. */
  7845. setEnabled: function (enabled) {
  7846. isEnabled = enabled;
  7847. }
  7848. };
  7849. module.exports = LocalSSRCReplacement;
  7850. }).call(this,"/modules/xmpp/LocalSSRCReplacement.js")
  7851. },{"../RTC/RTCBrowserType":17,"../util/RandomUtil":25,"./SDP":30,"jitsi-meet-logger":48}],30:[function(require,module,exports){
  7852. (function (__filename){
  7853. /* jshint -W117 */
  7854. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7855. var SDPUtil = require("./SDPUtil");
  7856. // SDP STUFF
  7857. function SDP(sdp) {
  7858. /**
  7859. * Whether or not to remove TCP ice candidates when translating from/to jingle.
  7860. * @type {boolean}
  7861. */
  7862. this.removeTcpCandidates = false;
  7863. /**
  7864. * Whether or not to remove UDP ice candidates when translating from/to jingle.
  7865. * @type {boolean}
  7866. */
  7867. this.removeUdpCandidates = false;
  7868. this.media = sdp.split('\r\nm=');
  7869. for (var i = 1; i < this.media.length; i++) {
  7870. this.media[i] = 'm=' + this.media[i];
  7871. if (i != this.media.length - 1) {
  7872. this.media[i] += '\r\n';
  7873. }
  7874. }
  7875. this.session = this.media.shift() + '\r\n';
  7876. this.raw = this.session + this.media.join('');
  7877. }
  7878. /**
  7879. * Returns map of MediaChannel mapped per channel idx.
  7880. */
  7881. SDP.prototype.getMediaSsrcMap = function() {
  7882. var self = this;
  7883. var media_ssrcs = {};
  7884. var tmp;
  7885. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  7886. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  7887. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  7888. var media = {
  7889. mediaindex: mediaindex,
  7890. mid: mid,
  7891. ssrcs: {},
  7892. ssrcGroups: []
  7893. };
  7894. media_ssrcs[mediaindex] = media;
  7895. tmp.forEach(function (line) {
  7896. var linessrc = line.substring(7).split(' ')[0];
  7897. // allocate new ChannelSsrc
  7898. if(!media.ssrcs[linessrc]) {
  7899. media.ssrcs[linessrc] = {
  7900. ssrc: linessrc,
  7901. lines: []
  7902. };
  7903. }
  7904. media.ssrcs[linessrc].lines.push(line);
  7905. });
  7906. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  7907. tmp.forEach(function(line){
  7908. var idx = line.indexOf(' ');
  7909. var semantics = line.substr(0, idx).substr(13);
  7910. var ssrcs = line.substr(14 + semantics.length).split(' ');
  7911. if (ssrcs.length) {
  7912. media.ssrcGroups.push({
  7913. semantics: semantics,
  7914. ssrcs: ssrcs
  7915. });
  7916. }
  7917. });
  7918. }
  7919. return media_ssrcs;
  7920. };
  7921. /**
  7922. * Returns <tt>true</tt> if this SDP contains given SSRC.
  7923. * @param ssrc the ssrc to check.
  7924. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  7925. */
  7926. SDP.prototype.containsSSRC = function (ssrc) {
  7927. // FIXME this code is really strange - improve it if you can
  7928. var medias = this.getMediaSsrcMap();
  7929. var result = false;
  7930. Object.keys(medias).forEach(function (mediaindex) {
  7931. if (result)
  7932. return;
  7933. if (medias[mediaindex].ssrcs[ssrc]) {
  7934. result = true;
  7935. }
  7936. });
  7937. return result;
  7938. };
  7939. // remove iSAC and CN from SDP
  7940. SDP.prototype.mangle = function () {
  7941. var i, j, mline, lines, rtpmap, newdesc;
  7942. for (i = 0; i < this.media.length; i++) {
  7943. lines = this.media[i].split('\r\n');
  7944. lines.pop(); // remove empty last element
  7945. mline = SDPUtil.parse_mline(lines.shift());
  7946. if (mline.media != 'audio')
  7947. continue;
  7948. newdesc = '';
  7949. mline.fmt.length = 0;
  7950. for (j = 0; j < lines.length; j++) {
  7951. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  7952. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  7953. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  7954. continue;
  7955. mline.fmt.push(rtpmap.id);
  7956. newdesc += lines[j] + '\r\n';
  7957. } else {
  7958. newdesc += lines[j] + '\r\n';
  7959. }
  7960. }
  7961. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  7962. this.media[i] += newdesc;
  7963. }
  7964. this.raw = this.session + this.media.join('');
  7965. };
  7966. // remove lines matching prefix from session section
  7967. SDP.prototype.removeSessionLines = function(prefix) {
  7968. var self = this;
  7969. var lines = SDPUtil.find_lines(this.session, prefix);
  7970. lines.forEach(function(line) {
  7971. self.session = self.session.replace(line + '\r\n', '');
  7972. });
  7973. this.raw = this.session + this.media.join('');
  7974. return lines;
  7975. }
  7976. // remove lines matching prefix from a media section specified by mediaindex
  7977. // TODO: non-numeric mediaindex could match mid
  7978. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  7979. var self = this;
  7980. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  7981. lines.forEach(function(line) {
  7982. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  7983. });
  7984. this.raw = this.session + this.media.join('');
  7985. return lines;
  7986. }
  7987. // add content's to a jingle element
  7988. SDP.prototype.toJingle = function (elem, thecreator) {
  7989. // logger.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  7990. var self = this;
  7991. var i, j, k, mline, ssrc, rtpmap, tmp, lines;
  7992. // new bundle plan
  7993. if (SDPUtil.find_line(this.session, 'a=group:')) {
  7994. lines = SDPUtil.find_lines(this.session, 'a=group:');
  7995. for (i = 0; i < lines.length; i++) {
  7996. tmp = lines[i].split(' ');
  7997. var semantics = tmp.shift().substr(8);
  7998. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  7999. for (j = 0; j < tmp.length; j++) {
  8000. elem.c('content', {name: tmp[j]}).up();
  8001. }
  8002. elem.up();
  8003. }
  8004. }
  8005. for (i = 0; i < this.media.length; i++) {
  8006. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  8007. if (!(mline.media === 'audio' ||
  8008. mline.media === 'video' ||
  8009. mline.media === 'application'))
  8010. {
  8011. continue;
  8012. }
  8013. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  8014. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  8015. } else {
  8016. ssrc = false;
  8017. }
  8018. elem.c('content', {creator: thecreator, name: mline.media});
  8019. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  8020. // prefer identifier from a=mid if present
  8021. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  8022. elem.attrs({ name: mid });
  8023. }
  8024. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length) {
  8025. elem.c('description',
  8026. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  8027. media: mline.media });
  8028. if (ssrc) {
  8029. elem.attrs({ssrc: ssrc});
  8030. }
  8031. for (j = 0; j < mline.fmt.length; j++) {
  8032. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  8033. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  8034. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  8035. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  8036. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  8037. for (k = 0; k < tmp.length; k++) {
  8038. elem.c('parameter', tmp[k]).up();
  8039. }
  8040. }
  8041. this.rtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  8042. elem.up();
  8043. }
  8044. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  8045. elem.c('encryption', {required: 1});
  8046. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  8047. crypto.forEach(function(line) {
  8048. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  8049. });
  8050. elem.up(); // end of encryption
  8051. }
  8052. if (ssrc) {
  8053. // new style mapping
  8054. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8055. // FIXME: group by ssrc and support multiple different ssrcs
  8056. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  8057. if(ssrclines.length > 0) {
  8058. ssrclines.forEach(function (line) {
  8059. var idx = line.indexOf(' ');
  8060. var linessrc = line.substr(0, idx).substr(7);
  8061. if (linessrc != ssrc) {
  8062. elem.up();
  8063. ssrc = linessrc;
  8064. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8065. }
  8066. var kv = line.substr(idx + 1);
  8067. elem.c('parameter');
  8068. if (kv.indexOf(':') == -1) {
  8069. elem.attrs({ name: kv });
  8070. } else {
  8071. var k = kv.split(':', 2)[0];
  8072. elem.attrs({ name: k });
  8073. var v = kv.split(':', 2)[1];
  8074. v = SDPUtil.filter_special_chars(v);
  8075. elem.attrs({ value: v });
  8076. }
  8077. elem.up();
  8078. });
  8079. } else {
  8080. elem.up();
  8081. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8082. elem.c('parameter');
  8083. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  8084. elem.up();
  8085. var msid = null;
  8086. if(mline.media == "audio")
  8087. {
  8088. msid = APP.RTC.localAudio.getId();
  8089. }
  8090. else
  8091. {
  8092. msid = APP.RTC.localVideo.getId();
  8093. }
  8094. if(msid != null)
  8095. {
  8096. msid = SDPUtil.filter_special_chars(msid);
  8097. elem.c('parameter');
  8098. elem.attrs({name: "msid", value:msid});
  8099. elem.up();
  8100. elem.c('parameter');
  8101. elem.attrs({name: "mslabel", value:msid});
  8102. elem.up();
  8103. elem.c('parameter');
  8104. elem.attrs({name: "label", value:msid});
  8105. elem.up();
  8106. }
  8107. }
  8108. elem.up();
  8109. // XEP-0339 handle ssrc-group attributes
  8110. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  8111. ssrc_group_lines.forEach(function(line) {
  8112. var idx = line.indexOf(' ');
  8113. var semantics = line.substr(0, idx).substr(13);
  8114. var ssrcs = line.substr(14 + semantics.length).split(' ');
  8115. if (ssrcs.length) {
  8116. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8117. ssrcs.forEach(function(ssrc) {
  8118. elem.c('source', { ssrc: ssrc })
  8119. .up();
  8120. });
  8121. elem.up();
  8122. }
  8123. });
  8124. }
  8125. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  8126. elem.c('rtcp-mux').up();
  8127. }
  8128. // XEP-0293 -- map a=rtcp-fb:*
  8129. this.rtcpFbToJingle(i, elem, '*');
  8130. // XEP-0294
  8131. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  8132. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  8133. for (j = 0; j < lines.length; j++) {
  8134. tmp = SDPUtil.parse_extmap(lines[j]);
  8135. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  8136. uri: tmp.uri,
  8137. id: tmp.value });
  8138. if (tmp.hasOwnProperty('direction')) {
  8139. switch (tmp.direction) {
  8140. case 'sendonly':
  8141. elem.attrs({senders: 'responder'});
  8142. break;
  8143. case 'recvonly':
  8144. elem.attrs({senders: 'initiator'});
  8145. break;
  8146. case 'sendrecv':
  8147. elem.attrs({senders: 'both'});
  8148. break;
  8149. case 'inactive':
  8150. elem.attrs({senders: 'none'});
  8151. break;
  8152. }
  8153. }
  8154. // TODO: handle params
  8155. elem.up();
  8156. }
  8157. }
  8158. elem.up(); // end of description
  8159. }
  8160. // map ice-ufrag/pwd, dtls fingerprint, candidates
  8161. this.transportToJingle(i, elem);
  8162. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  8163. elem.attrs({senders: 'both'});
  8164. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  8165. elem.attrs({senders: 'initiator'});
  8166. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  8167. elem.attrs({senders: 'responder'});
  8168. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  8169. elem.attrs({senders: 'none'});
  8170. }
  8171. if (mline.port == '0') {
  8172. // estos hack to reject an m-line
  8173. elem.attrs({senders: 'rejected'});
  8174. }
  8175. elem.up(); // end of content
  8176. }
  8177. elem.up();
  8178. return elem;
  8179. };
  8180. SDP.prototype.transportToJingle = function (mediaindex, elem) {
  8181. var tmp, sctpmap, sctpAttrs, fingerprints;
  8182. var self = this;
  8183. elem.c('transport');
  8184. // XEP-0343 DTLS/SCTP
  8185. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  8186. {
  8187. sctpmap = SDPUtil.find_line(
  8188. this.media[mediaindex], 'a=sctpmap:', self.session);
  8189. if (sctpmap)
  8190. {
  8191. sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  8192. elem.c('sctpmap',
  8193. {
  8194. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  8195. number: sctpAttrs[0], /* SCTP port */
  8196. protocol: sctpAttrs[1] /* protocol */
  8197. });
  8198. // Optional stream count attribute
  8199. if (sctpAttrs.length > 2)
  8200. elem.attrs({ streams: sctpAttrs[2]});
  8201. elem.up();
  8202. }
  8203. }
  8204. // XEP-0320
  8205. fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  8206. fingerprints.forEach(function(line) {
  8207. tmp = SDPUtil.parse_fingerprint(line);
  8208. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  8209. elem.c('fingerprint').t(tmp.fingerprint);
  8210. delete tmp.fingerprint;
  8211. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  8212. if (line) {
  8213. tmp.setup = line.substr(8);
  8214. }
  8215. elem.attrs(tmp);
  8216. elem.up(); // end of fingerprint
  8217. });
  8218. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  8219. if (tmp) {
  8220. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  8221. elem.attrs(tmp);
  8222. // XEP-0176
  8223. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  8224. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  8225. lines.forEach(function (line) {
  8226. var candidate = SDPUtil.candidateToJingle(line);
  8227. var protocol = (candidate &&
  8228. typeof candidate.protocol === 'string')
  8229. ? candidate.protocol.toLowerCase() : '';
  8230. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  8231. (self.removeUdpCandidates && protocol === 'udp')) {
  8232. return;
  8233. }
  8234. elem.c('candidate', candidate).up();
  8235. });
  8236. }
  8237. }
  8238. elem.up(); // end of transport
  8239. }
  8240. SDP.prototype.rtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  8241. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  8242. lines.forEach(function (line) {
  8243. var tmp = SDPUtil.parse_rtcpfb(line);
  8244. if (tmp.type == 'trr-int') {
  8245. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  8246. elem.up();
  8247. } else {
  8248. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  8249. if (tmp.params.length > 0) {
  8250. elem.attrs({'subtype': tmp.params[0]});
  8251. }
  8252. elem.up();
  8253. }
  8254. });
  8255. };
  8256. SDP.prototype.rtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  8257. var media = '';
  8258. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  8259. if (tmp.length) {
  8260. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  8261. if (tmp.attr('value')) {
  8262. media += tmp.attr('value');
  8263. } else {
  8264. media += '0';
  8265. }
  8266. media += '\r\n';
  8267. }
  8268. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  8269. tmp.each(function () {
  8270. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  8271. if ($(this).attr('subtype')) {
  8272. media += ' ' + $(this).attr('subtype');
  8273. }
  8274. media += '\r\n';
  8275. });
  8276. return media;
  8277. };
  8278. // construct an SDP from a jingle stanza
  8279. SDP.prototype.fromJingle = function (jingle) {
  8280. var self = this;
  8281. this.raw = 'v=0\r\n' +
  8282. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  8283. 's=-\r\n' +
  8284. 't=0 0\r\n';
  8285. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  8286. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  8287. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  8288. var contents = $(group).find('>content').map(function (idx, content) {
  8289. return content.getAttribute('name');
  8290. }).get();
  8291. if (contents.length > 0) {
  8292. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  8293. }
  8294. });
  8295. }
  8296. this.session = this.raw;
  8297. jingle.find('>content').each(function () {
  8298. var m = self.jingle2media($(this));
  8299. self.media.push(m);
  8300. });
  8301. // reconstruct msid-semantic -- apparently not necessary
  8302. /*
  8303. var msid = SDPUtil.parse_ssrc(this.raw);
  8304. if (msid.hasOwnProperty('mslabel')) {
  8305. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  8306. }
  8307. */
  8308. this.raw = this.session + this.media.join('');
  8309. };
  8310. // translate a jingle content element into an an SDP media part
  8311. SDP.prototype.jingle2media = function (content) {
  8312. var media = '',
  8313. desc = content.find('description'),
  8314. ssrc = desc.attr('ssrc'),
  8315. self = this,
  8316. tmp;
  8317. var sctp = content.find(
  8318. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  8319. tmp = { media: desc.attr('media') };
  8320. tmp.port = '1';
  8321. if (content.attr('senders') == 'rejected') {
  8322. // estos hack to reject an m-line.
  8323. tmp.port = '0';
  8324. }
  8325. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  8326. if (sctp.length)
  8327. tmp.proto = 'DTLS/SCTP';
  8328. else
  8329. tmp.proto = 'RTP/SAVPF';
  8330. } else {
  8331. tmp.proto = 'RTP/AVPF';
  8332. }
  8333. if (!sctp.length) {
  8334. tmp.fmt = desc.find('payload-type').map(
  8335. function () { return this.getAttribute('id'); }).get();
  8336. media += SDPUtil.build_mline(tmp) + '\r\n';
  8337. } else {
  8338. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  8339. media += 'a=sctpmap:' + sctp.attr('number') +
  8340. ' ' + sctp.attr('protocol');
  8341. var streamCount = sctp.attr('streams');
  8342. if (streamCount)
  8343. media += ' ' + streamCount + '\r\n';
  8344. else
  8345. media += '\r\n';
  8346. }
  8347. media += 'c=IN IP4 0.0.0.0\r\n';
  8348. if (!sctp.length)
  8349. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  8350. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  8351. if (tmp.length) {
  8352. if (tmp.attr('ufrag')) {
  8353. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  8354. }
  8355. if (tmp.attr('pwd')) {
  8356. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  8357. }
  8358. tmp.find('>fingerprint').each(function () {
  8359. // FIXME: check namespace at some point
  8360. media += 'a=fingerprint:' + this.getAttribute('hash');
  8361. media += ' ' + $(this).text();
  8362. media += '\r\n';
  8363. if (this.getAttribute('setup')) {
  8364. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  8365. }
  8366. });
  8367. }
  8368. switch (content.attr('senders')) {
  8369. case 'initiator':
  8370. media += 'a=sendonly\r\n';
  8371. break;
  8372. case 'responder':
  8373. media += 'a=recvonly\r\n';
  8374. break;
  8375. case 'none':
  8376. media += 'a=inactive\r\n';
  8377. break;
  8378. case 'both':
  8379. media += 'a=sendrecv\r\n';
  8380. break;
  8381. }
  8382. media += 'a=mid:' + content.attr('name') + '\r\n';
  8383. // <description><rtcp-mux/></description>
  8384. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  8385. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  8386. if (desc.find('rtcp-mux').length) {
  8387. media += 'a=rtcp-mux\r\n';
  8388. }
  8389. if (desc.find('encryption').length) {
  8390. desc.find('encryption>crypto').each(function () {
  8391. media += 'a=crypto:' + this.getAttribute('tag');
  8392. media += ' ' + this.getAttribute('crypto-suite');
  8393. media += ' ' + this.getAttribute('key-params');
  8394. if (this.getAttribute('session-params')) {
  8395. media += ' ' + this.getAttribute('session-params');
  8396. }
  8397. media += '\r\n';
  8398. });
  8399. }
  8400. desc.find('payload-type').each(function () {
  8401. media += SDPUtil.build_rtpmap(this) + '\r\n';
  8402. if ($(this).find('>parameter').length) {
  8403. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  8404. media += $(this).find('parameter').map(function () {
  8405. return (this.getAttribute('name')
  8406. ? (this.getAttribute('name') + '=') : '') +
  8407. this.getAttribute('value');
  8408. }).get().join('; ');
  8409. media += '\r\n';
  8410. }
  8411. // xep-0293
  8412. media += self.rtcpFbFromJingle($(this), this.getAttribute('id'));
  8413. });
  8414. // xep-0293
  8415. media += self.rtcpFbFromJingle(desc, '*');
  8416. // xep-0294
  8417. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  8418. tmp.each(function () {
  8419. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  8420. });
  8421. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  8422. var protocol = this.getAttribute('protocol');
  8423. protocol = (typeof protocol === 'string') ? protocol.toLowerCase(): '';
  8424. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  8425. (self.removeUdpCandidates && protocol === 'udp')) {
  8426. return;
  8427. }
  8428. media += SDPUtil.candidateFromJingle(this);
  8429. });
  8430. // XEP-0339 handle ssrc-group attributes
  8431. content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8432. var semantics = this.getAttribute('semantics');
  8433. var ssrcs = $(this).find('>source').map(function() {
  8434. return this.getAttribute('ssrc');
  8435. }).get();
  8436. if (ssrcs.length) {
  8437. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8438. }
  8439. });
  8440. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  8441. tmp.each(function () {
  8442. var ssrc = this.getAttribute('ssrc');
  8443. $(this).find('>parameter').each(function () {
  8444. var name = this.getAttribute('name');
  8445. var value = this.getAttribute('value');
  8446. value = SDPUtil.filter_special_chars(value);
  8447. media += 'a=ssrc:' + ssrc + ' ' + name;
  8448. if (value && value.length)
  8449. media += ':' + value;
  8450. media += '\r\n';
  8451. });
  8452. });
  8453. return media;
  8454. };
  8455. module.exports = SDP;
  8456. }).call(this,"/modules/xmpp/SDP.js")
  8457. },{"./SDPUtil":32,"jitsi-meet-logger":48}],31:[function(require,module,exports){
  8458. var SDPUtil = require("./SDPUtil");
  8459. function SDPDiffer(mySDP, otherSDP)
  8460. {
  8461. this.mySDP = mySDP;
  8462. this.otherSDP = otherSDP;
  8463. }
  8464. /**
  8465. * Returns map of MediaChannel that contains media contained in
  8466. * 'mySDP', but not contained in 'otherSdp'. Mapped by channel idx.
  8467. */
  8468. SDPDiffer.prototype.getNewMedia = function() {
  8469. // this could be useful in Array.prototype.
  8470. function arrayEquals(array) {
  8471. // if the other array is a falsy value, return
  8472. if (!array)
  8473. return false;
  8474. // compare lengths - can save a lot of time
  8475. if (this.length != array.length)
  8476. return false;
  8477. for (var i = 0, l=this.length; i < l; i++) {
  8478. // Check if we have nested arrays
  8479. if (this[i] instanceof Array && array[i] instanceof Array) {
  8480. // recurse into the nested arrays
  8481. if (!this[i].equals(array[i]))
  8482. return false;
  8483. }
  8484. else if (this[i] != array[i]) {
  8485. // Warning - two different object instances will never be
  8486. // equal: {x:20} != {x:20}
  8487. return false;
  8488. }
  8489. }
  8490. return true;
  8491. }
  8492. var myMedias = this.mySDP.getMediaSsrcMap();
  8493. var othersMedias = this.otherSDP.getMediaSsrcMap();
  8494. var newMedia = {};
  8495. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  8496. var myMedia = myMedias[othersMediaIdx];
  8497. var othersMedia = othersMedias[othersMediaIdx];
  8498. if(!myMedia && othersMedia) {
  8499. // Add whole channel
  8500. newMedia[othersMediaIdx] = othersMedia;
  8501. return;
  8502. }
  8503. // Look for new ssrcs across the channel
  8504. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  8505. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  8506. // Allocate channel if we've found ssrc that doesn't exist in
  8507. // our channel
  8508. if(!newMedia[othersMediaIdx]){
  8509. newMedia[othersMediaIdx] = {
  8510. mediaindex: othersMedia.mediaindex,
  8511. mid: othersMedia.mid,
  8512. ssrcs: {},
  8513. ssrcGroups: []
  8514. };
  8515. }
  8516. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  8517. }
  8518. });
  8519. // Look for new ssrc groups across the channels
  8520. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  8521. // try to match the other ssrc-group with an ssrc-group of ours
  8522. var matched = false;
  8523. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  8524. var mySsrcGroup = myMedia.ssrcGroups[i];
  8525. if (otherSsrcGroup.semantics == mySsrcGroup.semantics &&
  8526. arrayEquals.apply(otherSsrcGroup.ssrcs,
  8527. [mySsrcGroup.ssrcs])) {
  8528. matched = true;
  8529. break;
  8530. }
  8531. }
  8532. if (!matched) {
  8533. // Allocate channel if we've found an ssrc-group that doesn't
  8534. // exist in our channel
  8535. if(!newMedia[othersMediaIdx]){
  8536. newMedia[othersMediaIdx] = {
  8537. mediaindex: othersMedia.mediaindex,
  8538. mid: othersMedia.mid,
  8539. ssrcs: {},
  8540. ssrcGroups: []
  8541. };
  8542. }
  8543. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  8544. }
  8545. });
  8546. });
  8547. return newMedia;
  8548. };
  8549. /**
  8550. * TODO: document!
  8551. */
  8552. SDPDiffer.prototype.toJingle = function(modify) {
  8553. var sdpMediaSsrcs = this.getNewMedia();
  8554. var modified = false;
  8555. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  8556. modified = true;
  8557. var media = sdpMediaSsrcs[mediaindex];
  8558. modify.c('content', {name: media.mid});
  8559. modify.c('description',
  8560. {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  8561. // FIXME: not completely sure this operates on blocks and / or handles
  8562. // different ssrcs correctly
  8563. // generate sources from lines
  8564. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  8565. var mediaSsrc = media.ssrcs[ssrcNum];
  8566. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8567. modify.attrs({ssrc: mediaSsrc.ssrc});
  8568. // iterate over ssrc lines
  8569. mediaSsrc.lines.forEach(function (line) {
  8570. var idx = line.indexOf(' ');
  8571. var kv = line.substr(idx + 1);
  8572. modify.c('parameter');
  8573. if (kv.indexOf(':') == -1) {
  8574. modify.attrs({ name: kv });
  8575. } else {
  8576. var nv = kv.split(':', 2);
  8577. var name = nv[0];
  8578. var value = SDPUtil.filter_special_chars(nv[1]);
  8579. modify.attrs({ name: name });
  8580. modify.attrs({ value: value });
  8581. }
  8582. modify.up(); // end of parameter
  8583. });
  8584. modify.up(); // end of source
  8585. });
  8586. // generate source groups from lines
  8587. media.ssrcGroups.forEach(function(ssrcGroup) {
  8588. if (ssrcGroup.ssrcs.length) {
  8589. modify.c('ssrc-group', {
  8590. semantics: ssrcGroup.semantics,
  8591. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  8592. });
  8593. ssrcGroup.ssrcs.forEach(function (ssrc) {
  8594. modify.c('source', { ssrc: ssrc })
  8595. .up(); // end of source
  8596. });
  8597. modify.up(); // end of ssrc-group
  8598. }
  8599. });
  8600. modify.up(); // end of description
  8601. modify.up(); // end of content
  8602. });
  8603. return modified;
  8604. };
  8605. module.exports = SDPDiffer;
  8606. },{"./SDPUtil":32}],32:[function(require,module,exports){
  8607. (function (__filename){
  8608. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8609. var RTCBrowserType = require("../RTC/RTCBrowserType");
  8610. SDPUtil = {
  8611. filter_special_chars: function (text) {
  8612. return text.replace(/[\\\/\{,\}\+]/g, "");
  8613. },
  8614. iceparams: function (mediadesc, sessiondesc) {
  8615. var data = null;
  8616. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  8617. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  8618. data = {
  8619. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  8620. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  8621. };
  8622. }
  8623. return data;
  8624. },
  8625. parse_iceufrag: function (line) {
  8626. return line.substring(12);
  8627. },
  8628. build_iceufrag: function (frag) {
  8629. return 'a=ice-ufrag:' + frag;
  8630. },
  8631. parse_icepwd: function (line) {
  8632. return line.substring(10);
  8633. },
  8634. build_icepwd: function (pwd) {
  8635. return 'a=ice-pwd:' + pwd;
  8636. },
  8637. parse_mid: function (line) {
  8638. return line.substring(6);
  8639. },
  8640. parse_mline: function (line) {
  8641. var parts = line.substring(2).split(' '),
  8642. data = {};
  8643. data.media = parts.shift();
  8644. data.port = parts.shift();
  8645. data.proto = parts.shift();
  8646. if (parts[parts.length - 1] === '') { // trailing whitespace
  8647. parts.pop();
  8648. }
  8649. data.fmt = parts;
  8650. return data;
  8651. },
  8652. build_mline: function (mline) {
  8653. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  8654. },
  8655. parse_rtpmap: function (line) {
  8656. var parts = line.substring(9).split(' '),
  8657. data = {};
  8658. data.id = parts.shift();
  8659. parts = parts[0].split('/');
  8660. data.name = parts.shift();
  8661. data.clockrate = parts.shift();
  8662. data.channels = parts.length ? parts.shift() : '1';
  8663. return data;
  8664. },
  8665. /**
  8666. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  8667. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  8668. * @returns [SCTP port number, protocol, streams]
  8669. */
  8670. parse_sctpmap: function (line)
  8671. {
  8672. var parts = line.substring(10).split(' ');
  8673. var sctpPort = parts[0];
  8674. var protocol = parts[1];
  8675. // Stream count is optional
  8676. var streamCount = parts.length > 2 ? parts[2] : null;
  8677. return [sctpPort, protocol, streamCount];// SCTP port
  8678. },
  8679. build_rtpmap: function (el) {
  8680. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  8681. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  8682. line += '/' + el.getAttribute('channels');
  8683. }
  8684. return line;
  8685. },
  8686. parse_crypto: function (line) {
  8687. var parts = line.substring(9).split(' '),
  8688. data = {};
  8689. data.tag = parts.shift();
  8690. data['crypto-suite'] = parts.shift();
  8691. data['key-params'] = parts.shift();
  8692. if (parts.length) {
  8693. data['session-params'] = parts.join(' ');
  8694. }
  8695. return data;
  8696. },
  8697. parse_fingerprint: function (line) { // RFC 4572
  8698. var parts = line.substring(14).split(' '),
  8699. data = {};
  8700. data.hash = parts.shift();
  8701. data.fingerprint = parts.shift();
  8702. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  8703. return data;
  8704. },
  8705. parse_fmtp: function (line) {
  8706. var parts = line.split(' '),
  8707. i, key, value,
  8708. data = [];
  8709. parts.shift();
  8710. parts = parts.join(' ').split(';');
  8711. for (i = 0; i < parts.length; i++) {
  8712. key = parts[i].split('=')[0];
  8713. while (key.length && key[0] == ' ') {
  8714. key = key.substring(1);
  8715. }
  8716. value = parts[i].split('=')[1];
  8717. if (key && value) {
  8718. data.push({name: key, value: value});
  8719. } else if (key) {
  8720. // rfc 4733 (DTMF) style stuff
  8721. data.push({name: '', value: key});
  8722. }
  8723. }
  8724. return data;
  8725. },
  8726. parse_icecandidate: function (line) {
  8727. var candidate = {},
  8728. elems = line.split(' ');
  8729. candidate.foundation = elems[0].substring(12);
  8730. candidate.component = elems[1];
  8731. candidate.protocol = elems[2].toLowerCase();
  8732. candidate.priority = elems[3];
  8733. candidate.ip = elems[4];
  8734. candidate.port = elems[5];
  8735. // elems[6] => "typ"
  8736. candidate.type = elems[7];
  8737. candidate.generation = 0; // default value, may be overwritten below
  8738. for (var i = 8; i < elems.length; i += 2) {
  8739. switch (elems[i]) {
  8740. case 'raddr':
  8741. candidate['rel-addr'] = elems[i + 1];
  8742. break;
  8743. case 'rport':
  8744. candidate['rel-port'] = elems[i + 1];
  8745. break;
  8746. case 'generation':
  8747. candidate.generation = elems[i + 1];
  8748. break;
  8749. case 'tcptype':
  8750. candidate.tcptype = elems[i + 1];
  8751. break;
  8752. default: // TODO
  8753. logger.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  8754. }
  8755. }
  8756. candidate.network = '1';
  8757. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  8758. return candidate;
  8759. },
  8760. build_icecandidate: function (cand) {
  8761. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  8762. line += ' ';
  8763. switch (cand.type) {
  8764. case 'srflx':
  8765. case 'prflx':
  8766. case 'relay':
  8767. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  8768. line += 'raddr';
  8769. line += ' ';
  8770. line += cand['rel-addr'];
  8771. line += ' ';
  8772. line += 'rport';
  8773. line += ' ';
  8774. line += cand['rel-port'];
  8775. line += ' ';
  8776. }
  8777. break;
  8778. }
  8779. if (cand.hasOwnAttribute('tcptype')) {
  8780. line += 'tcptype';
  8781. line += ' ';
  8782. line += cand.tcptype;
  8783. line += ' ';
  8784. }
  8785. line += 'generation';
  8786. line += ' ';
  8787. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  8788. return line;
  8789. },
  8790. parse_ssrc: function (desc) {
  8791. // proprietary mapping of a=ssrc lines
  8792. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  8793. // and parse according to that
  8794. var lines = desc.split('\r\n'),
  8795. data = {};
  8796. for (var i = 0; i < lines.length; i++) {
  8797. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  8798. var idx = lines[i].indexOf(' ');
  8799. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  8800. }
  8801. }
  8802. return data;
  8803. },
  8804. parse_rtcpfb: function (line) {
  8805. var parts = line.substr(10).split(' ');
  8806. var data = {};
  8807. data.pt = parts.shift();
  8808. data.type = parts.shift();
  8809. data.params = parts;
  8810. return data;
  8811. },
  8812. parse_extmap: function (line) {
  8813. var parts = line.substr(9).split(' ');
  8814. var data = {};
  8815. data.value = parts.shift();
  8816. if (data.value.indexOf('/') != -1) {
  8817. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  8818. data.value = data.value.substr(0, data.value.indexOf('/'));
  8819. } else {
  8820. data.direction = 'both';
  8821. }
  8822. data.uri = parts.shift();
  8823. data.params = parts;
  8824. return data;
  8825. },
  8826. find_line: function (haystack, needle, sessionpart) {
  8827. var lines = haystack.split('\r\n');
  8828. for (var i = 0; i < lines.length; i++) {
  8829. if (lines[i].substring(0, needle.length) == needle) {
  8830. return lines[i];
  8831. }
  8832. }
  8833. if (!sessionpart) {
  8834. return false;
  8835. }
  8836. // search session part
  8837. lines = sessionpart.split('\r\n');
  8838. for (var j = 0; j < lines.length; j++) {
  8839. if (lines[j].substring(0, needle.length) == needle) {
  8840. return lines[j];
  8841. }
  8842. }
  8843. return false;
  8844. },
  8845. find_lines: function (haystack, needle, sessionpart) {
  8846. var lines = haystack.split('\r\n'),
  8847. needles = [];
  8848. for (var i = 0; i < lines.length; i++) {
  8849. if (lines[i].substring(0, needle.length) == needle)
  8850. needles.push(lines[i]);
  8851. }
  8852. if (needles.length || !sessionpart) {
  8853. return needles;
  8854. }
  8855. // search session part
  8856. lines = sessionpart.split('\r\n');
  8857. for (var j = 0; j < lines.length; j++) {
  8858. if (lines[j].substring(0, needle.length) == needle) {
  8859. needles.push(lines[j]);
  8860. }
  8861. }
  8862. return needles;
  8863. },
  8864. candidateToJingle: function (line) {
  8865. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  8866. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  8867. if (line.indexOf('candidate:') === 0) {
  8868. line = 'a=' + line;
  8869. } else if (line.substring(0, 12) != 'a=candidate:') {
  8870. logger.log('parseCandidate called with a line that is not a candidate line');
  8871. logger.log(line);
  8872. return null;
  8873. }
  8874. if (line.substring(line.length - 2) == '\r\n') // chomp it
  8875. line = line.substring(0, line.length - 2);
  8876. var candidate = {},
  8877. elems = line.split(' '),
  8878. i;
  8879. if (elems[6] != 'typ') {
  8880. logger.log('did not find typ in the right place');
  8881. logger.log(line);
  8882. return null;
  8883. }
  8884. candidate.foundation = elems[0].substring(12);
  8885. candidate.component = elems[1];
  8886. candidate.protocol = elems[2].toLowerCase();
  8887. candidate.priority = elems[3];
  8888. candidate.ip = elems[4];
  8889. candidate.port = elems[5];
  8890. // elems[6] => "typ"
  8891. candidate.type = elems[7];
  8892. candidate.generation = '0'; // default, may be overwritten below
  8893. for (i = 8; i < elems.length; i += 2) {
  8894. switch (elems[i]) {
  8895. case 'raddr':
  8896. candidate['rel-addr'] = elems[i + 1];
  8897. break;
  8898. case 'rport':
  8899. candidate['rel-port'] = elems[i + 1];
  8900. break;
  8901. case 'generation':
  8902. candidate.generation = elems[i + 1];
  8903. break;
  8904. case 'tcptype':
  8905. candidate.tcptype = elems[i + 1];
  8906. break;
  8907. default: // TODO
  8908. logger.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  8909. }
  8910. }
  8911. candidate.network = '1';
  8912. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  8913. return candidate;
  8914. },
  8915. candidateFromJingle: function (cand) {
  8916. var line = 'a=candidate:';
  8917. line += cand.getAttribute('foundation');
  8918. line += ' ';
  8919. line += cand.getAttribute('component');
  8920. line += ' ';
  8921. var protocol = cand.getAttribute('protocol');
  8922. // use tcp candidates for FF
  8923. if (RTCBrowserType.isFirefox() && protocol.toLowerCase() == 'ssltcp') {
  8924. protocol = 'tcp';
  8925. }
  8926. line += protocol; //.toUpperCase(); // chrome M23 doesn't like this
  8927. line += ' ';
  8928. line += cand.getAttribute('priority');
  8929. line += ' ';
  8930. line += cand.getAttribute('ip');
  8931. line += ' ';
  8932. line += cand.getAttribute('port');
  8933. line += ' ';
  8934. line += 'typ';
  8935. line += ' ' + cand.getAttribute('type');
  8936. line += ' ';
  8937. switch (cand.getAttribute('type')) {
  8938. case 'srflx':
  8939. case 'prflx':
  8940. case 'relay':
  8941. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  8942. line += 'raddr';
  8943. line += ' ';
  8944. line += cand.getAttribute('rel-addr');
  8945. line += ' ';
  8946. line += 'rport';
  8947. line += ' ';
  8948. line += cand.getAttribute('rel-port');
  8949. line += ' ';
  8950. }
  8951. break;
  8952. }
  8953. if (protocol.toLowerCase() == 'tcp') {
  8954. line += 'tcptype';
  8955. line += ' ';
  8956. line += cand.getAttribute('tcptype');
  8957. line += ' ';
  8958. }
  8959. line += 'generation';
  8960. line += ' ';
  8961. line += cand.getAttribute('generation') || '0';
  8962. return line + '\r\n';
  8963. }
  8964. };
  8965. module.exports = SDPUtil;
  8966. }).call(this,"/modules/xmpp/SDPUtil.js")
  8967. },{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":48}],33:[function(require,module,exports){
  8968. (function (__filename){
  8969. /* global $ */
  8970. var RTC = require('../RTC/RTC');
  8971. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8972. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  8973. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8974. var SSRCReplacement = require("./LocalSSRCReplacement");
  8975. function TraceablePeerConnection(ice_config, constraints, session) {
  8976. var self = this;
  8977. this.session = session;
  8978. var RTCPeerConnectionType = null;
  8979. if (RTCBrowserType.isFirefox()) {
  8980. RTCPeerConnectionType = mozRTCPeerConnection;
  8981. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  8982. RTCPeerConnectionType = RTCPeerConnection;
  8983. } else {
  8984. RTCPeerConnectionType = webkitRTCPeerConnection;
  8985. }
  8986. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  8987. this.updateLog = [];
  8988. this.stats = {};
  8989. this.statsinterval = null;
  8990. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  8991. var Interop = require('sdp-interop').Interop;
  8992. this.interop = new Interop();
  8993. var Simulcast = require('sdp-simulcast');
  8994. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  8995. // override as desired
  8996. this.trace = function (what, info) {
  8997. /*logger.warn('WTRACE', what, info);
  8998. if (info && RTCBrowserType.isIExplorer()) {
  8999. if (info.length > 1024) {
  9000. logger.warn('WTRACE', what, info.substr(1024));
  9001. }
  9002. if (info.length > 2048) {
  9003. logger.warn('WTRACE', what, info.substr(2048));
  9004. }
  9005. }*/
  9006. self.updateLog.push({
  9007. time: new Date(),
  9008. type: what,
  9009. value: info || ""
  9010. });
  9011. };
  9012. this.onicecandidate = null;
  9013. this.peerconnection.onicecandidate = function (event) {
  9014. // FIXME: this causes stack overflow with Temasys Plugin
  9015. if (!RTCBrowserType.isTemasysPluginUsed())
  9016. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  9017. if (self.onicecandidate !== null) {
  9018. self.onicecandidate(event);
  9019. }
  9020. };
  9021. this.onaddstream = null;
  9022. this.peerconnection.onaddstream = function (event) {
  9023. self.trace('onaddstream', event.stream.id);
  9024. if (self.onaddstream !== null) {
  9025. self.onaddstream(event);
  9026. }
  9027. };
  9028. this.onremovestream = null;
  9029. this.peerconnection.onremovestream = function (event) {
  9030. self.trace('onremovestream', event.stream.id);
  9031. if (self.onremovestream !== null) {
  9032. self.onremovestream(event);
  9033. }
  9034. };
  9035. this.onsignalingstatechange = null;
  9036. this.peerconnection.onsignalingstatechange = function (event) {
  9037. self.trace('onsignalingstatechange', self.signalingState);
  9038. if (self.onsignalingstatechange !== null) {
  9039. self.onsignalingstatechange(event);
  9040. }
  9041. };
  9042. this.oniceconnectionstatechange = null;
  9043. this.peerconnection.oniceconnectionstatechange = function (event) {
  9044. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  9045. if (self.oniceconnectionstatechange !== null) {
  9046. self.oniceconnectionstatechange(event);
  9047. }
  9048. };
  9049. this.onnegotiationneeded = null;
  9050. this.peerconnection.onnegotiationneeded = function (event) {
  9051. self.trace('onnegotiationneeded');
  9052. if (self.onnegotiationneeded !== null) {
  9053. self.onnegotiationneeded(event);
  9054. }
  9055. };
  9056. self.ondatachannel = null;
  9057. this.peerconnection.ondatachannel = function (event) {
  9058. self.trace('ondatachannel', event);
  9059. if (self.ondatachannel !== null) {
  9060. self.ondatachannel(event);
  9061. }
  9062. };
  9063. // XXX: do all non-firefox browsers which we support also support this?
  9064. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  9065. this.statsinterval = window.setInterval(function() {
  9066. self.peerconnection.getStats(function(stats) {
  9067. var results = stats.result();
  9068. var now = new Date();
  9069. for (var i = 0; i < results.length; ++i) {
  9070. results[i].names().forEach(function (name) {
  9071. var id = results[i].id + '-' + name;
  9072. if (!self.stats[id]) {
  9073. self.stats[id] = {
  9074. startTime: now,
  9075. endTime: now,
  9076. values: [],
  9077. times: []
  9078. };
  9079. }
  9080. self.stats[id].values.push(results[i].stat(name));
  9081. self.stats[id].times.push(now.getTime());
  9082. if (self.stats[id].values.length > self.maxstats) {
  9083. self.stats[id].values.shift();
  9084. self.stats[id].times.shift();
  9085. }
  9086. self.stats[id].endTime = now;
  9087. });
  9088. }
  9089. });
  9090. }, 1000);
  9091. }
  9092. }
  9093. /**
  9094. * Returns a string representation of a SessionDescription object.
  9095. */
  9096. var dumpSDP = function(description) {
  9097. if (typeof description === 'undefined' || description == null) {
  9098. return '';
  9099. }
  9100. return 'type: ' + description.type + '\r\n' + description.sdp;
  9101. };
  9102. /**
  9103. * Takes a SessionDescription object and returns a "normalized" version.
  9104. * Currently it only takes care of ordering the a=ssrc lines.
  9105. */
  9106. var normalizePlanB = function(desc) {
  9107. if (typeof desc !== 'object' || desc === null ||
  9108. typeof desc.sdp !== 'string') {
  9109. logger.warn('An empty description was passed as an argument.');
  9110. return desc;
  9111. }
  9112. var transform = require('sdp-transform');
  9113. var session = transform.parse(desc.sdp);
  9114. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  9115. Array.isArray(session.media)) {
  9116. session.media.forEach(function (mLine) {
  9117. // Chrome appears to be picky about the order in which a=ssrc lines
  9118. // are listed in an m-line when rtx is enabled (and thus there are
  9119. // a=ssrc-group lines with FID semantics). Specifically if we have
  9120. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  9121. // the "a=ssrc:S1" lines, SRD fails.
  9122. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  9123. // first.
  9124. var firstSsrcs = [];
  9125. var newSsrcLines = [];
  9126. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  9127. mLine.ssrcGroups.forEach(function (group) {
  9128. if (typeof group.semantics !== 'undefined' &&
  9129. group.semantics === 'FID') {
  9130. if (typeof group.ssrcs !== 'undefined') {
  9131. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  9132. }
  9133. }
  9134. });
  9135. }
  9136. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  9137. var i;
  9138. for (i = 0; i<mLine.ssrcs.length; i++){
  9139. if (typeof mLine.ssrcs[i] === 'object'
  9140. && typeof mLine.ssrcs[i].id !== 'undefined'
  9141. && !$.inArray(mLine.ssrcs[i].id, firstSsrcs)) {
  9142. newSsrcLines.push(mLine.ssrcs[i]);
  9143. delete mLine.ssrcs[i];
  9144. }
  9145. }
  9146. for (i = 0; i<mLine.ssrcs.length; i++){
  9147. if (typeof mLine.ssrcs[i] !== 'undefined') {
  9148. newSsrcLines.push(mLine.ssrcs[i]);
  9149. }
  9150. }
  9151. mLine.ssrcs = newSsrcLines;
  9152. }
  9153. });
  9154. }
  9155. var resStr = transform.write(session);
  9156. return new RTCSessionDescription({
  9157. type: desc.type,
  9158. sdp: resStr
  9159. });
  9160. };
  9161. var getters = {
  9162. signalingState: function () {
  9163. return this.peerconnection.signalingState;
  9164. },
  9165. iceConnectionState: function () {
  9166. return this.peerconnection.iceConnectionState;
  9167. },
  9168. localDescription: function() {
  9169. var desc = this.peerconnection.localDescription;
  9170. // FIXME this should probably be after the Unified Plan -> Plan B
  9171. // transformation.
  9172. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  9173. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  9174. // if we're running on FF, transform to Plan B first.
  9175. if (RTCBrowserType.usesUnifiedPlan()) {
  9176. desc = this.interop.toPlanB(desc);
  9177. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  9178. }
  9179. return desc;
  9180. },
  9181. remoteDescription: function() {
  9182. var desc = this.peerconnection.remoteDescription;
  9183. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  9184. // if we're running on FF, transform to Plan B first.
  9185. if (RTCBrowserType.usesUnifiedPlan()) {
  9186. desc = this.interop.toPlanB(desc);
  9187. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  9188. }
  9189. return desc;
  9190. }
  9191. };
  9192. Object.keys(getters).forEach(function (prop) {
  9193. Object.defineProperty(
  9194. TraceablePeerConnection.prototype,
  9195. prop, {
  9196. get: getters[prop]
  9197. }
  9198. );
  9199. });
  9200. TraceablePeerConnection.prototype.addStream = function (stream) {
  9201. this.trace('addStream', stream.id);
  9202. try
  9203. {
  9204. this.peerconnection.addStream(stream);
  9205. }
  9206. catch (e)
  9207. {
  9208. logger.error(e);
  9209. }
  9210. };
  9211. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  9212. this.trace('removeStream', stream.id);
  9213. if(stopStreams) {
  9214. RTC.stopMediaStream(stream);
  9215. }
  9216. try {
  9217. // FF doesn't support this yet.
  9218. if (this.peerconnection.removeStream)
  9219. this.peerconnection.removeStream(stream);
  9220. } catch (e) {
  9221. logger.error(e);
  9222. }
  9223. };
  9224. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  9225. this.trace('createDataChannel', label, opts);
  9226. return this.peerconnection.createDataChannel(label, opts);
  9227. };
  9228. TraceablePeerConnection.prototype.setLocalDescription
  9229. = function (description, successCallback, failureCallback) {
  9230. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  9231. // if we're running on FF, transform to Plan A first.
  9232. if (RTCBrowserType.usesUnifiedPlan()) {
  9233. description = this.interop.toUnifiedPlan(description);
  9234. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  9235. }
  9236. var self = this;
  9237. this.peerconnection.setLocalDescription(description,
  9238. function () {
  9239. self.trace('setLocalDescriptionOnSuccess');
  9240. successCallback();
  9241. },
  9242. function (err) {
  9243. self.trace('setLocalDescriptionOnFailure', err);
  9244. failureCallback(err);
  9245. }
  9246. );
  9247. /*
  9248. if (this.statsinterval === null && this.maxstats > 0) {
  9249. // start gathering stats
  9250. }
  9251. */
  9252. };
  9253. TraceablePeerConnection.prototype.setRemoteDescription
  9254. = function (description, successCallback, failureCallback) {
  9255. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  9256. // TODO the focus should squeze or explode the remote simulcast
  9257. description = this.simulcast.mungeRemoteDescription(description);
  9258. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  9259. // if we're running on FF, transform to Plan A first.
  9260. if (RTCBrowserType.usesUnifiedPlan()) {
  9261. description = this.interop.toUnifiedPlan(description);
  9262. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  9263. }
  9264. if (RTCBrowserType.usesPlanB()) {
  9265. description = normalizePlanB(description);
  9266. }
  9267. var self = this;
  9268. this.peerconnection.setRemoteDescription(description,
  9269. function () {
  9270. self.trace('setRemoteDescriptionOnSuccess');
  9271. successCallback();
  9272. },
  9273. function (err) {
  9274. self.trace('setRemoteDescriptionOnFailure', err);
  9275. failureCallback(err);
  9276. }
  9277. );
  9278. /*
  9279. if (this.statsinterval === null && this.maxstats > 0) {
  9280. // start gathering stats
  9281. }
  9282. */
  9283. };
  9284. TraceablePeerConnection.prototype.close = function () {
  9285. this.trace('stop');
  9286. if (this.statsinterval !== null) {
  9287. window.clearInterval(this.statsinterval);
  9288. this.statsinterval = null;
  9289. }
  9290. this.peerconnection.close();
  9291. };
  9292. TraceablePeerConnection.prototype.createOffer
  9293. = function (successCallback, failureCallback, constraints) {
  9294. var self = this;
  9295. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  9296. this.peerconnection.createOffer(
  9297. function (offer) {
  9298. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  9299. // NOTE this is not tested because in meet the focus generates the
  9300. // offer.
  9301. // if we're running on FF, transform to Plan B first.
  9302. if (RTCBrowserType.usesUnifiedPlan()) {
  9303. offer = self.interop.toPlanB(offer);
  9304. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  9305. }
  9306. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  9307. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  9308. offer = self.simulcast.mungeLocalDescription(offer);
  9309. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  9310. }
  9311. successCallback(offer);
  9312. },
  9313. function(err) {
  9314. self.trace('createOfferOnFailure', err);
  9315. failureCallback(err);
  9316. },
  9317. constraints
  9318. );
  9319. };
  9320. TraceablePeerConnection.prototype.createAnswer
  9321. = function (successCallback, failureCallback, constraints) {
  9322. var self = this;
  9323. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  9324. this.peerconnection.createAnswer(
  9325. function (answer) {
  9326. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  9327. // if we're running on FF, transform to Plan A first.
  9328. if (RTCBrowserType.usesUnifiedPlan()) {
  9329. answer = self.interop.toPlanB(answer);
  9330. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  9331. }
  9332. // munge local video SSRC
  9333. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  9334. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  9335. answer = self.simulcast.mungeLocalDescription(answer);
  9336. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  9337. }
  9338. successCallback(answer);
  9339. },
  9340. function(err) {
  9341. self.trace('createAnswerOnFailure', err);
  9342. failureCallback(err);
  9343. },
  9344. constraints
  9345. );
  9346. };
  9347. TraceablePeerConnection.prototype.addIceCandidate
  9348. = function (candidate, successCallback, failureCallback) {
  9349. //var self = this;
  9350. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  9351. this.peerconnection.addIceCandidate(candidate);
  9352. /* maybe later
  9353. this.peerconnection.addIceCandidate(candidate,
  9354. function () {
  9355. self.trace('addIceCandidateOnSuccess');
  9356. successCallback();
  9357. },
  9358. function (err) {
  9359. self.trace('addIceCandidateOnFailure', err);
  9360. failureCallback(err);
  9361. }
  9362. );
  9363. */
  9364. };
  9365. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  9366. // TODO: Is this the correct way to handle Opera, Temasys?
  9367. if (RTCBrowserType.isFirefox()) {
  9368. // ignore for now...
  9369. if(!errback)
  9370. errback = function () {};
  9371. this.peerconnection.getStats(null, callback, errback);
  9372. } else {
  9373. this.peerconnection.getStats(callback);
  9374. }
  9375. };
  9376. module.exports = TraceablePeerConnection;
  9377. }).call(this,"/modules/xmpp/TraceablePeerConnection.js")
  9378. },{"../../service/xmpp/XMPPEvents":87,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"./LocalSSRCReplacement":29,"jitsi-meet-logger":48,"sdp-interop":66,"sdp-simulcast":69,"sdp-transform":76}],34:[function(require,module,exports){
  9379. (function (__filename){
  9380. /* global $, $iq, Promise, Strophe */
  9381. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9382. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9383. var Settings = require("../settings/Settings");
  9384. var AuthenticationEvents
  9385. = require("../../service/authentication/AuthenticationEvents");
  9386. function createExpBackoffTimer(step) {
  9387. var count = 1;
  9388. return function (reset) {
  9389. // Reset call
  9390. if (reset) {
  9391. count = 1;
  9392. return;
  9393. }
  9394. // Calculate next timeout
  9395. var timeout = Math.pow(2, count - 1);
  9396. count += 1;
  9397. return timeout * step;
  9398. };
  9399. }
  9400. function Moderator(roomName, xmpp, emitter) {
  9401. this.roomName = roomName;
  9402. this.xmppService = xmpp;
  9403. this.getNextTimeout = createExpBackoffTimer(1000);
  9404. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  9405. // External authentication stuff
  9406. this.externalAuthEnabled = false;
  9407. this.settings = new Settings(roomName);
  9408. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  9409. // it will be enabled automatically if focus detects the component through
  9410. // service discovery.
  9411. this.sipGatewayEnabled =
  9412. this.xmppService.options.hosts.call_control !== undefined;
  9413. this.eventEmitter = emitter;
  9414. this.connection = this.xmppService.connection;
  9415. this.focusUserJid;
  9416. //FIXME:
  9417. // Message listener that talks to POPUP window
  9418. function listener(event) {
  9419. if (event.data && event.data.sessionId) {
  9420. if (event.origin !== window.location.origin) {
  9421. logger.warn("Ignoring sessionId from different origin: " +
  9422. event.origin);
  9423. return;
  9424. }
  9425. localStorage.setItem('sessionId', event.data.sessionId);
  9426. // After popup is closed we will authenticate
  9427. }
  9428. }
  9429. // Register
  9430. if (window.addEventListener) {
  9431. window.addEventListener("message", listener, false);
  9432. } else {
  9433. window.attachEvent("onmessage", listener);
  9434. }
  9435. }
  9436. Moderator.prototype.isExternalAuthEnabled = function () {
  9437. return this.externalAuthEnabled;
  9438. };
  9439. Moderator.prototype.isSipGatewayEnabled = function () {
  9440. return this.sipGatewayEnabled;
  9441. };
  9442. Moderator.prototype.onMucMemberLeft = function (jid) {
  9443. logger.info("Someone left is it focus ? " + jid);
  9444. var resource = Strophe.getResourceFromJid(jid);
  9445. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  9446. logger.info(
  9447. "Focus has left the room - leaving conference");
  9448. //hangUp();
  9449. // We'd rather reload to have everything re-initialized
  9450. //FIXME: show some message before reload
  9451. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  9452. }
  9453. };
  9454. Moderator.prototype.setFocusUserJid = function (focusJid) {
  9455. if (!this.focusUserJid) {
  9456. this.focusUserJid = focusJid;
  9457. logger.info("Focus jid set to: " + this.focusUserJid);
  9458. }
  9459. };
  9460. Moderator.prototype.getFocusUserJid = function () {
  9461. return this.focusUserJid;
  9462. };
  9463. Moderator.prototype.getFocusComponent = function () {
  9464. // Get focus component address
  9465. var focusComponent = this.xmppService.options.hosts.focus;
  9466. // If not specified use default: 'focus.domain'
  9467. if (!focusComponent) {
  9468. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  9469. }
  9470. return focusComponent;
  9471. };
  9472. Moderator.prototype.createConferenceIq = function () {
  9473. // Generate create conference IQ
  9474. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  9475. // Session Id used for authentication
  9476. var sessionId = localStorage.getItem('sessionId');
  9477. var machineUID = this.settings.getSettings().uid;
  9478. logger.info(
  9479. "Session ID: " + sessionId + " machine UID: " + machineUID);
  9480. elem.c('conference', {
  9481. xmlns: 'http://jitsi.org/protocol/focus',
  9482. room: this.roomName,
  9483. 'machine-uid': machineUID
  9484. });
  9485. if (sessionId) {
  9486. elem.attrs({ 'session-id': sessionId});
  9487. }
  9488. if (this.xmppService.options.hosts.bridge !== undefined) {
  9489. elem.c(
  9490. 'property', {
  9491. name: 'bridge',
  9492. value: this.xmppService.options.hosts.bridge
  9493. }).up();
  9494. }
  9495. if (this.xmppService.options.enforcedBridge !== undefined) {
  9496. elem.c(
  9497. 'property', {
  9498. name: 'enforcedBridge',
  9499. value: this.xmppService.options.enforcedBridge
  9500. }).up();
  9501. }
  9502. // Tell the focus we have Jigasi configured
  9503. if (this.xmppService.options.hosts.call_control !== undefined) {
  9504. elem.c(
  9505. 'property', {
  9506. name: 'call_control',
  9507. value: this.xmppService.options.hosts.call_control
  9508. }).up();
  9509. }
  9510. if (this.xmppService.options.channelLastN !== undefined) {
  9511. elem.c(
  9512. 'property', {
  9513. name: 'channelLastN',
  9514. value: this.xmppService.options.channelLastN
  9515. }).up();
  9516. }
  9517. if (this.xmppService.options.adaptiveLastN !== undefined) {
  9518. elem.c(
  9519. 'property', {
  9520. name: 'adaptiveLastN',
  9521. value: this.xmppService.options.adaptiveLastN
  9522. }).up();
  9523. }
  9524. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  9525. elem.c(
  9526. 'property', {
  9527. name: 'adaptiveSimulcast',
  9528. value: this.xmppService.options.adaptiveSimulcast
  9529. }).up();
  9530. }
  9531. if (this.xmppService.options.openSctp !== undefined) {
  9532. elem.c(
  9533. 'property', {
  9534. name: 'openSctp',
  9535. value: this.xmppService.options.openSctp
  9536. }).up();
  9537. }
  9538. if (this.xmppService.options.startAudioMuted !== undefined)
  9539. {
  9540. elem.c(
  9541. 'property', {
  9542. name: 'startAudioMuted',
  9543. value: this.xmppService.options.startAudioMuted
  9544. }).up();
  9545. }
  9546. if (this.xmppService.options.startVideoMuted !== undefined)
  9547. {
  9548. elem.c(
  9549. 'property', {
  9550. name: 'startVideoMuted',
  9551. value: this.xmppService.options.startVideoMuted
  9552. }).up();
  9553. }
  9554. elem.c(
  9555. 'property', {
  9556. name: 'simulcastMode',
  9557. value: 'rewriting'
  9558. }).up();
  9559. elem.up();
  9560. return elem;
  9561. };
  9562. Moderator.prototype.parseSessionId = function (resultIq) {
  9563. var sessionId = $(resultIq).find('conference').attr('session-id');
  9564. if (sessionId) {
  9565. logger.info('Received sessionId: ' + sessionId);
  9566. localStorage.setItem('sessionId', sessionId);
  9567. }
  9568. };
  9569. Moderator.prototype.parseConfigOptions = function (resultIq) {
  9570. this.setFocusUserJid(
  9571. $(resultIq).find('conference').attr('focusjid'));
  9572. var authenticationEnabled
  9573. = $(resultIq).find(
  9574. '>conference>property' +
  9575. '[name=\'authentication\'][value=\'true\']').length > 0;
  9576. logger.info("Authentication enabled: " + authenticationEnabled);
  9577. this.externalAuthEnabled = $(resultIq).find(
  9578. '>conference>property' +
  9579. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  9580. console.info(
  9581. 'External authentication enabled: ' + this.externalAuthEnabled);
  9582. if (!this.externalAuthEnabled) {
  9583. // We expect to receive sessionId in 'internal' authentication mode
  9584. this.parseSessionId(resultIq);
  9585. }
  9586. var authIdentity = $(resultIq).find('>conference').attr('identity');
  9587. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  9588. authenticationEnabled, authIdentity);
  9589. // Check if focus has auto-detected Jigasi component(this will be also
  9590. // included if we have passed our host from the config)
  9591. if ($(resultIq).find(
  9592. '>conference>property' +
  9593. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  9594. this.sipGatewayEnabled = true;
  9595. }
  9596. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  9597. };
  9598. // FIXME = we need to show the fact that we're waiting for the focus
  9599. // to the user(or that focus is not available)
  9600. Moderator.prototype.allocateConferenceFocus = function (callback) {
  9601. // Try to use focus user JID from the config
  9602. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  9603. // Send create conference IQ
  9604. var iq = this.createConferenceIq();
  9605. var self = this;
  9606. this.connection.sendIQ(
  9607. iq,
  9608. function (result) {
  9609. // Setup config options
  9610. self.parseConfigOptions(result);
  9611. if ('true' === $(result).find('conference').attr('ready')) {
  9612. // Reset both timers
  9613. self.getNextTimeout(true);
  9614. self.getNextErrorTimeout(true);
  9615. // Exec callback
  9616. callback();
  9617. } else {
  9618. var waitMs = self.getNextTimeout();
  9619. logger.info("Waiting for the focus... " + waitMs);
  9620. // Reset error timeout
  9621. self.getNextErrorTimeout(true);
  9622. window.setTimeout(
  9623. function () {
  9624. self.allocateConferenceFocus(callback);
  9625. }, waitMs);
  9626. }
  9627. },
  9628. function (error) {
  9629. // Invalid session ? remove and try again
  9630. // without session ID to get a new one
  9631. var invalidSession
  9632. = $(error).find('>error>session-invalid').length;
  9633. if (invalidSession) {
  9634. logger.info("Session expired! - removing");
  9635. localStorage.removeItem("sessionId");
  9636. }
  9637. if ($(error).find('>error>graceful-shutdown').length) {
  9638. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  9639. return;
  9640. }
  9641. // Check for error returned by the reservation system
  9642. var reservationErr = $(error).find('>error>reservation-error');
  9643. if (reservationErr.length) {
  9644. // Trigger error event
  9645. var errorCode = reservationErr.attr('error-code');
  9646. var errorMsg;
  9647. if ($(error).find('>error>text')) {
  9648. errorMsg = $(error).find('>error>text').text();
  9649. }
  9650. self.eventEmitter.emit(
  9651. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  9652. return;
  9653. }
  9654. // Not authorized to create new room
  9655. if ($(error).find('>error>not-authorized').length) {
  9656. logger.warn("Unauthorized to start the conference", error);
  9657. var toDomain
  9658. = Strophe.getDomainFromJid(error.getAttribute('to'));
  9659. if (toDomain !==
  9660. this.xmppService.options.hosts.anonymousdomain) {
  9661. //FIXME: "is external" should come either from
  9662. // the focus or config.js
  9663. self.externalAuthEnabled = true;
  9664. }
  9665. self.eventEmitter.emit(
  9666. XMPPEvents.AUTHENTICATION_REQUIRED,
  9667. function () {
  9668. self.allocateConferenceFocus(
  9669. callback);
  9670. });
  9671. return;
  9672. }
  9673. var waitMs = self.getNextErrorTimeout();
  9674. logger.error("Focus error, retry after " + waitMs, error);
  9675. // Show message
  9676. var focusComponent = self.getFocusComponent();
  9677. var retrySec = waitMs / 1000;
  9678. //FIXME: message is duplicated ?
  9679. // Do not show in case of session invalid
  9680. // which means just a retry
  9681. if (!invalidSession) {
  9682. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  9683. focusComponent, retrySec);
  9684. }
  9685. // Reset response timeout
  9686. self.getNextTimeout(true);
  9687. window.setTimeout(
  9688. function () {
  9689. self.allocateConferenceFocus(callback);
  9690. }, waitMs);
  9691. }
  9692. );
  9693. };
  9694. Moderator.prototype.authenticate = function () {
  9695. var self = this;
  9696. return new Promise(function (resolve, reject) {
  9697. self.connection.sendIQ(
  9698. self.createConferenceIq(),
  9699. function (result) {
  9700. self.parseSessionId(result);
  9701. resolve();
  9702. }, function (error) {
  9703. var code = $(error).find('>error').attr('code');
  9704. reject(error, code);
  9705. }
  9706. );
  9707. });
  9708. };
  9709. Moderator.prototype.getLoginUrl = function (urlCallback, failureCallback) {
  9710. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9711. iq.c('login-url', {
  9712. xmlns: 'http://jitsi.org/protocol/focus',
  9713. room: this.roomName,
  9714. 'machine-uid': this.settings.getSettings().uid
  9715. });
  9716. this.connection.sendIQ(
  9717. iq,
  9718. function (result) {
  9719. var url = $(result).find('login-url').attr('url');
  9720. url = url = decodeURIComponent(url);
  9721. if (url) {
  9722. logger.info("Got auth url: " + url);
  9723. urlCallback(url);
  9724. } else {
  9725. logger.error(
  9726. "Failed to get auth url from the focus", result);
  9727. failureCallback(result);
  9728. }
  9729. },
  9730. function (error) {
  9731. logger.error("Get auth url error", error);
  9732. failureCallback(error);
  9733. }
  9734. );
  9735. };
  9736. Moderator.prototype.getPopupLoginUrl = function (urlCallback, failureCallback) {
  9737. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9738. iq.c('login-url', {
  9739. xmlns: 'http://jitsi.org/protocol/focus',
  9740. room: this.roomName,
  9741. 'machine-uid': this.settings.getSettings().uid,
  9742. popup: true
  9743. });
  9744. this.connection.sendIQ(
  9745. iq,
  9746. function (result) {
  9747. var url = $(result).find('login-url').attr('url');
  9748. url = url = decodeURIComponent(url);
  9749. if (url) {
  9750. logger.info("Got POPUP auth url: " + url);
  9751. urlCallback(url);
  9752. } else {
  9753. logger.error(
  9754. "Failed to get POPUP auth url from the focus", result);
  9755. failureCallback(result);
  9756. }
  9757. },
  9758. function (error) {
  9759. logger.error('Get POPUP auth url error', error);
  9760. failureCallback(error);
  9761. }
  9762. );
  9763. };
  9764. Moderator.prototype.logout = function (callback) {
  9765. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  9766. var sessionId = localStorage.getItem('sessionId');
  9767. if (!sessionId) {
  9768. callback();
  9769. return;
  9770. }
  9771. iq.c('logout', {
  9772. xmlns: 'http://jitsi.org/protocol/focus',
  9773. 'session-id': sessionId
  9774. });
  9775. this.connection.sendIQ(
  9776. iq,
  9777. function (result) {
  9778. var logoutUrl = $(result).find('logout').attr('logout-url');
  9779. if (logoutUrl) {
  9780. logoutUrl = decodeURIComponent(logoutUrl);
  9781. }
  9782. logger.info("Log out OK, url: " + logoutUrl, result);
  9783. localStorage.removeItem('sessionId');
  9784. callback(logoutUrl);
  9785. },
  9786. function (error) {
  9787. logger.error("Logout error", error);
  9788. }
  9789. );
  9790. };
  9791. module.exports = Moderator;
  9792. }).call(this,"/modules/xmpp/moderator.js")
  9793. },{"../../service/authentication/AuthenticationEvents":83,"../../service/xmpp/XMPPEvents":87,"../settings/Settings":21,"jitsi-meet-logger":48}],35:[function(require,module,exports){
  9794. (function (__filename){
  9795. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  9796. Toolbar, Util, Promise */
  9797. var XMPPEvents = require("../../service/XMPP/XMPPEvents");
  9798. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9799. function Recording(ee, connection, focusMucJid) {
  9800. this.eventEmitter = ee;
  9801. this.connection = connection;
  9802. this.state = "off";
  9803. this.focusMucJid = focusMucJid;
  9804. this.url = null;
  9805. this._isSupported = false;
  9806. }
  9807. Recording.prototype.handleJibriPresence = function (jibri) {
  9808. var attributes = jibri.attributes;
  9809. if(!attributes)
  9810. return;
  9811. this._isSupported =
  9812. (attributes.status && attributes.status !== "undefined");
  9813. if(this._isSupported) {
  9814. this.url = attributes.url || null;
  9815. this.state = attributes.status || "off";
  9816. }
  9817. this.eventEmitter.emit(XMPPEvents.RECORDING_STATE_CHANGED);
  9818. };
  9819. Recording.prototype.setRecording = function (state, streamId, followEntity,
  9820. callback, errCallback){
  9821. if (state == this.state){
  9822. return;
  9823. }
  9824. // FIXME jibri does not accept IQ without 'url' attribute set ?
  9825. var iq = $iq({to: this.focusMucJid, type: 'set'})
  9826. .c('jibri', {
  9827. "xmlns": 'http://jitsi.org/protocol/jibri',
  9828. "action": (state === 'on') ? 'start' : 'stop',
  9829. "streamid": streamId,
  9830. "follow-entity": followEntity
  9831. }).up();
  9832. logger.log('Set jibri recording: '+state, iq.nodeTree);
  9833. console.log(iq.nodeTree);
  9834. this.connection.sendIQ(
  9835. iq,
  9836. function (result) {
  9837. callback($(result).find('jibri').attr('state'),
  9838. $(result).find('jibri').attr('url'));
  9839. },
  9840. function (error) {
  9841. logger.log('Failed to start recording, error: ', error);
  9842. errCallback(error);
  9843. });
  9844. };
  9845. Recording.prototype.toggleRecording = function (token, followEntity) {
  9846. var self = this;
  9847. return new Promise(function(resolve, reject) {
  9848. if (!token) {
  9849. reject(new Error("No token passed!"));
  9850. logger.error("No token passed!");
  9851. return;
  9852. }
  9853. if(self.state === "on") {
  9854. reject(new Error("Recording is already started!"));
  9855. logger.error("Recording is already started!");
  9856. return;
  9857. }
  9858. var oldState = self.state;
  9859. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  9860. self.setRecording(newState,
  9861. token, followEntity,
  9862. function (state, url) {
  9863. logger.log("New recording state: ", state);
  9864. if (state && state !== oldState) {
  9865. self.state = state;
  9866. self.url = url;
  9867. resolve();
  9868. } else {
  9869. reject(new Error("State not changed!"));
  9870. }
  9871. },
  9872. function (error) {
  9873. reject(error);
  9874. }
  9875. );
  9876. });
  9877. };
  9878. /**
  9879. * Returns true if the recording is supproted and false if not.
  9880. */
  9881. Recording.prototype.isSupported = function () {
  9882. return this._isSupported;
  9883. };
  9884. /**
  9885. * Returns null if the recording is not supported, "on" if the recording started
  9886. * and "off" if the recording is not started.
  9887. */
  9888. Recording.prototype.getState = function () {
  9889. return this.state;
  9890. };
  9891. /**
  9892. * Returns the url of the recorded video.
  9893. */
  9894. Recording.prototype.getURL = function () {
  9895. return this.url;
  9896. };
  9897. module.exports = Recording;
  9898. }).call(this,"/modules/xmpp/recording.js")
  9899. },{"../../service/XMPP/XMPPEvents":82,"jitsi-meet-logger":48}],36:[function(require,module,exports){
  9900. (function (__filename){
  9901. /* jshint -W117 */
  9902. /* a simple MUC connection plugin
  9903. * can only handle a single MUC room
  9904. */
  9905. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9906. var ChatRoom = require("./ChatRoom");
  9907. module.exports = function(XMPP) {
  9908. Strophe.addConnectionPlugin('emuc', {
  9909. connection: null,
  9910. rooms: {},//map with the rooms
  9911. init: function (conn) {
  9912. this.connection = conn;
  9913. // add handlers (just once)
  9914. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, null, null);
  9915. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null);
  9916. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null);
  9917. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null);
  9918. },
  9919. createRoom: function (jid, password, options) {
  9920. var roomJid = Strophe.getBareJidFromJid(jid);
  9921. if (this.rooms[roomJid]) {
  9922. logger.error("You are already in the room!");
  9923. return;
  9924. }
  9925. this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, options);
  9926. return this.rooms[roomJid];
  9927. },
  9928. doLeave: function (jid) {
  9929. this.rooms[jid].doLeave();
  9930. delete this.rooms[jid];
  9931. },
  9932. onPresence: function (pres) {
  9933. var from = pres.getAttribute('from');
  9934. // What is this for? A workaround for something?
  9935. if (pres.getAttribute('type')) {
  9936. return true;
  9937. }
  9938. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9939. if(!room)
  9940. return;
  9941. // Parse status.
  9942. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  9943. room.createNonAnonymousRoom();
  9944. }
  9945. room.onPresence(pres);
  9946. return true;
  9947. },
  9948. onPresenceUnavailable: function (pres) {
  9949. var from = pres.getAttribute('from');
  9950. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9951. if(!room)
  9952. return;
  9953. room.onPresenceUnavailable(pres, from);
  9954. return true;
  9955. },
  9956. onPresenceError: function (pres) {
  9957. var from = pres.getAttribute('from');
  9958. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9959. if(!room)
  9960. return;
  9961. room.onPresenceError(pres, from);
  9962. return true;
  9963. },
  9964. onMessage: function (msg) {
  9965. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  9966. var from = msg.getAttribute('from');
  9967. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9968. if(!room)
  9969. return;
  9970. room.onMessage(msg, from);
  9971. return true;
  9972. },
  9973. setJingleSession: function (from, session) {
  9974. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9975. if(!room)
  9976. return;
  9977. room.setJingleSession(session);
  9978. }
  9979. });
  9980. };
  9981. }).call(this,"/modules/xmpp/strophe.emuc.js")
  9982. },{"./ChatRoom":26,"jitsi-meet-logger":48}],37:[function(require,module,exports){
  9983. (function (__filename){
  9984. /* jshint -W117 */
  9985. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9986. var JingleSession = require("./JingleSessionPC");
  9987. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9988. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9989. module.exports = function(XMPP, eventEmitter) {
  9990. Strophe.addConnectionPlugin('jingle', {
  9991. connection: null,
  9992. sessions: {},
  9993. jid2session: {},
  9994. ice_config: {iceServers: []},
  9995. media_constraints: {
  9996. mandatory: {
  9997. 'OfferToReceiveAudio': true,
  9998. 'OfferToReceiveVideo': true
  9999. }
  10000. // MozDontOfferDataChannel: true when this is firefox
  10001. },
  10002. init: function (conn) {
  10003. this.connection = conn;
  10004. if (this.connection.disco) {
  10005. // http://xmpp.org/extensions/xep-0167.html#support
  10006. // http://xmpp.org/extensions/xep-0176.html#support
  10007. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  10008. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  10009. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  10010. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  10011. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  10012. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  10013. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  10014. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  10015. || RTCBrowserType.isTemasysPluginUsed()) {
  10016. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  10017. }
  10018. // this is dealt with by SDP O/A so we don't need to announce this
  10019. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  10020. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  10021. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  10022. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  10023. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  10024. }
  10025. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  10026. },
  10027. onJingle: function (iq) {
  10028. var sid = $(iq).find('jingle').attr('sid');
  10029. var action = $(iq).find('jingle').attr('action');
  10030. var fromJid = iq.getAttribute('from');
  10031. // send ack first
  10032. var ack = $iq({type: 'result',
  10033. to: fromJid,
  10034. id: iq.getAttribute('id')
  10035. });
  10036. logger.log('on jingle ' + action + ' from ' + fromJid, iq);
  10037. var sess = this.sessions[sid];
  10038. if ('session-initiate' != action) {
  10039. if (sess === null) {
  10040. ack.type = 'error';
  10041. ack.c('error', {type: 'cancel'})
  10042. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  10043. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  10044. this.connection.send(ack);
  10045. return true;
  10046. }
  10047. // local jid is not checked
  10048. if (fromJid != sess.peerjid) {
  10049. logger.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  10050. ack.type = 'error';
  10051. ack.c('error', {type: 'cancel'})
  10052. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  10053. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  10054. this.connection.send(ack);
  10055. return true;
  10056. }
  10057. } else if (sess !== undefined) {
  10058. // existing session with same session id
  10059. // this might be out-of-order if the sess.peerjid is the same as from
  10060. ack.type = 'error';
  10061. ack.c('error', {type: 'cancel'})
  10062. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  10063. logger.warn('duplicate session id', sid);
  10064. this.connection.send(ack);
  10065. return true;
  10066. }
  10067. // FIXME: check for a defined action
  10068. this.connection.send(ack);
  10069. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  10070. switch (action) {
  10071. case 'session-initiate':
  10072. console.log("(TIME) received session-initiate:\t",
  10073. window.performance.now());
  10074. var startMuted = $(iq).find('jingle>startmuted');
  10075. if (startMuted && startMuted.length > 0) {
  10076. var audioMuted = startMuted.attr("audio");
  10077. var videoMuted = startMuted.attr("video");
  10078. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  10079. audioMuted === "true", videoMuted === "true");
  10080. }
  10081. sess = new JingleSession(
  10082. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  10083. this.connection, XMPP);
  10084. // configure session
  10085. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  10086. this.connection.emuc.setJingleSession(fromBareJid, sess);
  10087. sess.media_constraints = this.media_constraints;
  10088. sess.ice_config = this.ice_config;
  10089. sess.initialize(fromJid, false);
  10090. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  10091. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  10092. sess.setOffer($(iq).find('>jingle'));
  10093. this.sessions[sess.sid] = sess;
  10094. this.jid2session[sess.peerjid] = sess;
  10095. // the callback should either
  10096. // .sendAnswer and .accept
  10097. // or .sendTerminate -- not necessarily synchronous
  10098. sess.sendAnswer();
  10099. sess.accept();
  10100. break;
  10101. case 'session-accept':
  10102. sess.setAnswer($(iq).find('>jingle'));
  10103. sess.accept();
  10104. break;
  10105. case 'session-terminate':
  10106. // If this is not the focus sending the terminate, we have
  10107. // nothing more to do here.
  10108. if (Object.keys(this.sessions).length < 1
  10109. || !(this.sessions[Object.keys(this.sessions)[0]]
  10110. instanceof JingleSession))
  10111. {
  10112. break;
  10113. }
  10114. logger.log('terminating...', sess.sid);
  10115. sess.terminate();
  10116. this.terminate(sess.sid);
  10117. if ($(iq).find('>jingle>reason').length) {
  10118. $(document).trigger('callterminated.jingle', [
  10119. sess.sid,
  10120. sess.peerjid,
  10121. $(iq).find('>jingle>reason>:first')[0].tagName,
  10122. $(iq).find('>jingle>reason>text').text()
  10123. ]);
  10124. } else {
  10125. $(document).trigger('callterminated.jingle',
  10126. [sess.sid, sess.peerjid]);
  10127. }
  10128. break;
  10129. case 'transport-info':
  10130. sess.addIceCandidate($(iq).find('>jingle>content'));
  10131. break;
  10132. case 'session-info':
  10133. var affected;
  10134. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  10135. $(document).trigger('ringing.jingle', [sess.sid]);
  10136. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  10137. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  10138. $(document).trigger('mute.jingle', [sess.sid, affected]);
  10139. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  10140. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  10141. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  10142. }
  10143. break;
  10144. case 'addsource': // FIXME: proprietary, un-jingleish
  10145. case 'source-add': // FIXME: proprietary
  10146. sess.addSource($(iq).find('>jingle>content'));
  10147. break;
  10148. case 'removesource': // FIXME: proprietary, un-jingleish
  10149. case 'source-remove': // FIXME: proprietary
  10150. sess.removeSource($(iq).find('>jingle>content'));
  10151. break;
  10152. default:
  10153. logger.warn('jingle action not implemented', action);
  10154. break;
  10155. }
  10156. return true;
  10157. },
  10158. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  10159. if (sid === null || sid === undefined) {
  10160. for (sid in this.sessions) {
  10161. if (this.sessions[sid].state != 'ended') {
  10162. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  10163. this.sessions[sid].terminate();
  10164. }
  10165. delete this.jid2session[this.sessions[sid].peerjid];
  10166. delete this.sessions[sid];
  10167. }
  10168. } else if (this.sessions.hasOwnProperty(sid)) {
  10169. if (this.sessions[sid].state != 'ended') {
  10170. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  10171. this.sessions[sid].terminate();
  10172. }
  10173. delete this.jid2session[this.sessions[sid].peerjid];
  10174. delete this.sessions[sid];
  10175. }
  10176. },
  10177. getStunAndTurnCredentials: function () {
  10178. // get stun and turn configuration from server via xep-0215
  10179. // uses time-limited credentials as described in
  10180. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  10181. //
  10182. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  10183. // for a prosody module which implements this
  10184. //
  10185. // currently, this doesn't work with updateIce and therefore credentials with a long
  10186. // validity have to be fetched before creating the peerconnection
  10187. // TODO: implement refresh via updateIce as described in
  10188. // https://code.google.com/p/webrtc/issues/detail?id=1650
  10189. var self = this;
  10190. this.connection.sendIQ(
  10191. $iq({type: 'get', to: this.connection.domain})
  10192. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  10193. function (res) {
  10194. var iceservers = [];
  10195. $(res).find('>services>service').each(function (idx, el) {
  10196. el = $(el);
  10197. var dict = {};
  10198. var type = el.attr('type');
  10199. switch (type) {
  10200. case 'stun':
  10201. dict.url = 'stun:' + el.attr('host');
  10202. if (el.attr('port')) {
  10203. dict.url += ':' + el.attr('port');
  10204. }
  10205. iceservers.push(dict);
  10206. break;
  10207. case 'turn':
  10208. case 'turns':
  10209. dict.url = type + ':';
  10210. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  10211. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  10212. dict.url += el.attr('username') + '@';
  10213. } else {
  10214. dict.username = el.attr('username'); // only works in M28
  10215. }
  10216. }
  10217. dict.url += el.attr('host');
  10218. if (el.attr('port') && el.attr('port') != '3478') {
  10219. dict.url += ':' + el.attr('port');
  10220. }
  10221. if (el.attr('transport') && el.attr('transport') != 'udp') {
  10222. dict.url += '?transport=' + el.attr('transport');
  10223. }
  10224. if (el.attr('password')) {
  10225. dict.credential = el.attr('password');
  10226. }
  10227. iceservers.push(dict);
  10228. break;
  10229. }
  10230. });
  10231. self.ice_config.iceServers = iceservers;
  10232. },
  10233. function (err) {
  10234. logger.warn('getting turn credentials failed', err);
  10235. logger.warn('is mod_turncredentials or similar installed?');
  10236. }
  10237. );
  10238. // implement push?
  10239. },
  10240. /**
  10241. * Returns the data saved in 'updateLog' in a format to be logged.
  10242. */
  10243. getLog: function () {
  10244. var data = {};
  10245. var self = this;
  10246. Object.keys(this.sessions).forEach(function (sid) {
  10247. var session = self.sessions[sid];
  10248. if (session.peerconnection && session.peerconnection.updateLog) {
  10249. // FIXME: should probably be a .dump call
  10250. data["jingle_" + session.sid] = {
  10251. updateLog: session.peerconnection.updateLog,
  10252. stats: session.peerconnection.stats,
  10253. url: window.location.href
  10254. };
  10255. }
  10256. });
  10257. return data;
  10258. }
  10259. });
  10260. };
  10261. }).call(this,"/modules/xmpp/strophe.jingle.js")
  10262. },{"../../service/xmpp/XMPPEvents":87,"../RTC/RTCBrowserType":17,"./JingleSessionPC":28,"jitsi-meet-logger":48}],38:[function(require,module,exports){
  10263. /* global Strophe */
  10264. module.exports = function () {
  10265. Strophe.addConnectionPlugin('logger', {
  10266. // logs raw stanzas and makes them available for download as JSON
  10267. connection: null,
  10268. log: [],
  10269. init: function (conn) {
  10270. this.connection = conn;
  10271. this.connection.rawInput = this.log_incoming.bind(this);
  10272. this.connection.rawOutput = this.log_outgoing.bind(this);
  10273. },
  10274. log_incoming: function (stanza) {
  10275. this.log.push([new Date().getTime(), 'incoming', stanza]);
  10276. },
  10277. log_outgoing: function (stanza) {
  10278. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  10279. }
  10280. });
  10281. };
  10282. },{}],39:[function(require,module,exports){
  10283. (function (__filename){
  10284. /* global $, $iq, Strophe */
  10285. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10286. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10287. /**
  10288. * Ping every 20 sec
  10289. */
  10290. var PING_INTERVAL = 20000;
  10291. /**
  10292. * Ping timeout error after 15 sec of waiting.
  10293. */
  10294. var PING_TIMEOUT = 15000;
  10295. /**
  10296. * Will close the connection after 3 consecutive ping errors.
  10297. */
  10298. var PING_THRESHOLD = 3;
  10299. /**
  10300. * XEP-0199 ping plugin.
  10301. *
  10302. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  10303. */
  10304. module.exports = function (XMPP, eventEmitter) {
  10305. Strophe.addConnectionPlugin('ping', {
  10306. connection: null,
  10307. failedPings: 0,
  10308. /**
  10309. * Initializes the plugin. Method called by Strophe.
  10310. * @param connection Strophe connection instance.
  10311. */
  10312. init: function (connection) {
  10313. this.connection = connection;
  10314. Strophe.addNamespace('PING', "urn:xmpp:ping");
  10315. },
  10316. /**
  10317. * Sends "ping" to given <tt>jid</tt>
  10318. * @param jid the JID to which ping request will be sent.
  10319. * @param success callback called on success.
  10320. * @param error callback called on error.
  10321. * @param timeout ms how long are we going to wait for the response. On
  10322. * timeout <tt>error<//t> callback is called with undefined error
  10323. * argument.
  10324. */
  10325. ping: function (jid, success, error, timeout) {
  10326. var iq = $iq({type: 'get', to: jid});
  10327. iq.c('ping', {xmlns: Strophe.NS.PING});
  10328. this.connection.sendIQ(iq, success, error, timeout);
  10329. },
  10330. /**
  10331. * Checks if given <tt>jid</tt> has XEP-0199 ping support.
  10332. * @param jid the JID to be checked for ping support.
  10333. * @param callback function with boolean argument which will be
  10334. * <tt>true</tt> if XEP-0199 ping is supported by given <tt>jid</tt>
  10335. */
  10336. hasPingSupport: function (jid, callback) {
  10337. this.connection.disco.info(
  10338. jid, null,
  10339. function (result) {
  10340. var ping = $(result).find('>>feature[var="urn:xmpp:ping"]');
  10341. callback(ping.length > 0);
  10342. },
  10343. function (error) {
  10344. logger.error("Ping feature discovery error", error);
  10345. callback(false);
  10346. }
  10347. );
  10348. },
  10349. /**
  10350. * Starts to send ping in given interval to specified remote JID.
  10351. * This plugin supports only one such task and <tt>stopInterval</tt>
  10352. * must be called before starting a new one.
  10353. * @param remoteJid remote JID to which ping requests will be sent to.
  10354. * @param interval task interval in ms.
  10355. */
  10356. startInterval: function (remoteJid, interval) {
  10357. if (this.intervalId) {
  10358. logger.error("Ping task scheduled already");
  10359. return;
  10360. }
  10361. if (!interval)
  10362. interval = PING_INTERVAL;
  10363. var self = this;
  10364. this.intervalId = window.setInterval(function () {
  10365. self.ping(remoteJid,
  10366. function (result) {
  10367. // Ping OK
  10368. self.failedPings = 0;
  10369. },
  10370. function (error) {
  10371. self.failedPings += 1;
  10372. logger.error(
  10373. "Ping " + (error ? "error" : "timeout"), error);
  10374. if (self.failedPings >= PING_THRESHOLD) {
  10375. self.connection.disconnect();
  10376. }
  10377. }, PING_TIMEOUT);
  10378. }, interval);
  10379. logger.info("XMPP pings will be sent every " + interval + " ms");
  10380. },
  10381. /**
  10382. * Stops current "ping" interval task.
  10383. */
  10384. stopInterval: function () {
  10385. if (this.intervalId) {
  10386. window.clearInterval(this.intervalId);
  10387. this.intervalId = null;
  10388. this.failedPings = 0;
  10389. logger.info("Ping interval cleared");
  10390. }
  10391. }
  10392. });
  10393. };
  10394. }).call(this,"/modules/xmpp/strophe.ping.js")
  10395. },{"../../service/xmpp/XMPPEvents":87,"jitsi-meet-logger":48}],40:[function(require,module,exports){
  10396. (function (__filename){
  10397. /* jshint -W117 */
  10398. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10399. module.exports = function() {
  10400. Strophe.addConnectionPlugin('rayo',
  10401. {
  10402. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  10403. connection: null,
  10404. init: function (conn) {
  10405. this.connection = conn;
  10406. if (this.connection.disco) {
  10407. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  10408. }
  10409. this.connection.addHandler(
  10410. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set',
  10411. null, null);
  10412. },
  10413. onRayo: function (iq) {
  10414. logger.info("Rayo IQ", iq);
  10415. },
  10416. dial: function (to, from, roomName, roomPass, focusMucJid) {
  10417. var self = this;
  10418. return new Promise(function (resolve, reject) {
  10419. if(!focusMucJid) {
  10420. reject(new Error("Internal error!"));
  10421. return;
  10422. }
  10423. var req = $iq(
  10424. {
  10425. type: 'set',
  10426. to: focusMucJid
  10427. }
  10428. );
  10429. req.c('dial',
  10430. {
  10431. xmlns: self.RAYO_XMLNS,
  10432. to: to,
  10433. from: from
  10434. });
  10435. req.c('header',
  10436. {
  10437. name: 'JvbRoomName',
  10438. value: roomName
  10439. }).up();
  10440. if (roomPass !== null && roomPass.length) {
  10441. req.c('header',
  10442. {
  10443. name: 'JvbRoomPassword',
  10444. value: roomPass
  10445. }).up();
  10446. }
  10447. self.connection.sendIQ(
  10448. req,
  10449. function (result) {
  10450. logger.info('Dial result ', result);
  10451. var resource = $(result).find('ref').attr('uri');
  10452. self.call_resource =
  10453. resource.substr('xmpp:'.length);
  10454. logger.info(
  10455. "Received call resource: " +
  10456. self.call_resource);
  10457. resolve();
  10458. },
  10459. function (error) {
  10460. logger.info('Dial error ', error);
  10461. reject(error);
  10462. }
  10463. );
  10464. });
  10465. },
  10466. hangup: function () {
  10467. var self = this;
  10468. return new Promise(function (resolve, reject) {
  10469. if (!self.call_resource) {
  10470. reject(new Error("No call in progress"));
  10471. logger.warn("No call in progress");
  10472. return;
  10473. }
  10474. var req = $iq(
  10475. {
  10476. type: 'set',
  10477. to: self.call_resource
  10478. }
  10479. );
  10480. req.c('hangup',
  10481. {
  10482. xmlns: self.RAYO_XMLNS
  10483. });
  10484. self.connection.sendIQ(
  10485. req,
  10486. function (result) {
  10487. logger.info('Hangup result ', result);
  10488. self.call_resource = null;
  10489. resolve();
  10490. },
  10491. function (error) {
  10492. logger.info('Hangup error ', error);
  10493. self.call_resource = null;
  10494. reject(new Error('Hangup error '));
  10495. }
  10496. );
  10497. });
  10498. }
  10499. }
  10500. );
  10501. };
  10502. }).call(this,"/modules/xmpp/strophe.rayo.js")
  10503. },{"jitsi-meet-logger":48}],41:[function(require,module,exports){
  10504. (function (__filename){
  10505. /* global Strophe */
  10506. /**
  10507. * Strophe logger implementation. Logs from level WARN and above.
  10508. */
  10509. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10510. module.exports = function () {
  10511. Strophe.log = function (level, msg) {
  10512. switch (level) {
  10513. case Strophe.LogLevel.WARN:
  10514. logger.warn("Strophe: " + msg);
  10515. break;
  10516. case Strophe.LogLevel.ERROR:
  10517. case Strophe.LogLevel.FATAL:
  10518. logger.error("Strophe: " + msg);
  10519. break;
  10520. }
  10521. };
  10522. Strophe.getStatusString = function (status) {
  10523. switch (status) {
  10524. case Strophe.Status.ERROR:
  10525. return "ERROR";
  10526. case Strophe.Status.CONNECTING:
  10527. return "CONNECTING";
  10528. case Strophe.Status.CONNFAIL:
  10529. return "CONNFAIL";
  10530. case Strophe.Status.AUTHENTICATING:
  10531. return "AUTHENTICATING";
  10532. case Strophe.Status.AUTHFAIL:
  10533. return "AUTHFAIL";
  10534. case Strophe.Status.CONNECTED:
  10535. return "CONNECTED";
  10536. case Strophe.Status.DISCONNECTED:
  10537. return "DISCONNECTED";
  10538. case Strophe.Status.DISCONNECTING:
  10539. return "DISCONNECTING";
  10540. case Strophe.Status.ATTACHED:
  10541. return "ATTACHED";
  10542. default:
  10543. return "unknown";
  10544. }
  10545. };
  10546. };
  10547. }).call(this,"/modules/xmpp/strophe.util.js")
  10548. },{"jitsi-meet-logger":48}],42:[function(require,module,exports){
  10549. (function (__filename){
  10550. /* global $, APP, config, Strophe*/
  10551. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10552. var EventEmitter = require("events");
  10553. var Pako = require("pako");
  10554. var RTCEvents = require("../../service/RTC/RTCEvents");
  10555. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10556. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  10557. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  10558. var RTC = require("../RTC/RTC");
  10559. var authenticatedUser = false;
  10560. function createConnection(bosh) {
  10561. bosh = bosh || '/http-bind';
  10562. // Append token as URL param
  10563. if (this.token) {
  10564. bosh += bosh.indexOf('?') == -1 ?
  10565. '?token=' + this.token : '&token=' + this.token;
  10566. }
  10567. return new Strophe.Connection(bosh);
  10568. };
  10569. //!!!!!!!!!! FIXME: ...
  10570. function initStrophePlugins(XMPP)
  10571. {
  10572. require("./strophe.emuc")(XMPP);
  10573. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  10574. // require("./strophe.moderate")(XMPP, eventEmitter);
  10575. require("./strophe.util")();
  10576. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  10577. require("./strophe.rayo")();
  10578. require("./strophe.logger")();
  10579. }
  10580. //!!!!!!!!!! FIXME: ...
  10581. ///**
  10582. // * If given <tt>localStream</tt> is video one this method will advertise it's
  10583. // * video type in MUC presence.
  10584. // * @param localStream new or modified <tt>LocalStream</tt>.
  10585. // */
  10586. //function broadcastLocalVideoType(localStream) {
  10587. // if (localStream.videoType)
  10588. // XMPP.addToPresence('videoType', localStream.videoType);
  10589. //}
  10590. //
  10591. //function registerListeners() {
  10592. // RTC.addStreamListener(
  10593. // broadcastLocalVideoType,
  10594. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  10595. // );
  10596. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  10597. // XMPP.addToPresence("devices", devices);
  10598. // });
  10599. //}
  10600. function XMPP(options) {
  10601. this.eventEmitter = new EventEmitter();
  10602. this.connection = null;
  10603. this.disconnectInProgress = false;
  10604. this.forceMuted = false;
  10605. this.options = options;
  10606. initStrophePlugins(this);
  10607. // registerListeners();
  10608. this.connection = createConnection(options.bosh);
  10609. }
  10610. XMPP.prototype.getConnection = function(){ return connection; };
  10611. XMPP.prototype._connect = function (jid, password) {
  10612. var self = this;
  10613. // connection.connect() starts the connection process.
  10614. //
  10615. // As the connection process proceeds, the user supplied callback will
  10616. // be triggered multiple times with status updates. The callback should
  10617. // take two arguments - the status code and the error condition.
  10618. //
  10619. // The status code will be one of the values in the Strophe.Status
  10620. // constants. The error condition will be one of the conditions defined
  10621. // in RFC 3920 or the condition ‘strophe-parsererror’.
  10622. //
  10623. // The Parameters wait, hold and route are optional and only relevant
  10624. // for BOSH connections. Please see XEP 124 for a more detailed
  10625. // explanation of the optional parameters.
  10626. //
  10627. // Connection status constants for use by the connection handler
  10628. // callback.
  10629. //
  10630. // Status.ERROR - An error has occurred (websockets specific)
  10631. // Status.CONNECTING - The connection is currently being made
  10632. // Status.CONNFAIL - The connection attempt failed
  10633. // Status.AUTHENTICATING - The connection is authenticating
  10634. // Status.AUTHFAIL - The authentication attempt failed
  10635. // Status.CONNECTED - The connection has succeeded
  10636. // Status.DISCONNECTED - The connection has been terminated
  10637. // Status.DISCONNECTING - The connection is currently being terminated
  10638. // Status.ATTACHED - The connection has been attached
  10639. var anonymousConnectionFailed = false;
  10640. var connectionFailed = false;
  10641. var lastErrorMsg;
  10642. this.connection.connect(jid, password, function (status, msg) {
  10643. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  10644. (msg ? "[" + msg + "]" : "") + "\t:" + window.performance.now());
  10645. if (status === Strophe.Status.CONNECTED) {
  10646. if (self.options.useStunTurn) {
  10647. self.connection.jingle.getStunAndTurnCredentials();
  10648. }
  10649. logger.info("My Jabber ID: " + self.connection.jid);
  10650. // Schedule ping ?
  10651. var pingJid = self.connection.domain;
  10652. self.connection.ping.hasPingSupport(
  10653. pingJid,
  10654. function (hasPing) {
  10655. if (hasPing)
  10656. self.connection.ping.startInterval(pingJid);
  10657. else
  10658. logger.warn("Ping NOT supported by " + pingJid);
  10659. }
  10660. );
  10661. if (password)
  10662. authenticatedUser = true;
  10663. if (self.connection && self.connection.connected &&
  10664. Strophe.getResourceFromJid(self.connection.jid)) {
  10665. // .connected is true while connecting?
  10666. // self.connection.send($pres());
  10667. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  10668. Strophe.getResourceFromJid(self.connection.jid));
  10669. }
  10670. } else if (status === Strophe.Status.CONNFAIL) {
  10671. if (msg === 'x-strophe-bad-non-anon-jid') {
  10672. anonymousConnectionFailed = true;
  10673. }
  10674. else
  10675. {
  10676. connectionFailed = true;
  10677. }
  10678. lastErrorMsg = msg;
  10679. } else if (status === Strophe.Status.DISCONNECTED) {
  10680. // Stop ping interval
  10681. self.connection.ping.stopInterval();
  10682. self.disconnectInProgress = false;
  10683. if (anonymousConnectionFailed) {
  10684. // prompt user for username and password
  10685. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10686. JitsiConnectionErrors.PASSWORD_REQUIRED);
  10687. } else if(connectionFailed) {
  10688. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10689. JitsiConnectionErrors.OTHER_ERROR,
  10690. msg ? msg : lastErrorMsg);
  10691. } else {
  10692. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  10693. msg ? msg : lastErrorMsg);
  10694. }
  10695. } else if (status === Strophe.Status.AUTHFAIL) {
  10696. // wrong password or username, prompt user
  10697. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10698. JitsiConnectionErrors.PASSWORD_REQUIRED);
  10699. }
  10700. });
  10701. }
  10702. XMPP.prototype.connect = function (jid, password) {
  10703. if(!jid) {
  10704. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  10705. // Force authenticated domain if room is appended with '?login=true'
  10706. if (this.options.hosts.anonymousdomain &&
  10707. window.location.search.indexOf("login=true") !== -1) {
  10708. configDomain = this.options.hosts.domain;
  10709. }
  10710. jid = configDomain || window.location.hostname;
  10711. }
  10712. return this._connect(jid, password);
  10713. };
  10714. XMPP.prototype.createRoom = function (roomName, options) {
  10715. var roomjid = roomName + '@' + this.options.hosts.muc;
  10716. if (options.useNicks) {
  10717. if (options.nick) {
  10718. roomjid += '/' + options.nick;
  10719. } else {
  10720. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  10721. }
  10722. } else {
  10723. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  10724. if(!authenticatedUser)
  10725. tmpJid = tmpJid.substr(0, 8);
  10726. roomjid += '/' + tmpJid;
  10727. }
  10728. return this.connection.emuc.createRoom(roomjid, null, options);
  10729. }
  10730. XMPP.prototype.addListener = function(type, listener) {
  10731. this.eventEmitter.on(type, listener);
  10732. };
  10733. XMPP.prototype.removeListener = function (type, listener) {
  10734. this.eventEmitter.removeListener(type, listener);
  10735. };
  10736. //FIXME: this should work with the room
  10737. XMPP.prototype.leaveRoom = function (jid) {
  10738. var handler = this.connection.jingle.jid2session[jid];
  10739. if (handler && handler.peerconnection) {
  10740. // FIXME: probably removing streams is not required and close() should
  10741. // be enough
  10742. if (RTC.localAudio) {
  10743. handler.peerconnection.removeStream(
  10744. RTC.localAudio.getOriginalStream(), true);
  10745. }
  10746. if (RTC.localVideo) {
  10747. handler.peerconnection.removeStream(
  10748. RTC.localVideo.getOriginalStream(), true);
  10749. }
  10750. handler.peerconnection.close();
  10751. }
  10752. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  10753. this.connection.emuc.doLeave(jid);
  10754. };
  10755. /**
  10756. * Sends 'data' as a log message to the focus. Returns true iff a message
  10757. * was sent.
  10758. * @param data
  10759. * @returns {boolean} true iff a message was sent.
  10760. */
  10761. XMPP.prototype.sendLogs = function (data) {
  10762. if(!this.connection.emuc.focusMucJid)
  10763. return false;
  10764. var deflate = true;
  10765. var content = JSON.stringify(data);
  10766. if (deflate) {
  10767. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  10768. }
  10769. content = Base64.encode(content);
  10770. // XEP-0337-ish
  10771. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  10772. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  10773. id: 'PeerConnectionStats'});
  10774. message.c('message').t(content).up();
  10775. if (deflate) {
  10776. message.c('tag', {name: "deflated", value: "true"}).up();
  10777. }
  10778. message.up();
  10779. this.connection.send(message);
  10780. return true;
  10781. };
  10782. // Gets the logs from strophe.jingle.
  10783. XMPP.prototype.getJingleLog = function () {
  10784. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  10785. };
  10786. // Gets the logs from strophe.
  10787. XMPP.prototype.getXmppLog = function () {
  10788. return this.connection.logger ? this.connection.logger.log : null;
  10789. };
  10790. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  10791. this.connection.rayo.dial(to, from, roomName,roomPass);
  10792. };
  10793. XMPP.prototype.setMute = function (jid, mute) {
  10794. this.connection.moderate.setMute(jid, mute);
  10795. };
  10796. XMPP.prototype.eject = function (jid) {
  10797. this.connection.moderate.eject(jid);
  10798. };
  10799. XMPP.prototype.getSessions = function () {
  10800. return this.connection.jingle.sessions;
  10801. };
  10802. XMPP.prototype.disconnect = function () {
  10803. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  10804. {
  10805. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  10806. return;
  10807. }
  10808. this.disconnectInProgress = true;
  10809. this.connection.disconnect();
  10810. };
  10811. /**
  10812. * Gets the SSRC of local media stream.
  10813. * @param mediaType the media type that tells whether we want to get
  10814. * the SSRC of local audio or video stream.
  10815. * @returns {*} the SSRC number for local media stream or <tt>null</tt> if
  10816. * not available.
  10817. */
  10818. XMPP.prototype.getLocalSSRC = function (mediaType) {
  10819. if (this.connection.jingle.activecall &&
  10820. this.connection.jingle.activecall.peerconnection) {
  10821. return this.connection.jingle.activecall.getLocalSSRC(mediaType);
  10822. } else {
  10823. return null;
  10824. }
  10825. };
  10826. module.exports = XMPP;
  10827. }).call(this,"/modules/xmpp/xmpp.js")
  10828. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":80,"../../service/xmpp/XMPPEvents":87,"../RTC/RTC":16,"./strophe.emuc":36,"./strophe.jingle":37,"./strophe.logger":38,"./strophe.ping":39,"./strophe.rayo":40,"./strophe.util":41,"events":44,"jitsi-meet-logger":48,"pako":49}],43:[function(require,module,exports){
  10829. (function (process){
  10830. /*!
  10831. * async
  10832. * https://github.com/caolan/async
  10833. *
  10834. * Copyright 2010-2014 Caolan McMahon
  10835. * Released under the MIT license
  10836. */
  10837. /*jshint onevar: false, indent:4 */
  10838. /*global setImmediate: false, setTimeout: false, console: false */
  10839. (function () {
  10840. var async = {};
  10841. // global on the server, window in the browser
  10842. var root, previous_async;
  10843. root = this;
  10844. if (root != null) {
  10845. previous_async = root.async;
  10846. }
  10847. async.noConflict = function () {
  10848. root.async = previous_async;
  10849. return async;
  10850. };
  10851. function only_once(fn) {
  10852. var called = false;
  10853. return function() {
  10854. if (called) throw new Error("Callback was already called.");
  10855. called = true;
  10856. fn.apply(root, arguments);
  10857. }
  10858. }
  10859. //// cross-browser compatiblity functions ////
  10860. var _toString = Object.prototype.toString;
  10861. var _isArray = Array.isArray || function (obj) {
  10862. return _toString.call(obj) === '[object Array]';
  10863. };
  10864. var _each = function (arr, iterator) {
  10865. if (arr.forEach) {
  10866. return arr.forEach(iterator);
  10867. }
  10868. for (var i = 0; i < arr.length; i += 1) {
  10869. iterator(arr[i], i, arr);
  10870. }
  10871. };
  10872. var _map = function (arr, iterator) {
  10873. if (arr.map) {
  10874. return arr.map(iterator);
  10875. }
  10876. var results = [];
  10877. _each(arr, function (x, i, a) {
  10878. results.push(iterator(x, i, a));
  10879. });
  10880. return results;
  10881. };
  10882. var _reduce = function (arr, iterator, memo) {
  10883. if (arr.reduce) {
  10884. return arr.reduce(iterator, memo);
  10885. }
  10886. _each(arr, function (x, i, a) {
  10887. memo = iterator(memo, x, i, a);
  10888. });
  10889. return memo;
  10890. };
  10891. var _keys = function (obj) {
  10892. if (Object.keys) {
  10893. return Object.keys(obj);
  10894. }
  10895. var keys = [];
  10896. for (var k in obj) {
  10897. if (obj.hasOwnProperty(k)) {
  10898. keys.push(k);
  10899. }
  10900. }
  10901. return keys;
  10902. };
  10903. //// exported async module functions ////
  10904. //// nextTick implementation with browser-compatible fallback ////
  10905. if (typeof process === 'undefined' || !(process.nextTick)) {
  10906. if (typeof setImmediate === 'function') {
  10907. async.nextTick = function (fn) {
  10908. // not a direct alias for IE10 compatibility
  10909. setImmediate(fn);
  10910. };
  10911. async.setImmediate = async.nextTick;
  10912. }
  10913. else {
  10914. async.nextTick = function (fn) {
  10915. setTimeout(fn, 0);
  10916. };
  10917. async.setImmediate = async.nextTick;
  10918. }
  10919. }
  10920. else {
  10921. async.nextTick = process.nextTick;
  10922. if (typeof setImmediate !== 'undefined') {
  10923. async.setImmediate = function (fn) {
  10924. // not a direct alias for IE10 compatibility
  10925. setImmediate(fn);
  10926. };
  10927. }
  10928. else {
  10929. async.setImmediate = async.nextTick;
  10930. }
  10931. }
  10932. async.each = function (arr, iterator, callback) {
  10933. callback = callback || function () {};
  10934. if (!arr.length) {
  10935. return callback();
  10936. }
  10937. var completed = 0;
  10938. _each(arr, function (x) {
  10939. iterator(x, only_once(done) );
  10940. });
  10941. function done(err) {
  10942. if (err) {
  10943. callback(err);
  10944. callback = function () {};
  10945. }
  10946. else {
  10947. completed += 1;
  10948. if (completed >= arr.length) {
  10949. callback();
  10950. }
  10951. }
  10952. }
  10953. };
  10954. async.forEach = async.each;
  10955. async.eachSeries = function (arr, iterator, callback) {
  10956. callback = callback || function () {};
  10957. if (!arr.length) {
  10958. return callback();
  10959. }
  10960. var completed = 0;
  10961. var iterate = function () {
  10962. iterator(arr[completed], function (err) {
  10963. if (err) {
  10964. callback(err);
  10965. callback = function () {};
  10966. }
  10967. else {
  10968. completed += 1;
  10969. if (completed >= arr.length) {
  10970. callback();
  10971. }
  10972. else {
  10973. iterate();
  10974. }
  10975. }
  10976. });
  10977. };
  10978. iterate();
  10979. };
  10980. async.forEachSeries = async.eachSeries;
  10981. async.eachLimit = function (arr, limit, iterator, callback) {
  10982. var fn = _eachLimit(limit);
  10983. fn.apply(null, [arr, iterator, callback]);
  10984. };
  10985. async.forEachLimit = async.eachLimit;
  10986. var _eachLimit = function (limit) {
  10987. return function (arr, iterator, callback) {
  10988. callback = callback || function () {};
  10989. if (!arr.length || limit <= 0) {
  10990. return callback();
  10991. }
  10992. var completed = 0;
  10993. var started = 0;
  10994. var running = 0;
  10995. (function replenish () {
  10996. if (completed >= arr.length) {
  10997. return callback();
  10998. }
  10999. while (running < limit && started < arr.length) {
  11000. started += 1;
  11001. running += 1;
  11002. iterator(arr[started - 1], function (err) {
  11003. if (err) {
  11004. callback(err);
  11005. callback = function () {};
  11006. }
  11007. else {
  11008. completed += 1;
  11009. running -= 1;
  11010. if (completed >= arr.length) {
  11011. callback();
  11012. }
  11013. else {
  11014. replenish();
  11015. }
  11016. }
  11017. });
  11018. }
  11019. })();
  11020. };
  11021. };
  11022. var doParallel = function (fn) {
  11023. return function () {
  11024. var args = Array.prototype.slice.call(arguments);
  11025. return fn.apply(null, [async.each].concat(args));
  11026. };
  11027. };
  11028. var doParallelLimit = function(limit, fn) {
  11029. return function () {
  11030. var args = Array.prototype.slice.call(arguments);
  11031. return fn.apply(null, [_eachLimit(limit)].concat(args));
  11032. };
  11033. };
  11034. var doSeries = function (fn) {
  11035. return function () {
  11036. var args = Array.prototype.slice.call(arguments);
  11037. return fn.apply(null, [async.eachSeries].concat(args));
  11038. };
  11039. };
  11040. var _asyncMap = function (eachfn, arr, iterator, callback) {
  11041. arr = _map(arr, function (x, i) {
  11042. return {index: i, value: x};
  11043. });
  11044. if (!callback) {
  11045. eachfn(arr, function (x, callback) {
  11046. iterator(x.value, function (err) {
  11047. callback(err);
  11048. });
  11049. });
  11050. } else {
  11051. var results = [];
  11052. eachfn(arr, function (x, callback) {
  11053. iterator(x.value, function (err, v) {
  11054. results[x.index] = v;
  11055. callback(err);
  11056. });
  11057. }, function (err) {
  11058. callback(err, results);
  11059. });
  11060. }
  11061. };
  11062. async.map = doParallel(_asyncMap);
  11063. async.mapSeries = doSeries(_asyncMap);
  11064. async.mapLimit = function (arr, limit, iterator, callback) {
  11065. return _mapLimit(limit)(arr, iterator, callback);
  11066. };
  11067. var _mapLimit = function(limit) {
  11068. return doParallelLimit(limit, _asyncMap);
  11069. };
  11070. // reduce only has a series version, as doing reduce in parallel won't
  11071. // work in many situations.
  11072. async.reduce = function (arr, memo, iterator, callback) {
  11073. async.eachSeries(arr, function (x, callback) {
  11074. iterator(memo, x, function (err, v) {
  11075. memo = v;
  11076. callback(err);
  11077. });
  11078. }, function (err) {
  11079. callback(err, memo);
  11080. });
  11081. };
  11082. // inject alias
  11083. async.inject = async.reduce;
  11084. // foldl alias
  11085. async.foldl = async.reduce;
  11086. async.reduceRight = function (arr, memo, iterator, callback) {
  11087. var reversed = _map(arr, function (x) {
  11088. return x;
  11089. }).reverse();
  11090. async.reduce(reversed, memo, iterator, callback);
  11091. };
  11092. // foldr alias
  11093. async.foldr = async.reduceRight;
  11094. var _filter = function (eachfn, arr, iterator, callback) {
  11095. var results = [];
  11096. arr = _map(arr, function (x, i) {
  11097. return {index: i, value: x};
  11098. });
  11099. eachfn(arr, function (x, callback) {
  11100. iterator(x.value, function (v) {
  11101. if (v) {
  11102. results.push(x);
  11103. }
  11104. callback();
  11105. });
  11106. }, function (err) {
  11107. callback(_map(results.sort(function (a, b) {
  11108. return a.index - b.index;
  11109. }), function (x) {
  11110. return x.value;
  11111. }));
  11112. });
  11113. };
  11114. async.filter = doParallel(_filter);
  11115. async.filterSeries = doSeries(_filter);
  11116. // select alias
  11117. async.select = async.filter;
  11118. async.selectSeries = async.filterSeries;
  11119. var _reject = function (eachfn, arr, iterator, callback) {
  11120. var results = [];
  11121. arr = _map(arr, function (x, i) {
  11122. return {index: i, value: x};
  11123. });
  11124. eachfn(arr, function (x, callback) {
  11125. iterator(x.value, function (v) {
  11126. if (!v) {
  11127. results.push(x);
  11128. }
  11129. callback();
  11130. });
  11131. }, function (err) {
  11132. callback(_map(results.sort(function (a, b) {
  11133. return a.index - b.index;
  11134. }), function (x) {
  11135. return x.value;
  11136. }));
  11137. });
  11138. };
  11139. async.reject = doParallel(_reject);
  11140. async.rejectSeries = doSeries(_reject);
  11141. var _detect = function (eachfn, arr, iterator, main_callback) {
  11142. eachfn(arr, function (x, callback) {
  11143. iterator(x, function (result) {
  11144. if (result) {
  11145. main_callback(x);
  11146. main_callback = function () {};
  11147. }
  11148. else {
  11149. callback();
  11150. }
  11151. });
  11152. }, function (err) {
  11153. main_callback();
  11154. });
  11155. };
  11156. async.detect = doParallel(_detect);
  11157. async.detectSeries = doSeries(_detect);
  11158. async.some = function (arr, iterator, main_callback) {
  11159. async.each(arr, function (x, callback) {
  11160. iterator(x, function (v) {
  11161. if (v) {
  11162. main_callback(true);
  11163. main_callback = function () {};
  11164. }
  11165. callback();
  11166. });
  11167. }, function (err) {
  11168. main_callback(false);
  11169. });
  11170. };
  11171. // any alias
  11172. async.any = async.some;
  11173. async.every = function (arr, iterator, main_callback) {
  11174. async.each(arr, function (x, callback) {
  11175. iterator(x, function (v) {
  11176. if (!v) {
  11177. main_callback(false);
  11178. main_callback = function () {};
  11179. }
  11180. callback();
  11181. });
  11182. }, function (err) {
  11183. main_callback(true);
  11184. });
  11185. };
  11186. // all alias
  11187. async.all = async.every;
  11188. async.sortBy = function (arr, iterator, callback) {
  11189. async.map(arr, function (x, callback) {
  11190. iterator(x, function (err, criteria) {
  11191. if (err) {
  11192. callback(err);
  11193. }
  11194. else {
  11195. callback(null, {value: x, criteria: criteria});
  11196. }
  11197. });
  11198. }, function (err, results) {
  11199. if (err) {
  11200. return callback(err);
  11201. }
  11202. else {
  11203. var fn = function (left, right) {
  11204. var a = left.criteria, b = right.criteria;
  11205. return a < b ? -1 : a > b ? 1 : 0;
  11206. };
  11207. callback(null, _map(results.sort(fn), function (x) {
  11208. return x.value;
  11209. }));
  11210. }
  11211. });
  11212. };
  11213. async.auto = function (tasks, callback) {
  11214. callback = callback || function () {};
  11215. var keys = _keys(tasks);
  11216. var remainingTasks = keys.length
  11217. if (!remainingTasks) {
  11218. return callback();
  11219. }
  11220. var results = {};
  11221. var listeners = [];
  11222. var addListener = function (fn) {
  11223. listeners.unshift(fn);
  11224. };
  11225. var removeListener = function (fn) {
  11226. for (var i = 0; i < listeners.length; i += 1) {
  11227. if (listeners[i] === fn) {
  11228. listeners.splice(i, 1);
  11229. return;
  11230. }
  11231. }
  11232. };
  11233. var taskComplete = function () {
  11234. remainingTasks--
  11235. _each(listeners.slice(0), function (fn) {
  11236. fn();
  11237. });
  11238. };
  11239. addListener(function () {
  11240. if (!remainingTasks) {
  11241. var theCallback = callback;
  11242. // prevent final callback from calling itself if it errors
  11243. callback = function () {};
  11244. theCallback(null, results);
  11245. }
  11246. });
  11247. _each(keys, function (k) {
  11248. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  11249. var taskCallback = function (err) {
  11250. var args = Array.prototype.slice.call(arguments, 1);
  11251. if (args.length <= 1) {
  11252. args = args[0];
  11253. }
  11254. if (err) {
  11255. var safeResults = {};
  11256. _each(_keys(results), function(rkey) {
  11257. safeResults[rkey] = results[rkey];
  11258. });
  11259. safeResults[k] = args;
  11260. callback(err, safeResults);
  11261. // stop subsequent errors hitting callback multiple times
  11262. callback = function () {};
  11263. }
  11264. else {
  11265. results[k] = args;
  11266. async.setImmediate(taskComplete);
  11267. }
  11268. };
  11269. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  11270. var ready = function () {
  11271. return _reduce(requires, function (a, x) {
  11272. return (a && results.hasOwnProperty(x));
  11273. }, true) && !results.hasOwnProperty(k);
  11274. };
  11275. if (ready()) {
  11276. task[task.length - 1](taskCallback, results);
  11277. }
  11278. else {
  11279. var listener = function () {
  11280. if (ready()) {
  11281. removeListener(listener);
  11282. task[task.length - 1](taskCallback, results);
  11283. }
  11284. };
  11285. addListener(listener);
  11286. }
  11287. });
  11288. };
  11289. async.retry = function(times, task, callback) {
  11290. var DEFAULT_TIMES = 5;
  11291. var attempts = [];
  11292. // Use defaults if times not passed
  11293. if (typeof times === 'function') {
  11294. callback = task;
  11295. task = times;
  11296. times = DEFAULT_TIMES;
  11297. }
  11298. // Make sure times is a number
  11299. times = parseInt(times, 10) || DEFAULT_TIMES;
  11300. var wrappedTask = function(wrappedCallback, wrappedResults) {
  11301. var retryAttempt = function(task, finalAttempt) {
  11302. return function(seriesCallback) {
  11303. task(function(err, result){
  11304. seriesCallback(!err || finalAttempt, {err: err, result: result});
  11305. }, wrappedResults);
  11306. };
  11307. };
  11308. while (times) {
  11309. attempts.push(retryAttempt(task, !(times-=1)));
  11310. }
  11311. async.series(attempts, function(done, data){
  11312. data = data[data.length - 1];
  11313. (wrappedCallback || callback)(data.err, data.result);
  11314. });
  11315. }
  11316. // If a callback is passed, run this as a controll flow
  11317. return callback ? wrappedTask() : wrappedTask
  11318. };
  11319. async.waterfall = function (tasks, callback) {
  11320. callback = callback || function () {};
  11321. if (!_isArray(tasks)) {
  11322. var err = new Error('First argument to waterfall must be an array of functions');
  11323. return callback(err);
  11324. }
  11325. if (!tasks.length) {
  11326. return callback();
  11327. }
  11328. var wrapIterator = function (iterator) {
  11329. return function (err) {
  11330. if (err) {
  11331. callback.apply(null, arguments);
  11332. callback = function () {};
  11333. }
  11334. else {
  11335. var args = Array.prototype.slice.call(arguments, 1);
  11336. var next = iterator.next();
  11337. if (next) {
  11338. args.push(wrapIterator(next));
  11339. }
  11340. else {
  11341. args.push(callback);
  11342. }
  11343. async.setImmediate(function () {
  11344. iterator.apply(null, args);
  11345. });
  11346. }
  11347. };
  11348. };
  11349. wrapIterator(async.iterator(tasks))();
  11350. };
  11351. var _parallel = function(eachfn, tasks, callback) {
  11352. callback = callback || function () {};
  11353. if (_isArray(tasks)) {
  11354. eachfn.map(tasks, function (fn, callback) {
  11355. if (fn) {
  11356. fn(function (err) {
  11357. var args = Array.prototype.slice.call(arguments, 1);
  11358. if (args.length <= 1) {
  11359. args = args[0];
  11360. }
  11361. callback.call(null, err, args);
  11362. });
  11363. }
  11364. }, callback);
  11365. }
  11366. else {
  11367. var results = {};
  11368. eachfn.each(_keys(tasks), function (k, callback) {
  11369. tasks[k](function (err) {
  11370. var args = Array.prototype.slice.call(arguments, 1);
  11371. if (args.length <= 1) {
  11372. args = args[0];
  11373. }
  11374. results[k] = args;
  11375. callback(err);
  11376. });
  11377. }, function (err) {
  11378. callback(err, results);
  11379. });
  11380. }
  11381. };
  11382. async.parallel = function (tasks, callback) {
  11383. _parallel({ map: async.map, each: async.each }, tasks, callback);
  11384. };
  11385. async.parallelLimit = function(tasks, limit, callback) {
  11386. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  11387. };
  11388. async.series = function (tasks, callback) {
  11389. callback = callback || function () {};
  11390. if (_isArray(tasks)) {
  11391. async.mapSeries(tasks, function (fn, callback) {
  11392. if (fn) {
  11393. fn(function (err) {
  11394. var args = Array.prototype.slice.call(arguments, 1);
  11395. if (args.length <= 1) {
  11396. args = args[0];
  11397. }
  11398. callback.call(null, err, args);
  11399. });
  11400. }
  11401. }, callback);
  11402. }
  11403. else {
  11404. var results = {};
  11405. async.eachSeries(_keys(tasks), function (k, callback) {
  11406. tasks[k](function (err) {
  11407. var args = Array.prototype.slice.call(arguments, 1);
  11408. if (args.length <= 1) {
  11409. args = args[0];
  11410. }
  11411. results[k] = args;
  11412. callback(err);
  11413. });
  11414. }, function (err) {
  11415. callback(err, results);
  11416. });
  11417. }
  11418. };
  11419. async.iterator = function (tasks) {
  11420. var makeCallback = function (index) {
  11421. var fn = function () {
  11422. if (tasks.length) {
  11423. tasks[index].apply(null, arguments);
  11424. }
  11425. return fn.next();
  11426. };
  11427. fn.next = function () {
  11428. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  11429. };
  11430. return fn;
  11431. };
  11432. return makeCallback(0);
  11433. };
  11434. async.apply = function (fn) {
  11435. var args = Array.prototype.slice.call(arguments, 1);
  11436. return function () {
  11437. return fn.apply(
  11438. null, args.concat(Array.prototype.slice.call(arguments))
  11439. );
  11440. };
  11441. };
  11442. var _concat = function (eachfn, arr, fn, callback) {
  11443. var r = [];
  11444. eachfn(arr, function (x, cb) {
  11445. fn(x, function (err, y) {
  11446. r = r.concat(y || []);
  11447. cb(err);
  11448. });
  11449. }, function (err) {
  11450. callback(err, r);
  11451. });
  11452. };
  11453. async.concat = doParallel(_concat);
  11454. async.concatSeries = doSeries(_concat);
  11455. async.whilst = function (test, iterator, callback) {
  11456. if (test()) {
  11457. iterator(function (err) {
  11458. if (err) {
  11459. return callback(err);
  11460. }
  11461. async.whilst(test, iterator, callback);
  11462. });
  11463. }
  11464. else {
  11465. callback();
  11466. }
  11467. };
  11468. async.doWhilst = function (iterator, test, callback) {
  11469. iterator(function (err) {
  11470. if (err) {
  11471. return callback(err);
  11472. }
  11473. var args = Array.prototype.slice.call(arguments, 1);
  11474. if (test.apply(null, args)) {
  11475. async.doWhilst(iterator, test, callback);
  11476. }
  11477. else {
  11478. callback();
  11479. }
  11480. });
  11481. };
  11482. async.until = function (test, iterator, callback) {
  11483. if (!test()) {
  11484. iterator(function (err) {
  11485. if (err) {
  11486. return callback(err);
  11487. }
  11488. async.until(test, iterator, callback);
  11489. });
  11490. }
  11491. else {
  11492. callback();
  11493. }
  11494. };
  11495. async.doUntil = function (iterator, test, callback) {
  11496. iterator(function (err) {
  11497. if (err) {
  11498. return callback(err);
  11499. }
  11500. var args = Array.prototype.slice.call(arguments, 1);
  11501. if (!test.apply(null, args)) {
  11502. async.doUntil(iterator, test, callback);
  11503. }
  11504. else {
  11505. callback();
  11506. }
  11507. });
  11508. };
  11509. async.queue = function (worker, concurrency) {
  11510. if (concurrency === undefined) {
  11511. concurrency = 1;
  11512. }
  11513. function _insert(q, data, pos, callback) {
  11514. if (!q.started){
  11515. q.started = true;
  11516. }
  11517. if (!_isArray(data)) {
  11518. data = [data];
  11519. }
  11520. if(data.length == 0) {
  11521. // call drain immediately if there are no tasks
  11522. return async.setImmediate(function() {
  11523. if (q.drain) {
  11524. q.drain();
  11525. }
  11526. });
  11527. }
  11528. _each(data, function(task) {
  11529. var item = {
  11530. data: task,
  11531. callback: typeof callback === 'function' ? callback : null
  11532. };
  11533. if (pos) {
  11534. q.tasks.unshift(item);
  11535. } else {
  11536. q.tasks.push(item);
  11537. }
  11538. if (q.saturated && q.tasks.length === q.concurrency) {
  11539. q.saturated();
  11540. }
  11541. async.setImmediate(q.process);
  11542. });
  11543. }
  11544. var workers = 0;
  11545. var q = {
  11546. tasks: [],
  11547. concurrency: concurrency,
  11548. saturated: null,
  11549. empty: null,
  11550. drain: null,
  11551. started: false,
  11552. paused: false,
  11553. push: function (data, callback) {
  11554. _insert(q, data, false, callback);
  11555. },
  11556. kill: function () {
  11557. q.drain = null;
  11558. q.tasks = [];
  11559. },
  11560. unshift: function (data, callback) {
  11561. _insert(q, data, true, callback);
  11562. },
  11563. process: function () {
  11564. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  11565. var task = q.tasks.shift();
  11566. if (q.empty && q.tasks.length === 0) {
  11567. q.empty();
  11568. }
  11569. workers += 1;
  11570. var next = function () {
  11571. workers -= 1;
  11572. if (task.callback) {
  11573. task.callback.apply(task, arguments);
  11574. }
  11575. if (q.drain && q.tasks.length + workers === 0) {
  11576. q.drain();
  11577. }
  11578. q.process();
  11579. };
  11580. var cb = only_once(next);
  11581. worker(task.data, cb);
  11582. }
  11583. },
  11584. length: function () {
  11585. return q.tasks.length;
  11586. },
  11587. running: function () {
  11588. return workers;
  11589. },
  11590. idle: function() {
  11591. return q.tasks.length + workers === 0;
  11592. },
  11593. pause: function () {
  11594. if (q.paused === true) { return; }
  11595. q.paused = true;
  11596. q.process();
  11597. },
  11598. resume: function () {
  11599. if (q.paused === false) { return; }
  11600. q.paused = false;
  11601. q.process();
  11602. }
  11603. };
  11604. return q;
  11605. };
  11606. async.priorityQueue = function (worker, concurrency) {
  11607. function _compareTasks(a, b){
  11608. return a.priority - b.priority;
  11609. };
  11610. function _binarySearch(sequence, item, compare) {
  11611. var beg = -1,
  11612. end = sequence.length - 1;
  11613. while (beg < end) {
  11614. var mid = beg + ((end - beg + 1) >>> 1);
  11615. if (compare(item, sequence[mid]) >= 0) {
  11616. beg = mid;
  11617. } else {
  11618. end = mid - 1;
  11619. }
  11620. }
  11621. return beg;
  11622. }
  11623. function _insert(q, data, priority, callback) {
  11624. if (!q.started){
  11625. q.started = true;
  11626. }
  11627. if (!_isArray(data)) {
  11628. data = [data];
  11629. }
  11630. if(data.length == 0) {
  11631. // call drain immediately if there are no tasks
  11632. return async.setImmediate(function() {
  11633. if (q.drain) {
  11634. q.drain();
  11635. }
  11636. });
  11637. }
  11638. _each(data, function(task) {
  11639. var item = {
  11640. data: task,
  11641. priority: priority,
  11642. callback: typeof callback === 'function' ? callback : null
  11643. };
  11644. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  11645. if (q.saturated && q.tasks.length === q.concurrency) {
  11646. q.saturated();
  11647. }
  11648. async.setImmediate(q.process);
  11649. });
  11650. }
  11651. // Start with a normal queue
  11652. var q = async.queue(worker, concurrency);
  11653. // Override push to accept second parameter representing priority
  11654. q.push = function (data, priority, callback) {
  11655. _insert(q, data, priority, callback);
  11656. };
  11657. // Remove unshift function
  11658. delete q.unshift;
  11659. return q;
  11660. };
  11661. async.cargo = function (worker, payload) {
  11662. var working = false,
  11663. tasks = [];
  11664. var cargo = {
  11665. tasks: tasks,
  11666. payload: payload,
  11667. saturated: null,
  11668. empty: null,
  11669. drain: null,
  11670. drained: true,
  11671. push: function (data, callback) {
  11672. if (!_isArray(data)) {
  11673. data = [data];
  11674. }
  11675. _each(data, function(task) {
  11676. tasks.push({
  11677. data: task,
  11678. callback: typeof callback === 'function' ? callback : null
  11679. });
  11680. cargo.drained = false;
  11681. if (cargo.saturated && tasks.length === payload) {
  11682. cargo.saturated();
  11683. }
  11684. });
  11685. async.setImmediate(cargo.process);
  11686. },
  11687. process: function process() {
  11688. if (working) return;
  11689. if (tasks.length === 0) {
  11690. if(cargo.drain && !cargo.drained) cargo.drain();
  11691. cargo.drained = true;
  11692. return;
  11693. }
  11694. var ts = typeof payload === 'number'
  11695. ? tasks.splice(0, payload)
  11696. : tasks.splice(0, tasks.length);
  11697. var ds = _map(ts, function (task) {
  11698. return task.data;
  11699. });
  11700. if(cargo.empty) cargo.empty();
  11701. working = true;
  11702. worker(ds, function () {
  11703. working = false;
  11704. var args = arguments;
  11705. _each(ts, function (data) {
  11706. if (data.callback) {
  11707. data.callback.apply(null, args);
  11708. }
  11709. });
  11710. process();
  11711. });
  11712. },
  11713. length: function () {
  11714. return tasks.length;
  11715. },
  11716. running: function () {
  11717. return working;
  11718. }
  11719. };
  11720. return cargo;
  11721. };
  11722. var _console_fn = function (name) {
  11723. return function (fn) {
  11724. var args = Array.prototype.slice.call(arguments, 1);
  11725. fn.apply(null, args.concat([function (err) {
  11726. var args = Array.prototype.slice.call(arguments, 1);
  11727. if (typeof console !== 'undefined') {
  11728. if (err) {
  11729. if (console.error) {
  11730. console.error(err);
  11731. }
  11732. }
  11733. else if (console[name]) {
  11734. _each(args, function (x) {
  11735. console[name](x);
  11736. });
  11737. }
  11738. }
  11739. }]));
  11740. };
  11741. };
  11742. async.log = _console_fn('log');
  11743. async.dir = _console_fn('dir');
  11744. /*async.info = _console_fn('info');
  11745. async.warn = _console_fn('warn');
  11746. async.error = _console_fn('error');*/
  11747. async.memoize = function (fn, hasher) {
  11748. var memo = {};
  11749. var queues = {};
  11750. hasher = hasher || function (x) {
  11751. return x;
  11752. };
  11753. var memoized = function () {
  11754. var args = Array.prototype.slice.call(arguments);
  11755. var callback = args.pop();
  11756. var key = hasher.apply(null, args);
  11757. if (key in memo) {
  11758. async.nextTick(function () {
  11759. callback.apply(null, memo[key]);
  11760. });
  11761. }
  11762. else if (key in queues) {
  11763. queues[key].push(callback);
  11764. }
  11765. else {
  11766. queues[key] = [callback];
  11767. fn.apply(null, args.concat([function () {
  11768. memo[key] = arguments;
  11769. var q = queues[key];
  11770. delete queues[key];
  11771. for (var i = 0, l = q.length; i < l; i++) {
  11772. q[i].apply(null, arguments);
  11773. }
  11774. }]));
  11775. }
  11776. };
  11777. memoized.memo = memo;
  11778. memoized.unmemoized = fn;
  11779. return memoized;
  11780. };
  11781. async.unmemoize = function (fn) {
  11782. return function () {
  11783. return (fn.unmemoized || fn).apply(null, arguments);
  11784. };
  11785. };
  11786. async.times = function (count, iterator, callback) {
  11787. var counter = [];
  11788. for (var i = 0; i < count; i++) {
  11789. counter.push(i);
  11790. }
  11791. return async.map(counter, iterator, callback);
  11792. };
  11793. async.timesSeries = function (count, iterator, callback) {
  11794. var counter = [];
  11795. for (var i = 0; i < count; i++) {
  11796. counter.push(i);
  11797. }
  11798. return async.mapSeries(counter, iterator, callback);
  11799. };
  11800. async.seq = function (/* functions... */) {
  11801. var fns = arguments;
  11802. return function () {
  11803. var that = this;
  11804. var args = Array.prototype.slice.call(arguments);
  11805. var callback = args.pop();
  11806. async.reduce(fns, args, function (newargs, fn, cb) {
  11807. fn.apply(that, newargs.concat([function () {
  11808. var err = arguments[0];
  11809. var nextargs = Array.prototype.slice.call(arguments, 1);
  11810. cb(err, nextargs);
  11811. }]))
  11812. },
  11813. function (err, results) {
  11814. callback.apply(that, [err].concat(results));
  11815. });
  11816. };
  11817. };
  11818. async.compose = function (/* functions... */) {
  11819. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  11820. };
  11821. var _applyEach = function (eachfn, fns /*args...*/) {
  11822. var go = function () {
  11823. var that = this;
  11824. var args = Array.prototype.slice.call(arguments);
  11825. var callback = args.pop();
  11826. return eachfn(fns, function (fn, cb) {
  11827. fn.apply(that, args.concat([cb]));
  11828. },
  11829. callback);
  11830. };
  11831. if (arguments.length > 2) {
  11832. var args = Array.prototype.slice.call(arguments, 2);
  11833. return go.apply(this, args);
  11834. }
  11835. else {
  11836. return go;
  11837. }
  11838. };
  11839. async.applyEach = doParallel(_applyEach);
  11840. async.applyEachSeries = doSeries(_applyEach);
  11841. async.forever = function (fn, callback) {
  11842. function next(err) {
  11843. if (err) {
  11844. if (callback) {
  11845. return callback(err);
  11846. }
  11847. throw err;
  11848. }
  11849. fn(next);
  11850. }
  11851. next();
  11852. };
  11853. // Node.js
  11854. if (typeof module !== 'undefined' && module.exports) {
  11855. module.exports = async;
  11856. }
  11857. // AMD / RequireJS
  11858. else if (typeof define !== 'undefined' && define.amd) {
  11859. define([], function () {
  11860. return async;
  11861. });
  11862. }
  11863. // included directly via <script> tag
  11864. else {
  11865. root.async = async;
  11866. }
  11867. }());
  11868. }).call(this,require('_process'))
  11869. },{"_process":45}],44:[function(require,module,exports){
  11870. // Copyright Joyent, Inc. and other Node contributors.
  11871. //
  11872. // Permission is hereby granted, free of charge, to any person obtaining a
  11873. // copy of this software and associated documentation files (the
  11874. // "Software"), to deal in the Software without restriction, including
  11875. // without limitation the rights to use, copy, modify, merge, publish,
  11876. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11877. // persons to whom the Software is furnished to do so, subject to the
  11878. // following conditions:
  11879. //
  11880. // The above copyright notice and this permission notice shall be included
  11881. // in all copies or substantial portions of the Software.
  11882. //
  11883. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11884. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11885. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11886. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11887. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11888. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11889. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11890. function EventEmitter() {
  11891. this._events = this._events || {};
  11892. this._maxListeners = this._maxListeners || undefined;
  11893. }
  11894. module.exports = EventEmitter;
  11895. // Backwards-compat with node 0.10.x
  11896. EventEmitter.EventEmitter = EventEmitter;
  11897. EventEmitter.prototype._events = undefined;
  11898. EventEmitter.prototype._maxListeners = undefined;
  11899. // By default EventEmitters will print a warning if more than 10 listeners are
  11900. // added to it. This is a useful default which helps finding memory leaks.
  11901. EventEmitter.defaultMaxListeners = 10;
  11902. // Obviously not all Emitters should be limited to 10. This function allows
  11903. // that to be increased. Set to zero for unlimited.
  11904. EventEmitter.prototype.setMaxListeners = function(n) {
  11905. if (!isNumber(n) || n < 0 || isNaN(n))
  11906. throw TypeError('n must be a positive number');
  11907. this._maxListeners = n;
  11908. return this;
  11909. };
  11910. EventEmitter.prototype.emit = function(type) {
  11911. var er, handler, len, args, i, listeners;
  11912. if (!this._events)
  11913. this._events = {};
  11914. // If there is no 'error' event listener then throw.
  11915. if (type === 'error') {
  11916. if (!this._events.error ||
  11917. (isObject(this._events.error) && !this._events.error.length)) {
  11918. er = arguments[1];
  11919. if (er instanceof Error) {
  11920. throw er; // Unhandled 'error' event
  11921. }
  11922. throw TypeError('Uncaught, unspecified "error" event.');
  11923. }
  11924. }
  11925. handler = this._events[type];
  11926. if (isUndefined(handler))
  11927. return false;
  11928. if (isFunction(handler)) {
  11929. switch (arguments.length) {
  11930. // fast cases
  11931. case 1:
  11932. handler.call(this);
  11933. break;
  11934. case 2:
  11935. handler.call(this, arguments[1]);
  11936. break;
  11937. case 3:
  11938. handler.call(this, arguments[1], arguments[2]);
  11939. break;
  11940. // slower
  11941. default:
  11942. len = arguments.length;
  11943. args = new Array(len - 1);
  11944. for (i = 1; i < len; i++)
  11945. args[i - 1] = arguments[i];
  11946. handler.apply(this, args);
  11947. }
  11948. } else if (isObject(handler)) {
  11949. len = arguments.length;
  11950. args = new Array(len - 1);
  11951. for (i = 1; i < len; i++)
  11952. args[i - 1] = arguments[i];
  11953. listeners = handler.slice();
  11954. len = listeners.length;
  11955. for (i = 0; i < len; i++)
  11956. listeners[i].apply(this, args);
  11957. }
  11958. return true;
  11959. };
  11960. EventEmitter.prototype.addListener = function(type, listener) {
  11961. var m;
  11962. if (!isFunction(listener))
  11963. throw TypeError('listener must be a function');
  11964. if (!this._events)
  11965. this._events = {};
  11966. // To avoid recursion in the case that type === "newListener"! Before
  11967. // adding it to the listeners, first emit "newListener".
  11968. if (this._events.newListener)
  11969. this.emit('newListener', type,
  11970. isFunction(listener.listener) ?
  11971. listener.listener : listener);
  11972. if (!this._events[type])
  11973. // Optimize the case of one listener. Don't need the extra array object.
  11974. this._events[type] = listener;
  11975. else if (isObject(this._events[type]))
  11976. // If we've already got an array, just append.
  11977. this._events[type].push(listener);
  11978. else
  11979. // Adding the second element, need to change to array.
  11980. this._events[type] = [this._events[type], listener];
  11981. // Check for listener leak
  11982. if (isObject(this._events[type]) && !this._events[type].warned) {
  11983. var m;
  11984. if (!isUndefined(this._maxListeners)) {
  11985. m = this._maxListeners;
  11986. } else {
  11987. m = EventEmitter.defaultMaxListeners;
  11988. }
  11989. if (m && m > 0 && this._events[type].length > m) {
  11990. this._events[type].warned = true;
  11991. console.error('(node) warning: possible EventEmitter memory ' +
  11992. 'leak detected. %d listeners added. ' +
  11993. 'Use emitter.setMaxListeners() to increase limit.',
  11994. this._events[type].length);
  11995. if (typeof console.trace === 'function') {
  11996. // not supported in IE 10
  11997. console.trace();
  11998. }
  11999. }
  12000. }
  12001. return this;
  12002. };
  12003. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  12004. EventEmitter.prototype.once = function(type, listener) {
  12005. if (!isFunction(listener))
  12006. throw TypeError('listener must be a function');
  12007. var fired = false;
  12008. function g() {
  12009. this.removeListener(type, g);
  12010. if (!fired) {
  12011. fired = true;
  12012. listener.apply(this, arguments);
  12013. }
  12014. }
  12015. g.listener = listener;
  12016. this.on(type, g);
  12017. return this;
  12018. };
  12019. // emits a 'removeListener' event iff the listener was removed
  12020. EventEmitter.prototype.removeListener = function(type, listener) {
  12021. var list, position, length, i;
  12022. if (!isFunction(listener))
  12023. throw TypeError('listener must be a function');
  12024. if (!this._events || !this._events[type])
  12025. return this;
  12026. list = this._events[type];
  12027. length = list.length;
  12028. position = -1;
  12029. if (list === listener ||
  12030. (isFunction(list.listener) && list.listener === listener)) {
  12031. delete this._events[type];
  12032. if (this._events.removeListener)
  12033. this.emit('removeListener', type, listener);
  12034. } else if (isObject(list)) {
  12035. for (i = length; i-- > 0;) {
  12036. if (list[i] === listener ||
  12037. (list[i].listener && list[i].listener === listener)) {
  12038. position = i;
  12039. break;
  12040. }
  12041. }
  12042. if (position < 0)
  12043. return this;
  12044. if (list.length === 1) {
  12045. list.length = 0;
  12046. delete this._events[type];
  12047. } else {
  12048. list.splice(position, 1);
  12049. }
  12050. if (this._events.removeListener)
  12051. this.emit('removeListener', type, listener);
  12052. }
  12053. return this;
  12054. };
  12055. EventEmitter.prototype.removeAllListeners = function(type) {
  12056. var key, listeners;
  12057. if (!this._events)
  12058. return this;
  12059. // not listening for removeListener, no need to emit
  12060. if (!this._events.removeListener) {
  12061. if (arguments.length === 0)
  12062. this._events = {};
  12063. else if (this._events[type])
  12064. delete this._events[type];
  12065. return this;
  12066. }
  12067. // emit removeListener for all listeners on all events
  12068. if (arguments.length === 0) {
  12069. for (key in this._events) {
  12070. if (key === 'removeListener') continue;
  12071. this.removeAllListeners(key);
  12072. }
  12073. this.removeAllListeners('removeListener');
  12074. this._events = {};
  12075. return this;
  12076. }
  12077. listeners = this._events[type];
  12078. if (isFunction(listeners)) {
  12079. this.removeListener(type, listeners);
  12080. } else {
  12081. // LIFO order
  12082. while (listeners.length)
  12083. this.removeListener(type, listeners[listeners.length - 1]);
  12084. }
  12085. delete this._events[type];
  12086. return this;
  12087. };
  12088. EventEmitter.prototype.listeners = function(type) {
  12089. var ret;
  12090. if (!this._events || !this._events[type])
  12091. ret = [];
  12092. else if (isFunction(this._events[type]))
  12093. ret = [this._events[type]];
  12094. else
  12095. ret = this._events[type].slice();
  12096. return ret;
  12097. };
  12098. EventEmitter.listenerCount = function(emitter, type) {
  12099. var ret;
  12100. if (!emitter._events || !emitter._events[type])
  12101. ret = 0;
  12102. else if (isFunction(emitter._events[type]))
  12103. ret = 1;
  12104. else
  12105. ret = emitter._events[type].length;
  12106. return ret;
  12107. };
  12108. function isFunction(arg) {
  12109. return typeof arg === 'function';
  12110. }
  12111. function isNumber(arg) {
  12112. return typeof arg === 'number';
  12113. }
  12114. function isObject(arg) {
  12115. return typeof arg === 'object' && arg !== null;
  12116. }
  12117. function isUndefined(arg) {
  12118. return arg === void 0;
  12119. }
  12120. },{}],45:[function(require,module,exports){
  12121. // shim for using process in browser
  12122. var process = module.exports = {};
  12123. var queue = [];
  12124. var draining = false;
  12125. var currentQueue;
  12126. var queueIndex = -1;
  12127. function cleanUpNextTick() {
  12128. draining = false;
  12129. if (currentQueue.length) {
  12130. queue = currentQueue.concat(queue);
  12131. } else {
  12132. queueIndex = -1;
  12133. }
  12134. if (queue.length) {
  12135. drainQueue();
  12136. }
  12137. }
  12138. function drainQueue() {
  12139. if (draining) {
  12140. return;
  12141. }
  12142. var timeout = setTimeout(cleanUpNextTick);
  12143. draining = true;
  12144. var len = queue.length;
  12145. while(len) {
  12146. currentQueue = queue;
  12147. queue = [];
  12148. while (++queueIndex < len) {
  12149. if (currentQueue) {
  12150. currentQueue[queueIndex].run();
  12151. }
  12152. }
  12153. queueIndex = -1;
  12154. len = queue.length;
  12155. }
  12156. currentQueue = null;
  12157. draining = false;
  12158. clearTimeout(timeout);
  12159. }
  12160. process.nextTick = function (fun) {
  12161. var args = new Array(arguments.length - 1);
  12162. if (arguments.length > 1) {
  12163. for (var i = 1; i < arguments.length; i++) {
  12164. args[i - 1] = arguments[i];
  12165. }
  12166. }
  12167. queue.push(new Item(fun, args));
  12168. if (queue.length === 1 && !draining) {
  12169. setTimeout(drainQueue, 0);
  12170. }
  12171. };
  12172. // v8 likes predictible objects
  12173. function Item(fun, array) {
  12174. this.fun = fun;
  12175. this.array = array;
  12176. }
  12177. Item.prototype.run = function () {
  12178. this.fun.apply(null, this.array);
  12179. };
  12180. process.title = 'browser';
  12181. process.browser = true;
  12182. process.env = {};
  12183. process.argv = [];
  12184. process.version = ''; // empty string to avoid regexp issues
  12185. process.versions = {};
  12186. function noop() {}
  12187. process.on = noop;
  12188. process.addListener = noop;
  12189. process.once = noop;
  12190. process.off = noop;
  12191. process.removeListener = noop;
  12192. process.removeAllListeners = noop;
  12193. process.emit = noop;
  12194. process.binding = function (name) {
  12195. throw new Error('process.binding is not supported');
  12196. };
  12197. process.cwd = function () { return '/' };
  12198. process.chdir = function (dir) {
  12199. throw new Error('process.chdir is not supported');
  12200. };
  12201. process.umask = function() { return 0; };
  12202. },{}],46:[function(require,module,exports){
  12203. (function (process,global){
  12204. /*!
  12205. * @overview es6-promise - a tiny implementation of Promises/A+.
  12206. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  12207. * @license Licensed under MIT license
  12208. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  12209. * @version 3.0.2
  12210. */
  12211. (function() {
  12212. "use strict";
  12213. function lib$es6$promise$utils$$objectOrFunction(x) {
  12214. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  12215. }
  12216. function lib$es6$promise$utils$$isFunction(x) {
  12217. return typeof x === 'function';
  12218. }
  12219. function lib$es6$promise$utils$$isMaybeThenable(x) {
  12220. return typeof x === 'object' && x !== null;
  12221. }
  12222. var lib$es6$promise$utils$$_isArray;
  12223. if (!Array.isArray) {
  12224. lib$es6$promise$utils$$_isArray = function (x) {
  12225. return Object.prototype.toString.call(x) === '[object Array]';
  12226. };
  12227. } else {
  12228. lib$es6$promise$utils$$_isArray = Array.isArray;
  12229. }
  12230. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  12231. var lib$es6$promise$asap$$len = 0;
  12232. var lib$es6$promise$asap$$toString = {}.toString;
  12233. var lib$es6$promise$asap$$vertxNext;
  12234. var lib$es6$promise$asap$$customSchedulerFn;
  12235. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  12236. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  12237. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  12238. lib$es6$promise$asap$$len += 2;
  12239. if (lib$es6$promise$asap$$len === 2) {
  12240. // If len is 2, that means that we need to schedule an async flush.
  12241. // If additional callbacks are queued before the queue is flushed, they
  12242. // will be processed by this flush that we are scheduling.
  12243. if (lib$es6$promise$asap$$customSchedulerFn) {
  12244. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  12245. } else {
  12246. lib$es6$promise$asap$$scheduleFlush();
  12247. }
  12248. }
  12249. }
  12250. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  12251. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  12252. }
  12253. function lib$es6$promise$asap$$setAsap(asapFn) {
  12254. lib$es6$promise$asap$$asap = asapFn;
  12255. }
  12256. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  12257. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  12258. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  12259. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  12260. // test for web worker but not in IE10
  12261. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  12262. typeof importScripts !== 'undefined' &&
  12263. typeof MessageChannel !== 'undefined';
  12264. // node
  12265. function lib$es6$promise$asap$$useNextTick() {
  12266. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  12267. // see https://github.com/cujojs/when/issues/410 for details
  12268. return function() {
  12269. process.nextTick(lib$es6$promise$asap$$flush);
  12270. };
  12271. }
  12272. // vertx
  12273. function lib$es6$promise$asap$$useVertxTimer() {
  12274. return function() {
  12275. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  12276. };
  12277. }
  12278. function lib$es6$promise$asap$$useMutationObserver() {
  12279. var iterations = 0;
  12280. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  12281. var node = document.createTextNode('');
  12282. observer.observe(node, { characterData: true });
  12283. return function() {
  12284. node.data = (iterations = ++iterations % 2);
  12285. };
  12286. }
  12287. // web worker
  12288. function lib$es6$promise$asap$$useMessageChannel() {
  12289. var channel = new MessageChannel();
  12290. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  12291. return function () {
  12292. channel.port2.postMessage(0);
  12293. };
  12294. }
  12295. function lib$es6$promise$asap$$useSetTimeout() {
  12296. return function() {
  12297. setTimeout(lib$es6$promise$asap$$flush, 1);
  12298. };
  12299. }
  12300. var lib$es6$promise$asap$$queue = new Array(1000);
  12301. function lib$es6$promise$asap$$flush() {
  12302. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  12303. var callback = lib$es6$promise$asap$$queue[i];
  12304. var arg = lib$es6$promise$asap$$queue[i+1];
  12305. callback(arg);
  12306. lib$es6$promise$asap$$queue[i] = undefined;
  12307. lib$es6$promise$asap$$queue[i+1] = undefined;
  12308. }
  12309. lib$es6$promise$asap$$len = 0;
  12310. }
  12311. function lib$es6$promise$asap$$attemptVertx() {
  12312. try {
  12313. var r = require;
  12314. var vertx = r('vertx');
  12315. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  12316. return lib$es6$promise$asap$$useVertxTimer();
  12317. } catch(e) {
  12318. return lib$es6$promise$asap$$useSetTimeout();
  12319. }
  12320. }
  12321. var lib$es6$promise$asap$$scheduleFlush;
  12322. // Decide what async method to use to triggering processing of queued callbacks:
  12323. if (lib$es6$promise$asap$$isNode) {
  12324. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  12325. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  12326. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  12327. } else if (lib$es6$promise$asap$$isWorker) {
  12328. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  12329. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  12330. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  12331. } else {
  12332. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  12333. }
  12334. function lib$es6$promise$$internal$$noop() {}
  12335. var lib$es6$promise$$internal$$PENDING = void 0;
  12336. var lib$es6$promise$$internal$$FULFILLED = 1;
  12337. var lib$es6$promise$$internal$$REJECTED = 2;
  12338. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  12339. function lib$es6$promise$$internal$$selfFulfillment() {
  12340. return new TypeError("You cannot resolve a promise with itself");
  12341. }
  12342. function lib$es6$promise$$internal$$cannotReturnOwn() {
  12343. return new TypeError('A promises callback cannot return that same promise.');
  12344. }
  12345. function lib$es6$promise$$internal$$getThen(promise) {
  12346. try {
  12347. return promise.then;
  12348. } catch(error) {
  12349. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  12350. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  12351. }
  12352. }
  12353. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  12354. try {
  12355. then.call(value, fulfillmentHandler, rejectionHandler);
  12356. } catch(e) {
  12357. return e;
  12358. }
  12359. }
  12360. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  12361. lib$es6$promise$asap$$asap(function(promise) {
  12362. var sealed = false;
  12363. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  12364. if (sealed) { return; }
  12365. sealed = true;
  12366. if (thenable !== value) {
  12367. lib$es6$promise$$internal$$resolve(promise, value);
  12368. } else {
  12369. lib$es6$promise$$internal$$fulfill(promise, value);
  12370. }
  12371. }, function(reason) {
  12372. if (sealed) { return; }
  12373. sealed = true;
  12374. lib$es6$promise$$internal$$reject(promise, reason);
  12375. }, 'Settle: ' + (promise._label || ' unknown promise'));
  12376. if (!sealed && error) {
  12377. sealed = true;
  12378. lib$es6$promise$$internal$$reject(promise, error);
  12379. }
  12380. }, promise);
  12381. }
  12382. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  12383. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  12384. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  12385. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  12386. lib$es6$promise$$internal$$reject(promise, thenable._result);
  12387. } else {
  12388. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  12389. lib$es6$promise$$internal$$resolve(promise, value);
  12390. }, function(reason) {
  12391. lib$es6$promise$$internal$$reject(promise, reason);
  12392. });
  12393. }
  12394. }
  12395. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  12396. if (maybeThenable.constructor === promise.constructor) {
  12397. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  12398. } else {
  12399. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  12400. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  12401. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  12402. } else if (then === undefined) {
  12403. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  12404. } else if (lib$es6$promise$utils$$isFunction(then)) {
  12405. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  12406. } else {
  12407. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  12408. }
  12409. }
  12410. }
  12411. function lib$es6$promise$$internal$$resolve(promise, value) {
  12412. if (promise === value) {
  12413. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  12414. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  12415. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  12416. } else {
  12417. lib$es6$promise$$internal$$fulfill(promise, value);
  12418. }
  12419. }
  12420. function lib$es6$promise$$internal$$publishRejection(promise) {
  12421. if (promise._onerror) {
  12422. promise._onerror(promise._result);
  12423. }
  12424. lib$es6$promise$$internal$$publish(promise);
  12425. }
  12426. function lib$es6$promise$$internal$$fulfill(promise, value) {
  12427. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  12428. promise._result = value;
  12429. promise._state = lib$es6$promise$$internal$$FULFILLED;
  12430. if (promise._subscribers.length !== 0) {
  12431. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  12432. }
  12433. }
  12434. function lib$es6$promise$$internal$$reject(promise, reason) {
  12435. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  12436. promise._state = lib$es6$promise$$internal$$REJECTED;
  12437. promise._result = reason;
  12438. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  12439. }
  12440. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  12441. var subscribers = parent._subscribers;
  12442. var length = subscribers.length;
  12443. parent._onerror = null;
  12444. subscribers[length] = child;
  12445. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  12446. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  12447. if (length === 0 && parent._state) {
  12448. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  12449. }
  12450. }
  12451. function lib$es6$promise$$internal$$publish(promise) {
  12452. var subscribers = promise._subscribers;
  12453. var settled = promise._state;
  12454. if (subscribers.length === 0) { return; }
  12455. var child, callback, detail = promise._result;
  12456. for (var i = 0; i < subscribers.length; i += 3) {
  12457. child = subscribers[i];
  12458. callback = subscribers[i + settled];
  12459. if (child) {
  12460. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  12461. } else {
  12462. callback(detail);
  12463. }
  12464. }
  12465. promise._subscribers.length = 0;
  12466. }
  12467. function lib$es6$promise$$internal$$ErrorObject() {
  12468. this.error = null;
  12469. }
  12470. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  12471. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  12472. try {
  12473. return callback(detail);
  12474. } catch(e) {
  12475. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  12476. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  12477. }
  12478. }
  12479. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  12480. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  12481. value, error, succeeded, failed;
  12482. if (hasCallback) {
  12483. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  12484. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  12485. failed = true;
  12486. error = value.error;
  12487. value = null;
  12488. } else {
  12489. succeeded = true;
  12490. }
  12491. if (promise === value) {
  12492. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  12493. return;
  12494. }
  12495. } else {
  12496. value = detail;
  12497. succeeded = true;
  12498. }
  12499. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  12500. // noop
  12501. } else if (hasCallback && succeeded) {
  12502. lib$es6$promise$$internal$$resolve(promise, value);
  12503. } else if (failed) {
  12504. lib$es6$promise$$internal$$reject(promise, error);
  12505. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  12506. lib$es6$promise$$internal$$fulfill(promise, value);
  12507. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  12508. lib$es6$promise$$internal$$reject(promise, value);
  12509. }
  12510. }
  12511. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  12512. try {
  12513. resolver(function resolvePromise(value){
  12514. lib$es6$promise$$internal$$resolve(promise, value);
  12515. }, function rejectPromise(reason) {
  12516. lib$es6$promise$$internal$$reject(promise, reason);
  12517. });
  12518. } catch(e) {
  12519. lib$es6$promise$$internal$$reject(promise, e);
  12520. }
  12521. }
  12522. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  12523. var enumerator = this;
  12524. enumerator._instanceConstructor = Constructor;
  12525. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  12526. if (enumerator._validateInput(input)) {
  12527. enumerator._input = input;
  12528. enumerator.length = input.length;
  12529. enumerator._remaining = input.length;
  12530. enumerator._init();
  12531. if (enumerator.length === 0) {
  12532. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  12533. } else {
  12534. enumerator.length = enumerator.length || 0;
  12535. enumerator._enumerate();
  12536. if (enumerator._remaining === 0) {
  12537. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  12538. }
  12539. }
  12540. } else {
  12541. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  12542. }
  12543. }
  12544. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  12545. return lib$es6$promise$utils$$isArray(input);
  12546. };
  12547. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  12548. return new Error('Array Methods must be provided an Array');
  12549. };
  12550. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  12551. this._result = new Array(this.length);
  12552. };
  12553. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  12554. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  12555. var enumerator = this;
  12556. var length = enumerator.length;
  12557. var promise = enumerator.promise;
  12558. var input = enumerator._input;
  12559. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  12560. enumerator._eachEntry(input[i], i);
  12561. }
  12562. };
  12563. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  12564. var enumerator = this;
  12565. var c = enumerator._instanceConstructor;
  12566. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  12567. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  12568. entry._onerror = null;
  12569. enumerator._settledAt(entry._state, i, entry._result);
  12570. } else {
  12571. enumerator._willSettleAt(c.resolve(entry), i);
  12572. }
  12573. } else {
  12574. enumerator._remaining--;
  12575. enumerator._result[i] = entry;
  12576. }
  12577. };
  12578. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  12579. var enumerator = this;
  12580. var promise = enumerator.promise;
  12581. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  12582. enumerator._remaining--;
  12583. if (state === lib$es6$promise$$internal$$REJECTED) {
  12584. lib$es6$promise$$internal$$reject(promise, value);
  12585. } else {
  12586. enumerator._result[i] = value;
  12587. }
  12588. }
  12589. if (enumerator._remaining === 0) {
  12590. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  12591. }
  12592. };
  12593. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  12594. var enumerator = this;
  12595. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  12596. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  12597. }, function(reason) {
  12598. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  12599. });
  12600. };
  12601. function lib$es6$promise$promise$all$$all(entries) {
  12602. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  12603. }
  12604. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  12605. function lib$es6$promise$promise$race$$race(entries) {
  12606. /*jshint validthis:true */
  12607. var Constructor = this;
  12608. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12609. if (!lib$es6$promise$utils$$isArray(entries)) {
  12610. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  12611. return promise;
  12612. }
  12613. var length = entries.length;
  12614. function onFulfillment(value) {
  12615. lib$es6$promise$$internal$$resolve(promise, value);
  12616. }
  12617. function onRejection(reason) {
  12618. lib$es6$promise$$internal$$reject(promise, reason);
  12619. }
  12620. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  12621. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  12622. }
  12623. return promise;
  12624. }
  12625. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  12626. function lib$es6$promise$promise$resolve$$resolve(object) {
  12627. /*jshint validthis:true */
  12628. var Constructor = this;
  12629. if (object && typeof object === 'object' && object.constructor === Constructor) {
  12630. return object;
  12631. }
  12632. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12633. lib$es6$promise$$internal$$resolve(promise, object);
  12634. return promise;
  12635. }
  12636. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  12637. function lib$es6$promise$promise$reject$$reject(reason) {
  12638. /*jshint validthis:true */
  12639. var Constructor = this;
  12640. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12641. lib$es6$promise$$internal$$reject(promise, reason);
  12642. return promise;
  12643. }
  12644. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  12645. var lib$es6$promise$promise$$counter = 0;
  12646. function lib$es6$promise$promise$$needsResolver() {
  12647. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  12648. }
  12649. function lib$es6$promise$promise$$needsNew() {
  12650. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  12651. }
  12652. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  12653. /**
  12654. Promise objects represent the eventual result of an asynchronous operation. The
  12655. primary way of interacting with a promise is through its `then` method, which
  12656. registers callbacks to receive either a promise's eventual value or the reason
  12657. why the promise cannot be fulfilled.
  12658. Terminology
  12659. -----------
  12660. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  12661. - `thenable` is an object or function that defines a `then` method.
  12662. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  12663. - `exception` is a value that is thrown using the throw statement.
  12664. - `reason` is a value that indicates why a promise was rejected.
  12665. - `settled` the final resting state of a promise, fulfilled or rejected.
  12666. A promise can be in one of three states: pending, fulfilled, or rejected.
  12667. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  12668. state. Promises that are rejected have a rejection reason and are in the
  12669. rejected state. A fulfillment value is never a thenable.
  12670. Promises can also be said to *resolve* a value. If this value is also a
  12671. promise, then the original promise's settled state will match the value's
  12672. settled state. So a promise that *resolves* a promise that rejects will
  12673. itself reject, and a promise that *resolves* a promise that fulfills will
  12674. itself fulfill.
  12675. Basic Usage:
  12676. ------------
  12677. ```js
  12678. var promise = new Promise(function(resolve, reject) {
  12679. // on success
  12680. resolve(value);
  12681. // on failure
  12682. reject(reason);
  12683. });
  12684. promise.then(function(value) {
  12685. // on fulfillment
  12686. }, function(reason) {
  12687. // on rejection
  12688. });
  12689. ```
  12690. Advanced Usage:
  12691. ---------------
  12692. Promises shine when abstracting away asynchronous interactions such as
  12693. `XMLHttpRequest`s.
  12694. ```js
  12695. function getJSON(url) {
  12696. return new Promise(function(resolve, reject){
  12697. var xhr = new XMLHttpRequest();
  12698. xhr.open('GET', url);
  12699. xhr.onreadystatechange = handler;
  12700. xhr.responseType = 'json';
  12701. xhr.setRequestHeader('Accept', 'application/json');
  12702. xhr.send();
  12703. function handler() {
  12704. if (this.readyState === this.DONE) {
  12705. if (this.status === 200) {
  12706. resolve(this.response);
  12707. } else {
  12708. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  12709. }
  12710. }
  12711. };
  12712. });
  12713. }
  12714. getJSON('/posts.json').then(function(json) {
  12715. // on fulfillment
  12716. }, function(reason) {
  12717. // on rejection
  12718. });
  12719. ```
  12720. Unlike callbacks, promises are great composable primitives.
  12721. ```js
  12722. Promise.all([
  12723. getJSON('/posts'),
  12724. getJSON('/comments')
  12725. ]).then(function(values){
  12726. values[0] // => postsJSON
  12727. values[1] // => commentsJSON
  12728. return values;
  12729. });
  12730. ```
  12731. @class Promise
  12732. @param {function} resolver
  12733. Useful for tooling.
  12734. @constructor
  12735. */
  12736. function lib$es6$promise$promise$$Promise(resolver) {
  12737. this._id = lib$es6$promise$promise$$counter++;
  12738. this._state = undefined;
  12739. this._result = undefined;
  12740. this._subscribers = [];
  12741. if (lib$es6$promise$$internal$$noop !== resolver) {
  12742. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  12743. lib$es6$promise$promise$$needsResolver();
  12744. }
  12745. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  12746. lib$es6$promise$promise$$needsNew();
  12747. }
  12748. lib$es6$promise$$internal$$initializePromise(this, resolver);
  12749. }
  12750. }
  12751. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  12752. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  12753. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  12754. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  12755. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  12756. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  12757. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  12758. lib$es6$promise$promise$$Promise.prototype = {
  12759. constructor: lib$es6$promise$promise$$Promise,
  12760. /**
  12761. The primary way of interacting with a promise is through its `then` method,
  12762. which registers callbacks to receive either a promise's eventual value or the
  12763. reason why the promise cannot be fulfilled.
  12764. ```js
  12765. findUser().then(function(user){
  12766. // user is available
  12767. }, function(reason){
  12768. // user is unavailable, and you are given the reason why
  12769. });
  12770. ```
  12771. Chaining
  12772. --------
  12773. The return value of `then` is itself a promise. This second, 'downstream'
  12774. promise is resolved with the return value of the first promise's fulfillment
  12775. or rejection handler, or rejected if the handler throws an exception.
  12776. ```js
  12777. findUser().then(function (user) {
  12778. return user.name;
  12779. }, function (reason) {
  12780. return 'default name';
  12781. }).then(function (userName) {
  12782. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  12783. // will be `'default name'`
  12784. });
  12785. findUser().then(function (user) {
  12786. throw new Error('Found user, but still unhappy');
  12787. }, function (reason) {
  12788. throw new Error('`findUser` rejected and we're unhappy');
  12789. }).then(function (value) {
  12790. // never reached
  12791. }, function (reason) {
  12792. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  12793. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  12794. });
  12795. ```
  12796. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  12797. ```js
  12798. findUser().then(function (user) {
  12799. throw new PedagogicalException('Upstream error');
  12800. }).then(function (value) {
  12801. // never reached
  12802. }).then(function (value) {
  12803. // never reached
  12804. }, function (reason) {
  12805. // The `PedgagocialException` is propagated all the way down to here
  12806. });
  12807. ```
  12808. Assimilation
  12809. ------------
  12810. Sometimes the value you want to propagate to a downstream promise can only be
  12811. retrieved asynchronously. This can be achieved by returning a promise in the
  12812. fulfillment or rejection handler. The downstream promise will then be pending
  12813. until the returned promise is settled. This is called *assimilation*.
  12814. ```js
  12815. findUser().then(function (user) {
  12816. return findCommentsByAuthor(user);
  12817. }).then(function (comments) {
  12818. // The user's comments are now available
  12819. });
  12820. ```
  12821. If the assimliated promise rejects, then the downstream promise will also reject.
  12822. ```js
  12823. findUser().then(function (user) {
  12824. return findCommentsByAuthor(user);
  12825. }).then(function (comments) {
  12826. // If `findCommentsByAuthor` fulfills, we'll have the value here
  12827. }, function (reason) {
  12828. // If `findCommentsByAuthor` rejects, we'll have the reason here
  12829. });
  12830. ```
  12831. Simple Example
  12832. --------------
  12833. Synchronous Example
  12834. ```javascript
  12835. var result;
  12836. try {
  12837. result = findResult();
  12838. // success
  12839. } catch(reason) {
  12840. // failure
  12841. }
  12842. ```
  12843. Errback Example
  12844. ```js
  12845. findResult(function(result, err){
  12846. if (err) {
  12847. // failure
  12848. } else {
  12849. // success
  12850. }
  12851. });
  12852. ```
  12853. Promise Example;
  12854. ```javascript
  12855. findResult().then(function(result){
  12856. // success
  12857. }, function(reason){
  12858. // failure
  12859. });
  12860. ```
  12861. Advanced Example
  12862. --------------
  12863. Synchronous Example
  12864. ```javascript
  12865. var author, books;
  12866. try {
  12867. author = findAuthor();
  12868. books = findBooksByAuthor(author);
  12869. // success
  12870. } catch(reason) {
  12871. // failure
  12872. }
  12873. ```
  12874. Errback Example
  12875. ```js
  12876. function foundBooks(books) {
  12877. }
  12878. function failure(reason) {
  12879. }
  12880. findAuthor(function(author, err){
  12881. if (err) {
  12882. failure(err);
  12883. // failure
  12884. } else {
  12885. try {
  12886. findBoooksByAuthor(author, function(books, err) {
  12887. if (err) {
  12888. failure(err);
  12889. } else {
  12890. try {
  12891. foundBooks(books);
  12892. } catch(reason) {
  12893. failure(reason);
  12894. }
  12895. }
  12896. });
  12897. } catch(error) {
  12898. failure(err);
  12899. }
  12900. // success
  12901. }
  12902. });
  12903. ```
  12904. Promise Example;
  12905. ```javascript
  12906. findAuthor().
  12907. then(findBooksByAuthor).
  12908. then(function(books){
  12909. // found books
  12910. }).catch(function(reason){
  12911. // something went wrong
  12912. });
  12913. ```
  12914. @method then
  12915. @param {Function} onFulfilled
  12916. @param {Function} onRejected
  12917. Useful for tooling.
  12918. @return {Promise}
  12919. */
  12920. then: function(onFulfillment, onRejection) {
  12921. var parent = this;
  12922. var state = parent._state;
  12923. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  12924. return this;
  12925. }
  12926. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  12927. var result = parent._result;
  12928. if (state) {
  12929. var callback = arguments[state - 1];
  12930. lib$es6$promise$asap$$asap(function(){
  12931. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  12932. });
  12933. } else {
  12934. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  12935. }
  12936. return child;
  12937. },
  12938. /**
  12939. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  12940. as the catch block of a try/catch statement.
  12941. ```js
  12942. function findAuthor(){
  12943. throw new Error('couldn't find that author');
  12944. }
  12945. // synchronous
  12946. try {
  12947. findAuthor();
  12948. } catch(reason) {
  12949. // something went wrong
  12950. }
  12951. // async with promises
  12952. findAuthor().catch(function(reason){
  12953. // something went wrong
  12954. });
  12955. ```
  12956. @method catch
  12957. @param {Function} onRejection
  12958. Useful for tooling.
  12959. @return {Promise}
  12960. */
  12961. 'catch': function(onRejection) {
  12962. return this.then(null, onRejection);
  12963. }
  12964. };
  12965. function lib$es6$promise$polyfill$$polyfill() {
  12966. var local;
  12967. if (typeof global !== 'undefined') {
  12968. local = global;
  12969. } else if (typeof self !== 'undefined') {
  12970. local = self;
  12971. } else {
  12972. try {
  12973. local = Function('return this')();
  12974. } catch (e) {
  12975. throw new Error('polyfill failed because global object is unavailable in this environment');
  12976. }
  12977. }
  12978. var P = local.Promise;
  12979. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  12980. return;
  12981. }
  12982. local.Promise = lib$es6$promise$promise$$default;
  12983. }
  12984. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  12985. var lib$es6$promise$umd$$ES6Promise = {
  12986. 'Promise': lib$es6$promise$promise$$default,
  12987. 'polyfill': lib$es6$promise$polyfill$$default
  12988. };
  12989. /* global define:true module:true window: true */
  12990. if (typeof define === 'function' && define['amd']) {
  12991. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  12992. } else if (typeof module !== 'undefined' && module['exports']) {
  12993. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  12994. } else if (typeof this !== 'undefined') {
  12995. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  12996. }
  12997. lib$es6$promise$polyfill$$default();
  12998. }).call(this);
  12999. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  13000. },{"_process":45}],47:[function(require,module,exports){
  13001. /* Copyright @ 2015 Atlassian Pty Ltd
  13002. *
  13003. * Licensed under the Apache License, Version 2.0 (the "License");
  13004. * you may not use this file except in compliance with the License.
  13005. * You may obtain a copy of the License at
  13006. *
  13007. * http://www.apache.org/licenses/LICENSE-2.0
  13008. *
  13009. * Unless required by applicable law or agreed to in writing, software
  13010. * distributed under the License is distributed on an "AS IS" BASIS,
  13011. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13012. * See the License for the specific language governing permissions and
  13013. * limitations under the License.
  13014. */
  13015. /**
  13016. * Ordered log levels.
  13017. */
  13018. var levels = {
  13019. "trace": 0,
  13020. "debug": 1,
  13021. "info": 2,
  13022. "log": 3,
  13023. "warn": 4,
  13024. "error": 5
  13025. };
  13026. /**
  13027. * Parses Error's object stack trace and extracts information about the last
  13028. * caller before the log method was called.
  13029. * @returns JS object with info about the caller - method name, file location,
  13030. * line and column.
  13031. */
  13032. function getCallerInfo() {
  13033. var callerInfo = {
  13034. methodName: "",
  13035. fileLocation: "",
  13036. line: null,
  13037. column: null
  13038. };
  13039. //gets the part of the stack without the logger wrappers
  13040. var error = new Error();
  13041. var stack = error.stack? error.stack.split("\n") : [];
  13042. if(!stack || stack.length < 1) {
  13043. return callerInfo;
  13044. }
  13045. var m = null;
  13046. if(stack[3]) {
  13047. m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);
  13048. }
  13049. if(!m || m.length <= 4) {
  13050. //Firefox && Safari
  13051. if(stack[2].indexOf("log@") === 0){
  13052. //Safari
  13053. callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));
  13054. } else {
  13055. //Firefox
  13056. callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));
  13057. }
  13058. return callerInfo;
  13059. }
  13060. callerInfo.methodName = m[1];
  13061. callerInfo.fileLocation = m[2];
  13062. callerInfo.line = m[3];
  13063. callerInfo.column = m[4];
  13064. return callerInfo;
  13065. }
  13066. /**
  13067. * Logs messages using the transports and level from the logger.
  13068. * @param logger a logger instance.
  13069. * @param level the log level of the message. See the levels variable.
  13070. * @param arguments array with arguments that will be logged.
  13071. */
  13072. function log() {
  13073. var logger = arguments[0], level = arguments[1],
  13074. args = Array.prototype.slice.call(arguments, 2);
  13075. if(levels[level] <= logger.level) {
  13076. return;
  13077. }
  13078. var callerInfo = getCallerInfo();
  13079. for(var i = 0; i < logger.transports.length; i++) {
  13080. var t = logger.transports[i];
  13081. var l = t[level];
  13082. if(l && typeof(l) === "function") {
  13083. l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")
  13084. .apply(t, args);
  13085. }
  13086. }
  13087. }
  13088. /**
  13089. *
  13090. * Constructs new logger object.
  13091. * @param level the logging level for the new logger
  13092. * @param id optional identifier for the logger instance.
  13093. * @param transports optional list of handlers(objects) for the logs.
  13094. * The handlers must support - log, warn, error, debug, info, trace.
  13095. * @param format optional (NOT implemented) string.
  13096. */
  13097. function Logger(level, id, transports, format) {
  13098. this.id = id;
  13099. this.format = format;
  13100. if(!this.transports) {
  13101. this.transports = [];
  13102. this.transports.push(Logger.consoleTransport);
  13103. }
  13104. this.level = levels[level];
  13105. var methods = Object.keys(levels);
  13106. for(var i = 0; i < methods.length; i++){
  13107. this[methods[i]] =
  13108. log.bind(null, this, methods[i]);
  13109. }
  13110. }
  13111. /**
  13112. * Sets the log level for the logger.
  13113. * @param level the new log level.
  13114. */
  13115. Logger.prototype.setLevel = function (level) {
  13116. this.level = levels[level];
  13117. };
  13118. module.exports = Logger;
  13119. /**
  13120. * The default transport - console
  13121. */
  13122. Logger.consoleTransport = console;
  13123. /**
  13124. * Enum for the supported log levels.
  13125. */
  13126. Logger.levels = {
  13127. TRACE: "trace",
  13128. DEBUG: "debug",
  13129. INFO: "info",
  13130. LOG: "log",
  13131. WARN: "warn",
  13132. ERROR: "error"
  13133. };
  13134. },{}],48:[function(require,module,exports){
  13135. /* Copyright @ 2015 Atlassian Pty Ltd
  13136. *
  13137. * Licensed under the Apache License, Version 2.0 (the "License");
  13138. * you may not use this file except in compliance with the License.
  13139. * You may obtain a copy of the License at
  13140. *
  13141. * http://www.apache.org/licenses/LICENSE-2.0
  13142. *
  13143. * Unless required by applicable law or agreed to in writing, software
  13144. * distributed under the License is distributed on an "AS IS" BASIS,
  13145. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13146. * See the License for the specific language governing permissions and
  13147. * limitations under the License.
  13148. */
  13149. var Logger = require("./Logger");
  13150. /**
  13151. * Map with the created loggers with ID.
  13152. */
  13153. var idLoggers = {};
  13154. /**
  13155. * Array with the loggers without id.
  13156. */
  13157. var loggers = [];
  13158. /**
  13159. * Log level for the lbrary.
  13160. */
  13161. var curLevel = Logger.levels.TRACE;
  13162. module.exports = {
  13163. /**
  13164. * Creates new logger.
  13165. * @arguments the same as Logger constructor
  13166. */
  13167. getLogger: function(id, transports, format) {
  13168. var logger = new Logger(curLevel, id, transports, format);
  13169. if(id) {
  13170. idLoggers[id] = idLoggers[id] || [];
  13171. idLoggers[id].push(logger);
  13172. } else {
  13173. loggers.push(logger);
  13174. }
  13175. return logger;
  13176. },
  13177. /**
  13178. * Changes the log level for the existing loggers by id.
  13179. * @param level the new log level.
  13180. * @param id if specified the level will be changed only for loggers with the
  13181. * same id. Otherwise the operation will affect all loggers that don't
  13182. * have id.
  13183. */
  13184. setLogLevelById: function(level, id) {
  13185. var l = id? (idLoggers[id] || []) : loggers;
  13186. for(var i = 0; i < l.length; i++) {
  13187. l[i].setLevel(level);
  13188. }
  13189. },
  13190. /**
  13191. * Changes the log level for all existing loggers.
  13192. * @param level the new log level.
  13193. */
  13194. setLogLevel: function (level) {
  13195. curLevel = level;
  13196. var i = 0;
  13197. for(; i < loggers.length; i++) {
  13198. loggers[i].setLevel(level);
  13199. }
  13200. for(var id in idLoggers) {
  13201. var l = idLoggers[id] || [];
  13202. for(i = 0; i < l.length; i++) {
  13203. l[i].setLevel(level);
  13204. }
  13205. }
  13206. },
  13207. /**
  13208. * The supported log levels.
  13209. */
  13210. levels: Logger.levels
  13211. };
  13212. },{"./Logger":47}],49:[function(require,module,exports){
  13213. // Top level file is just a mixin of submodules & constants
  13214. 'use strict';
  13215. var assign = require('./lib/utils/common').assign;
  13216. var deflate = require('./lib/deflate');
  13217. var inflate = require('./lib/inflate');
  13218. var constants = require('./lib/zlib/constants');
  13219. var pako = {};
  13220. assign(pako, deflate, inflate, constants);
  13221. module.exports = pako;
  13222. },{"./lib/deflate":50,"./lib/inflate":51,"./lib/utils/common":52,"./lib/zlib/constants":55}],50:[function(require,module,exports){
  13223. 'use strict';
  13224. var zlib_deflate = require('./zlib/deflate.js');
  13225. var utils = require('./utils/common');
  13226. var strings = require('./utils/strings');
  13227. var msg = require('./zlib/messages');
  13228. var zstream = require('./zlib/zstream');
  13229. var toString = Object.prototype.toString;
  13230. /* Public constants ==========================================================*/
  13231. /* ===========================================================================*/
  13232. var Z_NO_FLUSH = 0;
  13233. var Z_FINISH = 4;
  13234. var Z_OK = 0;
  13235. var Z_STREAM_END = 1;
  13236. var Z_SYNC_FLUSH = 2;
  13237. var Z_DEFAULT_COMPRESSION = -1;
  13238. var Z_DEFAULT_STRATEGY = 0;
  13239. var Z_DEFLATED = 8;
  13240. /* ===========================================================================*/
  13241. /**
  13242. * class Deflate
  13243. *
  13244. * Generic JS-style wrapper for zlib calls. If you don't need
  13245. * streaming behaviour - use more simple functions: [[deflate]],
  13246. * [[deflateRaw]] and [[gzip]].
  13247. **/
  13248. /* internal
  13249. * Deflate.chunks -> Array
  13250. *
  13251. * Chunks of output data, if [[Deflate#onData]] not overriden.
  13252. **/
  13253. /**
  13254. * Deflate.result -> Uint8Array|Array
  13255. *
  13256. * Compressed result, generated by default [[Deflate#onData]]
  13257. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  13258. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  13259. * push a chunk with explicit flush (call [[Deflate#push]] with
  13260. * `Z_SYNC_FLUSH` param).
  13261. **/
  13262. /**
  13263. * Deflate.err -> Number
  13264. *
  13265. * Error code after deflate finished. 0 (Z_OK) on success.
  13266. * You will not need it in real life, because deflate errors
  13267. * are possible only on wrong options or bad `onData` / `onEnd`
  13268. * custom handlers.
  13269. **/
  13270. /**
  13271. * Deflate.msg -> String
  13272. *
  13273. * Error message, if [[Deflate.err]] != 0
  13274. **/
  13275. /**
  13276. * new Deflate(options)
  13277. * - options (Object): zlib deflate options.
  13278. *
  13279. * Creates new deflator instance with specified params. Throws exception
  13280. * on bad params. Supported options:
  13281. *
  13282. * - `level`
  13283. * - `windowBits`
  13284. * - `memLevel`
  13285. * - `strategy`
  13286. *
  13287. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13288. * for more information on these.
  13289. *
  13290. * Additional options, for internal needs:
  13291. *
  13292. * - `chunkSize` - size of generated data chunks (16K by default)
  13293. * - `raw` (Boolean) - do raw deflate
  13294. * - `gzip` (Boolean) - create gzip wrapper
  13295. * - `to` (String) - if equal to 'string', then result will be "binary string"
  13296. * (each char code [0..255])
  13297. * - `header` (Object) - custom header for gzip
  13298. * - `text` (Boolean) - true if compressed data believed to be text
  13299. * - `time` (Number) - modification time, unix timestamp
  13300. * - `os` (Number) - operation system code
  13301. * - `extra` (Array) - array of bytes with extra data (max 65536)
  13302. * - `name` (String) - file name (binary string)
  13303. * - `comment` (String) - comment (binary string)
  13304. * - `hcrc` (Boolean) - true if header crc should be added
  13305. *
  13306. * ##### Example:
  13307. *
  13308. * ```javascript
  13309. * var pako = require('pako')
  13310. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  13311. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  13312. *
  13313. * var deflate = new pako.Deflate({ level: 3});
  13314. *
  13315. * deflate.push(chunk1, false);
  13316. * deflate.push(chunk2, true); // true -> last chunk
  13317. *
  13318. * if (deflate.err) { throw new Error(deflate.err); }
  13319. *
  13320. * console.log(deflate.result);
  13321. * ```
  13322. **/
  13323. var Deflate = function(options) {
  13324. this.options = utils.assign({
  13325. level: Z_DEFAULT_COMPRESSION,
  13326. method: Z_DEFLATED,
  13327. chunkSize: 16384,
  13328. windowBits: 15,
  13329. memLevel: 8,
  13330. strategy: Z_DEFAULT_STRATEGY,
  13331. to: ''
  13332. }, options || {});
  13333. var opt = this.options;
  13334. if (opt.raw && (opt.windowBits > 0)) {
  13335. opt.windowBits = -opt.windowBits;
  13336. }
  13337. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  13338. opt.windowBits += 16;
  13339. }
  13340. this.err = 0; // error code, if happens (0 = Z_OK)
  13341. this.msg = ''; // error message
  13342. this.ended = false; // used to avoid multiple onEnd() calls
  13343. this.chunks = []; // chunks of compressed data
  13344. this.strm = new zstream();
  13345. this.strm.avail_out = 0;
  13346. var status = zlib_deflate.deflateInit2(
  13347. this.strm,
  13348. opt.level,
  13349. opt.method,
  13350. opt.windowBits,
  13351. opt.memLevel,
  13352. opt.strategy
  13353. );
  13354. if (status !== Z_OK) {
  13355. throw new Error(msg[status]);
  13356. }
  13357. if (opt.header) {
  13358. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  13359. }
  13360. };
  13361. /**
  13362. * Deflate#push(data[, mode]) -> Boolean
  13363. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  13364. * converted to utf8 byte sequence.
  13365. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  13366. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  13367. *
  13368. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  13369. * new compressed chunks. Returns `true` on success. The last data block must have
  13370. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  13371. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  13372. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  13373. *
  13374. * On fail call [[Deflate#onEnd]] with error code and return false.
  13375. *
  13376. * We strongly recommend to use `Uint8Array` on input for best speed (output
  13377. * array format is detected automatically). Also, don't skip last param and always
  13378. * use the same type in your code (boolean or number). That will improve JS speed.
  13379. *
  13380. * For regular `Array`-s make sure all elements are [0..255].
  13381. *
  13382. * ##### Example
  13383. *
  13384. * ```javascript
  13385. * push(chunk, false); // push one of data chunks
  13386. * ...
  13387. * push(chunk, true); // push last chunk
  13388. * ```
  13389. **/
  13390. Deflate.prototype.push = function(data, mode) {
  13391. var strm = this.strm;
  13392. var chunkSize = this.options.chunkSize;
  13393. var status, _mode;
  13394. if (this.ended) { return false; }
  13395. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  13396. // Convert data if needed
  13397. if (typeof data === 'string') {
  13398. // If we need to compress text, change encoding to utf8.
  13399. strm.input = strings.string2buf(data);
  13400. } else if (toString.call(data) === '[object ArrayBuffer]') {
  13401. strm.input = new Uint8Array(data);
  13402. } else {
  13403. strm.input = data;
  13404. }
  13405. strm.next_in = 0;
  13406. strm.avail_in = strm.input.length;
  13407. do {
  13408. if (strm.avail_out === 0) {
  13409. strm.output = new utils.Buf8(chunkSize);
  13410. strm.next_out = 0;
  13411. strm.avail_out = chunkSize;
  13412. }
  13413. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  13414. if (status !== Z_STREAM_END && status !== Z_OK) {
  13415. this.onEnd(status);
  13416. this.ended = true;
  13417. return false;
  13418. }
  13419. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  13420. if (this.options.to === 'string') {
  13421. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  13422. } else {
  13423. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  13424. }
  13425. }
  13426. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  13427. // Finalize on the last chunk.
  13428. if (_mode === Z_FINISH) {
  13429. status = zlib_deflate.deflateEnd(this.strm);
  13430. this.onEnd(status);
  13431. this.ended = true;
  13432. return status === Z_OK;
  13433. }
  13434. // callback interim results if Z_SYNC_FLUSH.
  13435. if (_mode === Z_SYNC_FLUSH) {
  13436. this.onEnd(Z_OK);
  13437. strm.avail_out = 0;
  13438. return true;
  13439. }
  13440. return true;
  13441. };
  13442. /**
  13443. * Deflate#onData(chunk) -> Void
  13444. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  13445. * on js engine support. When string output requested, each chunk
  13446. * will be string.
  13447. *
  13448. * By default, stores data blocks in `chunks[]` property and glue
  13449. * those in `onEnd`. Override this handler, if you need another behaviour.
  13450. **/
  13451. Deflate.prototype.onData = function(chunk) {
  13452. this.chunks.push(chunk);
  13453. };
  13454. /**
  13455. * Deflate#onEnd(status) -> Void
  13456. * - status (Number): deflate status. 0 (Z_OK) on success,
  13457. * other if not.
  13458. *
  13459. * Called once after you tell deflate that the input stream is
  13460. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  13461. * or if an error happened. By default - join collected chunks,
  13462. * free memory and fill `results` / `err` properties.
  13463. **/
  13464. Deflate.prototype.onEnd = function(status) {
  13465. // On success - join
  13466. if (status === Z_OK) {
  13467. if (this.options.to === 'string') {
  13468. this.result = this.chunks.join('');
  13469. } else {
  13470. this.result = utils.flattenChunks(this.chunks);
  13471. }
  13472. }
  13473. this.chunks = [];
  13474. this.err = status;
  13475. this.msg = this.strm.msg;
  13476. };
  13477. /**
  13478. * deflate(data[, options]) -> Uint8Array|Array|String
  13479. * - data (Uint8Array|Array|String): input data to compress.
  13480. * - options (Object): zlib deflate options.
  13481. *
  13482. * Compress `data` with deflate alrorythm and `options`.
  13483. *
  13484. * Supported options are:
  13485. *
  13486. * - level
  13487. * - windowBits
  13488. * - memLevel
  13489. * - strategy
  13490. *
  13491. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13492. * for more information on these.
  13493. *
  13494. * Sugar (options):
  13495. *
  13496. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  13497. * negative windowBits implicitly.
  13498. * - `to` (String) - if equal to 'string', then result will be "binary string"
  13499. * (each char code [0..255])
  13500. *
  13501. * ##### Example:
  13502. *
  13503. * ```javascript
  13504. * var pako = require('pako')
  13505. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  13506. *
  13507. * console.log(pako.deflate(data));
  13508. * ```
  13509. **/
  13510. function deflate(input, options) {
  13511. var deflator = new Deflate(options);
  13512. deflator.push(input, true);
  13513. // That will never happens, if you don't cheat with options :)
  13514. if (deflator.err) { throw deflator.msg; }
  13515. return deflator.result;
  13516. }
  13517. /**
  13518. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  13519. * - data (Uint8Array|Array|String): input data to compress.
  13520. * - options (Object): zlib deflate options.
  13521. *
  13522. * The same as [[deflate]], but creates raw data, without wrapper
  13523. * (header and adler32 crc).
  13524. **/
  13525. function deflateRaw(input, options) {
  13526. options = options || {};
  13527. options.raw = true;
  13528. return deflate(input, options);
  13529. }
  13530. /**
  13531. * gzip(data[, options]) -> Uint8Array|Array|String
  13532. * - data (Uint8Array|Array|String): input data to compress.
  13533. * - options (Object): zlib deflate options.
  13534. *
  13535. * The same as [[deflate]], but create gzip wrapper instead of
  13536. * deflate one.
  13537. **/
  13538. function gzip(input, options) {
  13539. options = options || {};
  13540. options.gzip = true;
  13541. return deflate(input, options);
  13542. }
  13543. exports.Deflate = Deflate;
  13544. exports.deflate = deflate;
  13545. exports.deflateRaw = deflateRaw;
  13546. exports.gzip = gzip;
  13547. },{"./utils/common":52,"./utils/strings":53,"./zlib/deflate.js":57,"./zlib/messages":62,"./zlib/zstream":64}],51:[function(require,module,exports){
  13548. 'use strict';
  13549. var zlib_inflate = require('./zlib/inflate.js');
  13550. var utils = require('./utils/common');
  13551. var strings = require('./utils/strings');
  13552. var c = require('./zlib/constants');
  13553. var msg = require('./zlib/messages');
  13554. var zstream = require('./zlib/zstream');
  13555. var gzheader = require('./zlib/gzheader');
  13556. var toString = Object.prototype.toString;
  13557. /**
  13558. * class Inflate
  13559. *
  13560. * Generic JS-style wrapper for zlib calls. If you don't need
  13561. * streaming behaviour - use more simple functions: [[inflate]]
  13562. * and [[inflateRaw]].
  13563. **/
  13564. /* internal
  13565. * inflate.chunks -> Array
  13566. *
  13567. * Chunks of output data, if [[Inflate#onData]] not overriden.
  13568. **/
  13569. /**
  13570. * Inflate.result -> Uint8Array|Array|String
  13571. *
  13572. * Uncompressed result, generated by default [[Inflate#onData]]
  13573. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  13574. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  13575. * push a chunk with explicit flush (call [[Inflate#push]] with
  13576. * `Z_SYNC_FLUSH` param).
  13577. **/
  13578. /**
  13579. * Inflate.err -> Number
  13580. *
  13581. * Error code after inflate finished. 0 (Z_OK) on success.
  13582. * Should be checked if broken data possible.
  13583. **/
  13584. /**
  13585. * Inflate.msg -> String
  13586. *
  13587. * Error message, if [[Inflate.err]] != 0
  13588. **/
  13589. /**
  13590. * new Inflate(options)
  13591. * - options (Object): zlib inflate options.
  13592. *
  13593. * Creates new inflator instance with specified params. Throws exception
  13594. * on bad params. Supported options:
  13595. *
  13596. * - `windowBits`
  13597. *
  13598. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13599. * for more information on these.
  13600. *
  13601. * Additional options, for internal needs:
  13602. *
  13603. * - `chunkSize` - size of generated data chunks (16K by default)
  13604. * - `raw` (Boolean) - do raw inflate
  13605. * - `to` (String) - if equal to 'string', then result will be converted
  13606. * from utf8 to utf16 (javascript) string. When string output requested,
  13607. * chunk length can differ from `chunkSize`, depending on content.
  13608. *
  13609. * By default, when no options set, autodetect deflate/gzip data format via
  13610. * wrapper header.
  13611. *
  13612. * ##### Example:
  13613. *
  13614. * ```javascript
  13615. * var pako = require('pako')
  13616. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  13617. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  13618. *
  13619. * var inflate = new pako.Inflate({ level: 3});
  13620. *
  13621. * inflate.push(chunk1, false);
  13622. * inflate.push(chunk2, true); // true -> last chunk
  13623. *
  13624. * if (inflate.err) { throw new Error(inflate.err); }
  13625. *
  13626. * console.log(inflate.result);
  13627. * ```
  13628. **/
  13629. var Inflate = function(options) {
  13630. this.options = utils.assign({
  13631. chunkSize: 16384,
  13632. windowBits: 0,
  13633. to: ''
  13634. }, options || {});
  13635. var opt = this.options;
  13636. // Force window size for `raw` data, if not set directly,
  13637. // because we have no header for autodetect.
  13638. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  13639. opt.windowBits = -opt.windowBits;
  13640. if (opt.windowBits === 0) { opt.windowBits = -15; }
  13641. }
  13642. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  13643. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  13644. !(options && options.windowBits)) {
  13645. opt.windowBits += 32;
  13646. }
  13647. // Gzip header has no info about windows size, we can do autodetect only
  13648. // for deflate. So, if window size not set, force it to max when gzip possible
  13649. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  13650. // bit 3 (16) -> gzipped data
  13651. // bit 4 (32) -> autodetect gzip/deflate
  13652. if ((opt.windowBits & 15) === 0) {
  13653. opt.windowBits |= 15;
  13654. }
  13655. }
  13656. this.err = 0; // error code, if happens (0 = Z_OK)
  13657. this.msg = ''; // error message
  13658. this.ended = false; // used to avoid multiple onEnd() calls
  13659. this.chunks = []; // chunks of compressed data
  13660. this.strm = new zstream();
  13661. this.strm.avail_out = 0;
  13662. var status = zlib_inflate.inflateInit2(
  13663. this.strm,
  13664. opt.windowBits
  13665. );
  13666. if (status !== c.Z_OK) {
  13667. throw new Error(msg[status]);
  13668. }
  13669. this.header = new gzheader();
  13670. zlib_inflate.inflateGetHeader(this.strm, this.header);
  13671. };
  13672. /**
  13673. * Inflate#push(data[, mode]) -> Boolean
  13674. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  13675. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  13676. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  13677. *
  13678. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  13679. * new output chunks. Returns `true` on success. The last data block must have
  13680. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  13681. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  13682. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  13683. *
  13684. * On fail call [[Inflate#onEnd]] with error code and return false.
  13685. *
  13686. * We strongly recommend to use `Uint8Array` on input for best speed (output
  13687. * format is detected automatically). Also, don't skip last param and always
  13688. * use the same type in your code (boolean or number). That will improve JS speed.
  13689. *
  13690. * For regular `Array`-s make sure all elements are [0..255].
  13691. *
  13692. * ##### Example
  13693. *
  13694. * ```javascript
  13695. * push(chunk, false); // push one of data chunks
  13696. * ...
  13697. * push(chunk, true); // push last chunk
  13698. * ```
  13699. **/
  13700. Inflate.prototype.push = function(data, mode) {
  13701. var strm = this.strm;
  13702. var chunkSize = this.options.chunkSize;
  13703. var status, _mode;
  13704. var next_out_utf8, tail, utf8str;
  13705. // Flag to properly process Z_BUF_ERROR on testing inflate call
  13706. // when we check that all output data was flushed.
  13707. var allowBufError = false;
  13708. if (this.ended) { return false; }
  13709. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  13710. // Convert data if needed
  13711. if (typeof data === 'string') {
  13712. // Only binary strings can be decompressed on practice
  13713. strm.input = strings.binstring2buf(data);
  13714. } else if (toString.call(data) === '[object ArrayBuffer]') {
  13715. strm.input = new Uint8Array(data);
  13716. } else {
  13717. strm.input = data;
  13718. }
  13719. strm.next_in = 0;
  13720. strm.avail_in = strm.input.length;
  13721. do {
  13722. if (strm.avail_out === 0) {
  13723. strm.output = new utils.Buf8(chunkSize);
  13724. strm.next_out = 0;
  13725. strm.avail_out = chunkSize;
  13726. }
  13727. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  13728. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  13729. status = c.Z_OK;
  13730. allowBufError = false;
  13731. }
  13732. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  13733. this.onEnd(status);
  13734. this.ended = true;
  13735. return false;
  13736. }
  13737. if (strm.next_out) {
  13738. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  13739. if (this.options.to === 'string') {
  13740. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  13741. tail = strm.next_out - next_out_utf8;
  13742. utf8str = strings.buf2string(strm.output, next_out_utf8);
  13743. // move tail
  13744. strm.next_out = tail;
  13745. strm.avail_out = chunkSize - tail;
  13746. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  13747. this.onData(utf8str);
  13748. } else {
  13749. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  13750. }
  13751. }
  13752. }
  13753. // When no more input data, we should check that internal inflate buffers
  13754. // are flushed. The only way to do it when avail_out = 0 - run one more
  13755. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  13756. // Here we set flag to process this error properly.
  13757. //
  13758. // NOTE. Deflate does not return error in this case and does not needs such
  13759. // logic.
  13760. if (strm.avail_in === 0 && strm.avail_out === 0) {
  13761. allowBufError = true;
  13762. }
  13763. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  13764. if (status === c.Z_STREAM_END) {
  13765. _mode = c.Z_FINISH;
  13766. }
  13767. // Finalize on the last chunk.
  13768. if (_mode === c.Z_FINISH) {
  13769. status = zlib_inflate.inflateEnd(this.strm);
  13770. this.onEnd(status);
  13771. this.ended = true;
  13772. return status === c.Z_OK;
  13773. }
  13774. // callback interim results if Z_SYNC_FLUSH.
  13775. if (_mode === c.Z_SYNC_FLUSH) {
  13776. this.onEnd(c.Z_OK);
  13777. strm.avail_out = 0;
  13778. return true;
  13779. }
  13780. return true;
  13781. };
  13782. /**
  13783. * Inflate#onData(chunk) -> Void
  13784. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  13785. * on js engine support. When string output requested, each chunk
  13786. * will be string.
  13787. *
  13788. * By default, stores data blocks in `chunks[]` property and glue
  13789. * those in `onEnd`. Override this handler, if you need another behaviour.
  13790. **/
  13791. Inflate.prototype.onData = function(chunk) {
  13792. this.chunks.push(chunk);
  13793. };
  13794. /**
  13795. * Inflate#onEnd(status) -> Void
  13796. * - status (Number): inflate status. 0 (Z_OK) on success,
  13797. * other if not.
  13798. *
  13799. * Called either after you tell inflate that the input stream is
  13800. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  13801. * or if an error happened. By default - join collected chunks,
  13802. * free memory and fill `results` / `err` properties.
  13803. **/
  13804. Inflate.prototype.onEnd = function(status) {
  13805. // On success - join
  13806. if (status === c.Z_OK) {
  13807. if (this.options.to === 'string') {
  13808. // Glue & convert here, until we teach pako to send
  13809. // utf8 alligned strings to onData
  13810. this.result = this.chunks.join('');
  13811. } else {
  13812. this.result = utils.flattenChunks(this.chunks);
  13813. }
  13814. }
  13815. this.chunks = [];
  13816. this.err = status;
  13817. this.msg = this.strm.msg;
  13818. };
  13819. /**
  13820. * inflate(data[, options]) -> Uint8Array|Array|String
  13821. * - data (Uint8Array|Array|String): input data to decompress.
  13822. * - options (Object): zlib inflate options.
  13823. *
  13824. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  13825. * format via wrapper header by default. That's why we don't provide
  13826. * separate `ungzip` method.
  13827. *
  13828. * Supported options are:
  13829. *
  13830. * - windowBits
  13831. *
  13832. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13833. * for more information.
  13834. *
  13835. * Sugar (options):
  13836. *
  13837. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  13838. * negative windowBits implicitly.
  13839. * - `to` (String) - if equal to 'string', then result will be converted
  13840. * from utf8 to utf16 (javascript) string. When string output requested,
  13841. * chunk length can differ from `chunkSize`, depending on content.
  13842. *
  13843. *
  13844. * ##### Example:
  13845. *
  13846. * ```javascript
  13847. * var pako = require('pako')
  13848. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  13849. * , output;
  13850. *
  13851. * try {
  13852. * output = pako.inflate(input);
  13853. * } catch (err)
  13854. * console.log(err);
  13855. * }
  13856. * ```
  13857. **/
  13858. function inflate(input, options) {
  13859. var inflator = new Inflate(options);
  13860. inflator.push(input, true);
  13861. // That will never happens, if you don't cheat with options :)
  13862. if (inflator.err) { throw inflator.msg; }
  13863. return inflator.result;
  13864. }
  13865. /**
  13866. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  13867. * - data (Uint8Array|Array|String): input data to decompress.
  13868. * - options (Object): zlib inflate options.
  13869. *
  13870. * The same as [[inflate]], but creates raw data, without wrapper
  13871. * (header and adler32 crc).
  13872. **/
  13873. function inflateRaw(input, options) {
  13874. options = options || {};
  13875. options.raw = true;
  13876. return inflate(input, options);
  13877. }
  13878. /**
  13879. * ungzip(data[, options]) -> Uint8Array|Array|String
  13880. * - data (Uint8Array|Array|String): input data to decompress.
  13881. * - options (Object): zlib inflate options.
  13882. *
  13883. * Just shortcut to [[inflate]], because it autodetects format
  13884. * by header.content. Done for convenience.
  13885. **/
  13886. exports.Inflate = Inflate;
  13887. exports.inflate = inflate;
  13888. exports.inflateRaw = inflateRaw;
  13889. exports.ungzip = inflate;
  13890. },{"./utils/common":52,"./utils/strings":53,"./zlib/constants":55,"./zlib/gzheader":58,"./zlib/inflate.js":60,"./zlib/messages":62,"./zlib/zstream":64}],52:[function(require,module,exports){
  13891. 'use strict';
  13892. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  13893. (typeof Uint16Array !== 'undefined') &&
  13894. (typeof Int32Array !== 'undefined');
  13895. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  13896. var sources = Array.prototype.slice.call(arguments, 1);
  13897. while (sources.length) {
  13898. var source = sources.shift();
  13899. if (!source) { continue; }
  13900. if (typeof source !== 'object') {
  13901. throw new TypeError(source + 'must be non-object');
  13902. }
  13903. for (var p in source) {
  13904. if (source.hasOwnProperty(p)) {
  13905. obj[p] = source[p];
  13906. }
  13907. }
  13908. }
  13909. return obj;
  13910. };
  13911. // reduce buffer size, avoiding mem copy
  13912. exports.shrinkBuf = function (buf, size) {
  13913. if (buf.length === size) { return buf; }
  13914. if (buf.subarray) { return buf.subarray(0, size); }
  13915. buf.length = size;
  13916. return buf;
  13917. };
  13918. var fnTyped = {
  13919. arraySet: function (dest, src, src_offs, len, dest_offs) {
  13920. if (src.subarray && dest.subarray) {
  13921. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  13922. return;
  13923. }
  13924. // Fallback to ordinary array
  13925. for (var i=0; i<len; i++) {
  13926. dest[dest_offs + i] = src[src_offs + i];
  13927. }
  13928. },
  13929. // Join array of chunks to single array.
  13930. flattenChunks: function(chunks) {
  13931. var i, l, len, pos, chunk, result;
  13932. // calculate data length
  13933. len = 0;
  13934. for (i=0, l=chunks.length; i<l; i++) {
  13935. len += chunks[i].length;
  13936. }
  13937. // join chunks
  13938. result = new Uint8Array(len);
  13939. pos = 0;
  13940. for (i=0, l=chunks.length; i<l; i++) {
  13941. chunk = chunks[i];
  13942. result.set(chunk, pos);
  13943. pos += chunk.length;
  13944. }
  13945. return result;
  13946. }
  13947. };
  13948. var fnUntyped = {
  13949. arraySet: function (dest, src, src_offs, len, dest_offs) {
  13950. for (var i=0; i<len; i++) {
  13951. dest[dest_offs + i] = src[src_offs + i];
  13952. }
  13953. },
  13954. // Join array of chunks to single array.
  13955. flattenChunks: function(chunks) {
  13956. return [].concat.apply([], chunks);
  13957. }
  13958. };
  13959. // Enable/Disable typed arrays use, for testing
  13960. //
  13961. exports.setTyped = function (on) {
  13962. if (on) {
  13963. exports.Buf8 = Uint8Array;
  13964. exports.Buf16 = Uint16Array;
  13965. exports.Buf32 = Int32Array;
  13966. exports.assign(exports, fnTyped);
  13967. } else {
  13968. exports.Buf8 = Array;
  13969. exports.Buf16 = Array;
  13970. exports.Buf32 = Array;
  13971. exports.assign(exports, fnUntyped);
  13972. }
  13973. };
  13974. exports.setTyped(TYPED_OK);
  13975. },{}],53:[function(require,module,exports){
  13976. // String encode/decode helpers
  13977. 'use strict';
  13978. var utils = require('./common');
  13979. // Quick check if we can use fast array to bin string conversion
  13980. //
  13981. // - apply(Array) can fail on Android 2.2
  13982. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  13983. //
  13984. var STR_APPLY_OK = true;
  13985. var STR_APPLY_UIA_OK = true;
  13986. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  13987. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  13988. // Table with utf8 lengths (calculated by first byte of sequence)
  13989. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  13990. // because max possible codepoint is 0x10ffff
  13991. var _utf8len = new utils.Buf8(256);
  13992. for (var q=0; q<256; q++) {
  13993. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  13994. }
  13995. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  13996. // convert string to array (typed, when possible)
  13997. exports.string2buf = function (str) {
  13998. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  13999. // count binary size
  14000. for (m_pos = 0; m_pos < str_len; m_pos++) {
  14001. c = str.charCodeAt(m_pos);
  14002. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  14003. c2 = str.charCodeAt(m_pos+1);
  14004. if ((c2 & 0xfc00) === 0xdc00) {
  14005. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  14006. m_pos++;
  14007. }
  14008. }
  14009. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  14010. }
  14011. // allocate buffer
  14012. buf = new utils.Buf8(buf_len);
  14013. // convert
  14014. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  14015. c = str.charCodeAt(m_pos);
  14016. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  14017. c2 = str.charCodeAt(m_pos+1);
  14018. if ((c2 & 0xfc00) === 0xdc00) {
  14019. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  14020. m_pos++;
  14021. }
  14022. }
  14023. if (c < 0x80) {
  14024. /* one byte */
  14025. buf[i++] = c;
  14026. } else if (c < 0x800) {
  14027. /* two bytes */
  14028. buf[i++] = 0xC0 | (c >>> 6);
  14029. buf[i++] = 0x80 | (c & 0x3f);
  14030. } else if (c < 0x10000) {
  14031. /* three bytes */
  14032. buf[i++] = 0xE0 | (c >>> 12);
  14033. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  14034. buf[i++] = 0x80 | (c & 0x3f);
  14035. } else {
  14036. /* four bytes */
  14037. buf[i++] = 0xf0 | (c >>> 18);
  14038. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  14039. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  14040. buf[i++] = 0x80 | (c & 0x3f);
  14041. }
  14042. }
  14043. return buf;
  14044. };
  14045. // Helper (used in 2 places)
  14046. function buf2binstring(buf, len) {
  14047. // use fallback for big arrays to avoid stack overflow
  14048. if (len < 65537) {
  14049. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  14050. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  14051. }
  14052. }
  14053. var result = '';
  14054. for (var i=0; i < len; i++) {
  14055. result += String.fromCharCode(buf[i]);
  14056. }
  14057. return result;
  14058. }
  14059. // Convert byte array to binary string
  14060. exports.buf2binstring = function(buf) {
  14061. return buf2binstring(buf, buf.length);
  14062. };
  14063. // Convert binary string (typed, when possible)
  14064. exports.binstring2buf = function(str) {
  14065. var buf = new utils.Buf8(str.length);
  14066. for (var i=0, len=buf.length; i < len; i++) {
  14067. buf[i] = str.charCodeAt(i);
  14068. }
  14069. return buf;
  14070. };
  14071. // convert array to string
  14072. exports.buf2string = function (buf, max) {
  14073. var i, out, c, c_len;
  14074. var len = max || buf.length;
  14075. // Reserve max possible length (2 words per char)
  14076. // NB: by unknown reasons, Array is significantly faster for
  14077. // String.fromCharCode.apply than Uint16Array.
  14078. var utf16buf = new Array(len*2);
  14079. for (out=0, i=0; i<len;) {
  14080. c = buf[i++];
  14081. // quick process ascii
  14082. if (c < 0x80) { utf16buf[out++] = c; continue; }
  14083. c_len = _utf8len[c];
  14084. // skip 5 & 6 byte codes
  14085. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  14086. // apply mask on first byte
  14087. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  14088. // join the rest
  14089. while (c_len > 1 && i < len) {
  14090. c = (c << 6) | (buf[i++] & 0x3f);
  14091. c_len--;
  14092. }
  14093. // terminated by end of string?
  14094. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  14095. if (c < 0x10000) {
  14096. utf16buf[out++] = c;
  14097. } else {
  14098. c -= 0x10000;
  14099. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  14100. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  14101. }
  14102. }
  14103. return buf2binstring(utf16buf, out);
  14104. };
  14105. // Calculate max possible position in utf8 buffer,
  14106. // that will not break sequence. If that's not possible
  14107. // - (very small limits) return max size as is.
  14108. //
  14109. // buf[] - utf8 bytes array
  14110. // max - length limit (mandatory);
  14111. exports.utf8border = function(buf, max) {
  14112. var pos;
  14113. max = max || buf.length;
  14114. if (max > buf.length) { max = buf.length; }
  14115. // go back from last position, until start of sequence found
  14116. pos = max-1;
  14117. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  14118. // Fuckup - very small and broken sequence,
  14119. // return max, because we should return something anyway.
  14120. if (pos < 0) { return max; }
  14121. // If we came to start of buffer - that means vuffer is too small,
  14122. // return max too.
  14123. if (pos === 0) { return max; }
  14124. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  14125. };
  14126. },{"./common":52}],54:[function(require,module,exports){
  14127. 'use strict';
  14128. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  14129. // It doesn't worth to make additional optimizationa as in original.
  14130. // Small size is preferable.
  14131. function adler32(adler, buf, len, pos) {
  14132. var s1 = (adler & 0xffff) |0,
  14133. s2 = ((adler >>> 16) & 0xffff) |0,
  14134. n = 0;
  14135. while (len !== 0) {
  14136. // Set limit ~ twice less than 5552, to keep
  14137. // s2 in 31-bits, because we force signed ints.
  14138. // in other case %= will fail.
  14139. n = len > 2000 ? 2000 : len;
  14140. len -= n;
  14141. do {
  14142. s1 = (s1 + buf[pos++]) |0;
  14143. s2 = (s2 + s1) |0;
  14144. } while (--n);
  14145. s1 %= 65521;
  14146. s2 %= 65521;
  14147. }
  14148. return (s1 | (s2 << 16)) |0;
  14149. }
  14150. module.exports = adler32;
  14151. },{}],55:[function(require,module,exports){
  14152. module.exports = {
  14153. /* Allowed flush values; see deflate() and inflate() below for details */
  14154. Z_NO_FLUSH: 0,
  14155. Z_PARTIAL_FLUSH: 1,
  14156. Z_SYNC_FLUSH: 2,
  14157. Z_FULL_FLUSH: 3,
  14158. Z_FINISH: 4,
  14159. Z_BLOCK: 5,
  14160. Z_TREES: 6,
  14161. /* Return codes for the compression/decompression functions. Negative values
  14162. * are errors, positive values are used for special but normal events.
  14163. */
  14164. Z_OK: 0,
  14165. Z_STREAM_END: 1,
  14166. Z_NEED_DICT: 2,
  14167. Z_ERRNO: -1,
  14168. Z_STREAM_ERROR: -2,
  14169. Z_DATA_ERROR: -3,
  14170. //Z_MEM_ERROR: -4,
  14171. Z_BUF_ERROR: -5,
  14172. //Z_VERSION_ERROR: -6,
  14173. /* compression levels */
  14174. Z_NO_COMPRESSION: 0,
  14175. Z_BEST_SPEED: 1,
  14176. Z_BEST_COMPRESSION: 9,
  14177. Z_DEFAULT_COMPRESSION: -1,
  14178. Z_FILTERED: 1,
  14179. Z_HUFFMAN_ONLY: 2,
  14180. Z_RLE: 3,
  14181. Z_FIXED: 4,
  14182. Z_DEFAULT_STRATEGY: 0,
  14183. /* Possible values of the data_type field (though see inflate()) */
  14184. Z_BINARY: 0,
  14185. Z_TEXT: 1,
  14186. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  14187. Z_UNKNOWN: 2,
  14188. /* The deflate compression method */
  14189. Z_DEFLATED: 8
  14190. //Z_NULL: null // Use -1 or null inline, depending on var type
  14191. };
  14192. },{}],56:[function(require,module,exports){
  14193. 'use strict';
  14194. // Note: we can't get significant speed boost here.
  14195. // So write code to minimize size - no pregenerated tables
  14196. // and array tools dependencies.
  14197. // Use ordinary array, since untyped makes no boost here
  14198. function makeTable() {
  14199. var c, table = [];
  14200. for (var n =0; n < 256; n++) {
  14201. c = n;
  14202. for (var k =0; k < 8; k++) {
  14203. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  14204. }
  14205. table[n] = c;
  14206. }
  14207. return table;
  14208. }
  14209. // Create table on load. Just 255 signed longs. Not a problem.
  14210. var crcTable = makeTable();
  14211. function crc32(crc, buf, len, pos) {
  14212. var t = crcTable,
  14213. end = pos + len;
  14214. crc = crc ^ (-1);
  14215. for (var i = pos; i < end; i++) {
  14216. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  14217. }
  14218. return (crc ^ (-1)); // >>> 0;
  14219. }
  14220. module.exports = crc32;
  14221. },{}],57:[function(require,module,exports){
  14222. 'use strict';
  14223. var utils = require('../utils/common');
  14224. var trees = require('./trees');
  14225. var adler32 = require('./adler32');
  14226. var crc32 = require('./crc32');
  14227. var msg = require('./messages');
  14228. /* Public constants ==========================================================*/
  14229. /* ===========================================================================*/
  14230. /* Allowed flush values; see deflate() and inflate() below for details */
  14231. var Z_NO_FLUSH = 0;
  14232. var Z_PARTIAL_FLUSH = 1;
  14233. //var Z_SYNC_FLUSH = 2;
  14234. var Z_FULL_FLUSH = 3;
  14235. var Z_FINISH = 4;
  14236. var Z_BLOCK = 5;
  14237. //var Z_TREES = 6;
  14238. /* Return codes for the compression/decompression functions. Negative values
  14239. * are errors, positive values are used for special but normal events.
  14240. */
  14241. var Z_OK = 0;
  14242. var Z_STREAM_END = 1;
  14243. //var Z_NEED_DICT = 2;
  14244. //var Z_ERRNO = -1;
  14245. var Z_STREAM_ERROR = -2;
  14246. var Z_DATA_ERROR = -3;
  14247. //var Z_MEM_ERROR = -4;
  14248. var Z_BUF_ERROR = -5;
  14249. //var Z_VERSION_ERROR = -6;
  14250. /* compression levels */
  14251. //var Z_NO_COMPRESSION = 0;
  14252. //var Z_BEST_SPEED = 1;
  14253. //var Z_BEST_COMPRESSION = 9;
  14254. var Z_DEFAULT_COMPRESSION = -1;
  14255. var Z_FILTERED = 1;
  14256. var Z_HUFFMAN_ONLY = 2;
  14257. var Z_RLE = 3;
  14258. var Z_FIXED = 4;
  14259. var Z_DEFAULT_STRATEGY = 0;
  14260. /* Possible values of the data_type field (though see inflate()) */
  14261. //var Z_BINARY = 0;
  14262. //var Z_TEXT = 1;
  14263. //var Z_ASCII = 1; // = Z_TEXT
  14264. var Z_UNKNOWN = 2;
  14265. /* The deflate compression method */
  14266. var Z_DEFLATED = 8;
  14267. /*============================================================================*/
  14268. var MAX_MEM_LEVEL = 9;
  14269. /* Maximum value for memLevel in deflateInit2 */
  14270. var MAX_WBITS = 15;
  14271. /* 32K LZ77 window */
  14272. var DEF_MEM_LEVEL = 8;
  14273. var LENGTH_CODES = 29;
  14274. /* number of length codes, not counting the special END_BLOCK code */
  14275. var LITERALS = 256;
  14276. /* number of literal bytes 0..255 */
  14277. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  14278. /* number of Literal or Length codes, including the END_BLOCK code */
  14279. var D_CODES = 30;
  14280. /* number of distance codes */
  14281. var BL_CODES = 19;
  14282. /* number of codes used to transfer the bit lengths */
  14283. var HEAP_SIZE = 2*L_CODES + 1;
  14284. /* maximum heap size */
  14285. var MAX_BITS = 15;
  14286. /* All codes must not exceed MAX_BITS bits */
  14287. var MIN_MATCH = 3;
  14288. var MAX_MATCH = 258;
  14289. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  14290. var PRESET_DICT = 0x20;
  14291. var INIT_STATE = 42;
  14292. var EXTRA_STATE = 69;
  14293. var NAME_STATE = 73;
  14294. var COMMENT_STATE = 91;
  14295. var HCRC_STATE = 103;
  14296. var BUSY_STATE = 113;
  14297. var FINISH_STATE = 666;
  14298. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  14299. var BS_BLOCK_DONE = 2; /* block flush performed */
  14300. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  14301. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  14302. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  14303. function err(strm, errorCode) {
  14304. strm.msg = msg[errorCode];
  14305. return errorCode;
  14306. }
  14307. function rank(f) {
  14308. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  14309. }
  14310. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  14311. /* =========================================================================
  14312. * Flush as much pending output as possible. All deflate() output goes
  14313. * through this function so some applications may wish to modify it
  14314. * to avoid allocating a large strm->output buffer and copying into it.
  14315. * (See also read_buf()).
  14316. */
  14317. function flush_pending(strm) {
  14318. var s = strm.state;
  14319. //_tr_flush_bits(s);
  14320. var len = s.pending;
  14321. if (len > strm.avail_out) {
  14322. len = strm.avail_out;
  14323. }
  14324. if (len === 0) { return; }
  14325. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  14326. strm.next_out += len;
  14327. s.pending_out += len;
  14328. strm.total_out += len;
  14329. strm.avail_out -= len;
  14330. s.pending -= len;
  14331. if (s.pending === 0) {
  14332. s.pending_out = 0;
  14333. }
  14334. }
  14335. function flush_block_only (s, last) {
  14336. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  14337. s.block_start = s.strstart;
  14338. flush_pending(s.strm);
  14339. }
  14340. function put_byte(s, b) {
  14341. s.pending_buf[s.pending++] = b;
  14342. }
  14343. /* =========================================================================
  14344. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  14345. * IN assertion: the stream state is correct and there is enough room in
  14346. * pending_buf.
  14347. */
  14348. function putShortMSB(s, b) {
  14349. // put_byte(s, (Byte)(b >> 8));
  14350. // put_byte(s, (Byte)(b & 0xff));
  14351. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  14352. s.pending_buf[s.pending++] = b & 0xff;
  14353. }
  14354. /* ===========================================================================
  14355. * Read a new buffer from the current input stream, update the adler32
  14356. * and total number of bytes read. All deflate() input goes through
  14357. * this function so some applications may wish to modify it to avoid
  14358. * allocating a large strm->input buffer and copying from it.
  14359. * (See also flush_pending()).
  14360. */
  14361. function read_buf(strm, buf, start, size) {
  14362. var len = strm.avail_in;
  14363. if (len > size) { len = size; }
  14364. if (len === 0) { return 0; }
  14365. strm.avail_in -= len;
  14366. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  14367. if (strm.state.wrap === 1) {
  14368. strm.adler = adler32(strm.adler, buf, len, start);
  14369. }
  14370. else if (strm.state.wrap === 2) {
  14371. strm.adler = crc32(strm.adler, buf, len, start);
  14372. }
  14373. strm.next_in += len;
  14374. strm.total_in += len;
  14375. return len;
  14376. }
  14377. /* ===========================================================================
  14378. * Set match_start to the longest match starting at the given string and
  14379. * return its length. Matches shorter or equal to prev_length are discarded,
  14380. * in which case the result is equal to prev_length and match_start is
  14381. * garbage.
  14382. * IN assertions: cur_match is the head of the hash chain for the current
  14383. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  14384. * OUT assertion: the match length is not greater than s->lookahead.
  14385. */
  14386. function longest_match(s, cur_match) {
  14387. var chain_length = s.max_chain_length; /* max hash chain length */
  14388. var scan = s.strstart; /* current string */
  14389. var match; /* matched string */
  14390. var len; /* length of current match */
  14391. var best_len = s.prev_length; /* best match length so far */
  14392. var nice_match = s.nice_match; /* stop if match long enough */
  14393. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  14394. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  14395. var _win = s.window; // shortcut
  14396. var wmask = s.w_mask;
  14397. var prev = s.prev;
  14398. /* Stop when cur_match becomes <= limit. To simplify the code,
  14399. * we prevent matches with the string of window index 0.
  14400. */
  14401. var strend = s.strstart + MAX_MATCH;
  14402. var scan_end1 = _win[scan + best_len - 1];
  14403. var scan_end = _win[scan + best_len];
  14404. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  14405. * It is easy to get rid of this optimization if necessary.
  14406. */
  14407. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  14408. /* Do not waste too much time if we already have a good match: */
  14409. if (s.prev_length >= s.good_match) {
  14410. chain_length >>= 2;
  14411. }
  14412. /* Do not look for matches beyond the end of the input. This is necessary
  14413. * to make deflate deterministic.
  14414. */
  14415. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  14416. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  14417. do {
  14418. // Assert(cur_match < s->strstart, "no future");
  14419. match = cur_match;
  14420. /* Skip to next match if the match length cannot increase
  14421. * or if the match length is less than 2. Note that the checks below
  14422. * for insufficient lookahead only occur occasionally for performance
  14423. * reasons. Therefore uninitialized memory will be accessed, and
  14424. * conditional jumps will be made that depend on those values.
  14425. * However the length of the match is limited to the lookahead, so
  14426. * the output of deflate is not affected by the uninitialized values.
  14427. */
  14428. if (_win[match + best_len] !== scan_end ||
  14429. _win[match + best_len - 1] !== scan_end1 ||
  14430. _win[match] !== _win[scan] ||
  14431. _win[++match] !== _win[scan + 1]) {
  14432. continue;
  14433. }
  14434. /* The check at best_len-1 can be removed because it will be made
  14435. * again later. (This heuristic is not always a win.)
  14436. * It is not necessary to compare scan[2] and match[2] since they
  14437. * are always equal when the other bytes match, given that
  14438. * the hash keys are equal and that HASH_BITS >= 8.
  14439. */
  14440. scan += 2;
  14441. match++;
  14442. // Assert(*scan == *match, "match[2]?");
  14443. /* We check for insufficient lookahead only every 8th comparison;
  14444. * the 256th check will be made at strstart+258.
  14445. */
  14446. do {
  14447. /*jshint noempty:false*/
  14448. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14449. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14450. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14451. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14452. scan < strend);
  14453. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  14454. len = MAX_MATCH - (strend - scan);
  14455. scan = strend - MAX_MATCH;
  14456. if (len > best_len) {
  14457. s.match_start = cur_match;
  14458. best_len = len;
  14459. if (len >= nice_match) {
  14460. break;
  14461. }
  14462. scan_end1 = _win[scan + best_len - 1];
  14463. scan_end = _win[scan + best_len];
  14464. }
  14465. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  14466. if (best_len <= s.lookahead) {
  14467. return best_len;
  14468. }
  14469. return s.lookahead;
  14470. }
  14471. /* ===========================================================================
  14472. * Fill the window when the lookahead becomes insufficient.
  14473. * Updates strstart and lookahead.
  14474. *
  14475. * IN assertion: lookahead < MIN_LOOKAHEAD
  14476. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  14477. * At least one byte has been read, or avail_in == 0; reads are
  14478. * performed for at least two bytes (required for the zip translate_eol
  14479. * option -- not supported here).
  14480. */
  14481. function fill_window(s) {
  14482. var _w_size = s.w_size;
  14483. var p, n, m, more, str;
  14484. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  14485. do {
  14486. more = s.window_size - s.lookahead - s.strstart;
  14487. // JS ints have 32 bit, block below not needed
  14488. /* Deal with !@#$% 64K limit: */
  14489. //if (sizeof(int) <= 2) {
  14490. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  14491. // more = wsize;
  14492. //
  14493. // } else if (more == (unsigned)(-1)) {
  14494. // /* Very unlikely, but possible on 16 bit machine if
  14495. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  14496. // */
  14497. // more--;
  14498. // }
  14499. //}
  14500. /* If the window is almost full and there is insufficient lookahead,
  14501. * move the upper half to the lower one to make room in the upper half.
  14502. */
  14503. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  14504. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  14505. s.match_start -= _w_size;
  14506. s.strstart -= _w_size;
  14507. /* we now have strstart >= MAX_DIST */
  14508. s.block_start -= _w_size;
  14509. /* Slide the hash table (could be avoided with 32 bit values
  14510. at the expense of memory usage). We slide even when level == 0
  14511. to keep the hash table consistent if we switch back to level > 0
  14512. later. (Using level 0 permanently is not an optimal usage of
  14513. zlib, so we don't care about this pathological case.)
  14514. */
  14515. n = s.hash_size;
  14516. p = n;
  14517. do {
  14518. m = s.head[--p];
  14519. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  14520. } while (--n);
  14521. n = _w_size;
  14522. p = n;
  14523. do {
  14524. m = s.prev[--p];
  14525. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  14526. /* If n is not on any hash chain, prev[n] is garbage but
  14527. * its value will never be used.
  14528. */
  14529. } while (--n);
  14530. more += _w_size;
  14531. }
  14532. if (s.strm.avail_in === 0) {
  14533. break;
  14534. }
  14535. /* If there was no sliding:
  14536. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  14537. * more == window_size - lookahead - strstart
  14538. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  14539. * => more >= window_size - 2*WSIZE + 2
  14540. * In the BIG_MEM or MMAP case (not yet supported),
  14541. * window_size == input_size + MIN_LOOKAHEAD &&
  14542. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  14543. * Otherwise, window_size == 2*WSIZE so more >= 2.
  14544. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  14545. */
  14546. //Assert(more >= 2, "more < 2");
  14547. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  14548. s.lookahead += n;
  14549. /* Initialize the hash value now that we have some input: */
  14550. if (s.lookahead + s.insert >= MIN_MATCH) {
  14551. str = s.strstart - s.insert;
  14552. s.ins_h = s.window[str];
  14553. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  14554. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  14555. //#if MIN_MATCH != 3
  14556. // Call update_hash() MIN_MATCH-3 more times
  14557. //#endif
  14558. while (s.insert) {
  14559. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  14560. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  14561. s.prev[str & s.w_mask] = s.head[s.ins_h];
  14562. s.head[s.ins_h] = str;
  14563. str++;
  14564. s.insert--;
  14565. if (s.lookahead + s.insert < MIN_MATCH) {
  14566. break;
  14567. }
  14568. }
  14569. }
  14570. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  14571. * but this is not important since only literal bytes will be emitted.
  14572. */
  14573. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  14574. /* If the WIN_INIT bytes after the end of the current data have never been
  14575. * written, then zero those bytes in order to avoid memory check reports of
  14576. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  14577. * the longest match routines. Update the high water mark for the next
  14578. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  14579. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  14580. */
  14581. // if (s.high_water < s.window_size) {
  14582. // var curr = s.strstart + s.lookahead;
  14583. // var init = 0;
  14584. //
  14585. // if (s.high_water < curr) {
  14586. // /* Previous high water mark below current data -- zero WIN_INIT
  14587. // * bytes or up to end of window, whichever is less.
  14588. // */
  14589. // init = s.window_size - curr;
  14590. // if (init > WIN_INIT)
  14591. // init = WIN_INIT;
  14592. // zmemzero(s->window + curr, (unsigned)init);
  14593. // s->high_water = curr + init;
  14594. // }
  14595. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  14596. // /* High water mark at or above current data, but below current data
  14597. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  14598. // * to end of window, whichever is less.
  14599. // */
  14600. // init = (ulg)curr + WIN_INIT - s->high_water;
  14601. // if (init > s->window_size - s->high_water)
  14602. // init = s->window_size - s->high_water;
  14603. // zmemzero(s->window + s->high_water, (unsigned)init);
  14604. // s->high_water += init;
  14605. // }
  14606. // }
  14607. //
  14608. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  14609. // "not enough room for search");
  14610. }
  14611. /* ===========================================================================
  14612. * Copy without compression as much as possible from the input stream, return
  14613. * the current block state.
  14614. * This function does not insert new strings in the dictionary since
  14615. * uncompressible data is probably not useful. This function is used
  14616. * only for the level=0 compression option.
  14617. * NOTE: this function should be optimized to avoid extra copying from
  14618. * window to pending_buf.
  14619. */
  14620. function deflate_stored(s, flush) {
  14621. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  14622. * to pending_buf_size, and each stored block has a 5 byte header:
  14623. */
  14624. var max_block_size = 0xffff;
  14625. if (max_block_size > s.pending_buf_size - 5) {
  14626. max_block_size = s.pending_buf_size - 5;
  14627. }
  14628. /* Copy as much as possible from input to output: */
  14629. for (;;) {
  14630. /* Fill the window as much as possible: */
  14631. if (s.lookahead <= 1) {
  14632. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  14633. // s->block_start >= (long)s->w_size, "slide too late");
  14634. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  14635. // s.block_start >= s.w_size)) {
  14636. // throw new Error("slide too late");
  14637. // }
  14638. fill_window(s);
  14639. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  14640. return BS_NEED_MORE;
  14641. }
  14642. if (s.lookahead === 0) {
  14643. break;
  14644. }
  14645. /* flush the current block */
  14646. }
  14647. //Assert(s->block_start >= 0L, "block gone");
  14648. // if (s.block_start < 0) throw new Error("block gone");
  14649. s.strstart += s.lookahead;
  14650. s.lookahead = 0;
  14651. /* Emit a stored block if pending_buf will be full: */
  14652. var max_start = s.block_start + max_block_size;
  14653. if (s.strstart === 0 || s.strstart >= max_start) {
  14654. /* strstart == 0 is possible when wraparound on 16-bit machine */
  14655. s.lookahead = s.strstart - max_start;
  14656. s.strstart = max_start;
  14657. /*** FLUSH_BLOCK(s, 0); ***/
  14658. flush_block_only(s, false);
  14659. if (s.strm.avail_out === 0) {
  14660. return BS_NEED_MORE;
  14661. }
  14662. /***/
  14663. }
  14664. /* Flush if we may have to slide, otherwise block_start may become
  14665. * negative and the data will be gone:
  14666. */
  14667. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  14668. /*** FLUSH_BLOCK(s, 0); ***/
  14669. flush_block_only(s, false);
  14670. if (s.strm.avail_out === 0) {
  14671. return BS_NEED_MORE;
  14672. }
  14673. /***/
  14674. }
  14675. }
  14676. s.insert = 0;
  14677. if (flush === Z_FINISH) {
  14678. /*** FLUSH_BLOCK(s, 1); ***/
  14679. flush_block_only(s, true);
  14680. if (s.strm.avail_out === 0) {
  14681. return BS_FINISH_STARTED;
  14682. }
  14683. /***/
  14684. return BS_FINISH_DONE;
  14685. }
  14686. if (s.strstart > s.block_start) {
  14687. /*** FLUSH_BLOCK(s, 0); ***/
  14688. flush_block_only(s, false);
  14689. if (s.strm.avail_out === 0) {
  14690. return BS_NEED_MORE;
  14691. }
  14692. /***/
  14693. }
  14694. return BS_NEED_MORE;
  14695. }
  14696. /* ===========================================================================
  14697. * Compress as much as possible from the input stream, return the current
  14698. * block state.
  14699. * This function does not perform lazy evaluation of matches and inserts
  14700. * new strings in the dictionary only for unmatched strings or for short
  14701. * matches. It is used only for the fast compression options.
  14702. */
  14703. function deflate_fast(s, flush) {
  14704. var hash_head; /* head of the hash chain */
  14705. var bflush; /* set if current block must be flushed */
  14706. for (;;) {
  14707. /* Make sure that we always have enough lookahead, except
  14708. * at the end of the input file. We need MAX_MATCH bytes
  14709. * for the next match, plus MIN_MATCH bytes to insert the
  14710. * string following the next match.
  14711. */
  14712. if (s.lookahead < MIN_LOOKAHEAD) {
  14713. fill_window(s);
  14714. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  14715. return BS_NEED_MORE;
  14716. }
  14717. if (s.lookahead === 0) {
  14718. break; /* flush the current block */
  14719. }
  14720. }
  14721. /* Insert the string window[strstart .. strstart+2] in the
  14722. * dictionary, and set hash_head to the head of the hash chain:
  14723. */
  14724. hash_head = 0/*NIL*/;
  14725. if (s.lookahead >= MIN_MATCH) {
  14726. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14727. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14728. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14729. s.head[s.ins_h] = s.strstart;
  14730. /***/
  14731. }
  14732. /* Find the longest match, discarding those <= prev_length.
  14733. * At this point we have always match_length < MIN_MATCH
  14734. */
  14735. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  14736. /* To simplify the code, we prevent matches with the string
  14737. * of window index 0 (in particular we have to avoid a match
  14738. * of the string with itself at the start of the input file).
  14739. */
  14740. s.match_length = longest_match(s, hash_head);
  14741. /* longest_match() sets match_start */
  14742. }
  14743. if (s.match_length >= MIN_MATCH) {
  14744. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  14745. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  14746. s.match_length - MIN_MATCH, bflush); ***/
  14747. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  14748. s.lookahead -= s.match_length;
  14749. /* Insert new strings in the hash table only if the match length
  14750. * is not too large. This saves time but degrades compression.
  14751. */
  14752. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  14753. s.match_length--; /* string at strstart already in table */
  14754. do {
  14755. s.strstart++;
  14756. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14757. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14758. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14759. s.head[s.ins_h] = s.strstart;
  14760. /***/
  14761. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  14762. * always MIN_MATCH bytes ahead.
  14763. */
  14764. } while (--s.match_length !== 0);
  14765. s.strstart++;
  14766. } else
  14767. {
  14768. s.strstart += s.match_length;
  14769. s.match_length = 0;
  14770. s.ins_h = s.window[s.strstart];
  14771. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  14772. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  14773. //#if MIN_MATCH != 3
  14774. // Call UPDATE_HASH() MIN_MATCH-3 more times
  14775. //#endif
  14776. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  14777. * matter since it will be recomputed at next deflate call.
  14778. */
  14779. }
  14780. } else {
  14781. /* No match, output a literal byte */
  14782. //Tracevv((stderr,"%c", s.window[s.strstart]));
  14783. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14784. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14785. s.lookahead--;
  14786. s.strstart++;
  14787. }
  14788. if (bflush) {
  14789. /*** FLUSH_BLOCK(s, 0); ***/
  14790. flush_block_only(s, false);
  14791. if (s.strm.avail_out === 0) {
  14792. return BS_NEED_MORE;
  14793. }
  14794. /***/
  14795. }
  14796. }
  14797. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  14798. if (flush === Z_FINISH) {
  14799. /*** FLUSH_BLOCK(s, 1); ***/
  14800. flush_block_only(s, true);
  14801. if (s.strm.avail_out === 0) {
  14802. return BS_FINISH_STARTED;
  14803. }
  14804. /***/
  14805. return BS_FINISH_DONE;
  14806. }
  14807. if (s.last_lit) {
  14808. /*** FLUSH_BLOCK(s, 0); ***/
  14809. flush_block_only(s, false);
  14810. if (s.strm.avail_out === 0) {
  14811. return BS_NEED_MORE;
  14812. }
  14813. /***/
  14814. }
  14815. return BS_BLOCK_DONE;
  14816. }
  14817. /* ===========================================================================
  14818. * Same as above, but achieves better compression. We use a lazy
  14819. * evaluation for matches: a match is finally adopted only if there is
  14820. * no better match at the next window position.
  14821. */
  14822. function deflate_slow(s, flush) {
  14823. var hash_head; /* head of hash chain */
  14824. var bflush; /* set if current block must be flushed */
  14825. var max_insert;
  14826. /* Process the input block. */
  14827. for (;;) {
  14828. /* Make sure that we always have enough lookahead, except
  14829. * at the end of the input file. We need MAX_MATCH bytes
  14830. * for the next match, plus MIN_MATCH bytes to insert the
  14831. * string following the next match.
  14832. */
  14833. if (s.lookahead < MIN_LOOKAHEAD) {
  14834. fill_window(s);
  14835. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  14836. return BS_NEED_MORE;
  14837. }
  14838. if (s.lookahead === 0) { break; } /* flush the current block */
  14839. }
  14840. /* Insert the string window[strstart .. strstart+2] in the
  14841. * dictionary, and set hash_head to the head of the hash chain:
  14842. */
  14843. hash_head = 0/*NIL*/;
  14844. if (s.lookahead >= MIN_MATCH) {
  14845. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14846. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14847. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14848. s.head[s.ins_h] = s.strstart;
  14849. /***/
  14850. }
  14851. /* Find the longest match, discarding those <= prev_length.
  14852. */
  14853. s.prev_length = s.match_length;
  14854. s.prev_match = s.match_start;
  14855. s.match_length = MIN_MATCH-1;
  14856. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  14857. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  14858. /* To simplify the code, we prevent matches with the string
  14859. * of window index 0 (in particular we have to avoid a match
  14860. * of the string with itself at the start of the input file).
  14861. */
  14862. s.match_length = longest_match(s, hash_head);
  14863. /* longest_match() sets match_start */
  14864. if (s.match_length <= 5 &&
  14865. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  14866. /* If prev_match is also MIN_MATCH, match_start is garbage
  14867. * but we will ignore the current match anyway.
  14868. */
  14869. s.match_length = MIN_MATCH-1;
  14870. }
  14871. }
  14872. /* If there was a match at the previous step and the current
  14873. * match is not better, output the previous match:
  14874. */
  14875. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  14876. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  14877. /* Do not insert strings in hash table beyond this. */
  14878. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  14879. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  14880. s.prev_length - MIN_MATCH, bflush);***/
  14881. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  14882. /* Insert in hash table all strings up to the end of the match.
  14883. * strstart-1 and strstart are already inserted. If there is not
  14884. * enough lookahead, the last two strings are not inserted in
  14885. * the hash table.
  14886. */
  14887. s.lookahead -= s.prev_length-1;
  14888. s.prev_length -= 2;
  14889. do {
  14890. if (++s.strstart <= max_insert) {
  14891. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14892. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14893. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14894. s.head[s.ins_h] = s.strstart;
  14895. /***/
  14896. }
  14897. } while (--s.prev_length !== 0);
  14898. s.match_available = 0;
  14899. s.match_length = MIN_MATCH-1;
  14900. s.strstart++;
  14901. if (bflush) {
  14902. /*** FLUSH_BLOCK(s, 0); ***/
  14903. flush_block_only(s, false);
  14904. if (s.strm.avail_out === 0) {
  14905. return BS_NEED_MORE;
  14906. }
  14907. /***/
  14908. }
  14909. } else if (s.match_available) {
  14910. /* If there was no match at the previous position, output a
  14911. * single literal. If there was a match but the current match
  14912. * is longer, truncate the previous match to a single literal.
  14913. */
  14914. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  14915. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  14916. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  14917. if (bflush) {
  14918. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  14919. flush_block_only(s, false);
  14920. /***/
  14921. }
  14922. s.strstart++;
  14923. s.lookahead--;
  14924. if (s.strm.avail_out === 0) {
  14925. return BS_NEED_MORE;
  14926. }
  14927. } else {
  14928. /* There is no previous match to compare with, wait for
  14929. * the next step to decide.
  14930. */
  14931. s.match_available = 1;
  14932. s.strstart++;
  14933. s.lookahead--;
  14934. }
  14935. }
  14936. //Assert (flush != Z_NO_FLUSH, "no flush?");
  14937. if (s.match_available) {
  14938. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  14939. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  14940. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  14941. s.match_available = 0;
  14942. }
  14943. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  14944. if (flush === Z_FINISH) {
  14945. /*** FLUSH_BLOCK(s, 1); ***/
  14946. flush_block_only(s, true);
  14947. if (s.strm.avail_out === 0) {
  14948. return BS_FINISH_STARTED;
  14949. }
  14950. /***/
  14951. return BS_FINISH_DONE;
  14952. }
  14953. if (s.last_lit) {
  14954. /*** FLUSH_BLOCK(s, 0); ***/
  14955. flush_block_only(s, false);
  14956. if (s.strm.avail_out === 0) {
  14957. return BS_NEED_MORE;
  14958. }
  14959. /***/
  14960. }
  14961. return BS_BLOCK_DONE;
  14962. }
  14963. /* ===========================================================================
  14964. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  14965. * one. Do not maintain a hash table. (It will be regenerated if this run of
  14966. * deflate switches away from Z_RLE.)
  14967. */
  14968. function deflate_rle(s, flush) {
  14969. var bflush; /* set if current block must be flushed */
  14970. var prev; /* byte at distance one to match */
  14971. var scan, strend; /* scan goes up to strend for length of run */
  14972. var _win = s.window;
  14973. for (;;) {
  14974. /* Make sure that we always have enough lookahead, except
  14975. * at the end of the input file. We need MAX_MATCH bytes
  14976. * for the longest run, plus one for the unrolled loop.
  14977. */
  14978. if (s.lookahead <= MAX_MATCH) {
  14979. fill_window(s);
  14980. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  14981. return BS_NEED_MORE;
  14982. }
  14983. if (s.lookahead === 0) { break; } /* flush the current block */
  14984. }
  14985. /* See how many times the previous byte repeats */
  14986. s.match_length = 0;
  14987. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  14988. scan = s.strstart - 1;
  14989. prev = _win[scan];
  14990. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  14991. strend = s.strstart + MAX_MATCH;
  14992. do {
  14993. /*jshint noempty:false*/
  14994. } while (prev === _win[++scan] && prev === _win[++scan] &&
  14995. prev === _win[++scan] && prev === _win[++scan] &&
  14996. prev === _win[++scan] && prev === _win[++scan] &&
  14997. prev === _win[++scan] && prev === _win[++scan] &&
  14998. scan < strend);
  14999. s.match_length = MAX_MATCH - (strend - scan);
  15000. if (s.match_length > s.lookahead) {
  15001. s.match_length = s.lookahead;
  15002. }
  15003. }
  15004. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  15005. }
  15006. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  15007. if (s.match_length >= MIN_MATCH) {
  15008. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  15009. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  15010. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  15011. s.lookahead -= s.match_length;
  15012. s.strstart += s.match_length;
  15013. s.match_length = 0;
  15014. } else {
  15015. /* No match, output a literal byte */
  15016. //Tracevv((stderr,"%c", s->window[s->strstart]));
  15017. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  15018. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  15019. s.lookahead--;
  15020. s.strstart++;
  15021. }
  15022. if (bflush) {
  15023. /*** FLUSH_BLOCK(s, 0); ***/
  15024. flush_block_only(s, false);
  15025. if (s.strm.avail_out === 0) {
  15026. return BS_NEED_MORE;
  15027. }
  15028. /***/
  15029. }
  15030. }
  15031. s.insert = 0;
  15032. if (flush === Z_FINISH) {
  15033. /*** FLUSH_BLOCK(s, 1); ***/
  15034. flush_block_only(s, true);
  15035. if (s.strm.avail_out === 0) {
  15036. return BS_FINISH_STARTED;
  15037. }
  15038. /***/
  15039. return BS_FINISH_DONE;
  15040. }
  15041. if (s.last_lit) {
  15042. /*** FLUSH_BLOCK(s, 0); ***/
  15043. flush_block_only(s, false);
  15044. if (s.strm.avail_out === 0) {
  15045. return BS_NEED_MORE;
  15046. }
  15047. /***/
  15048. }
  15049. return BS_BLOCK_DONE;
  15050. }
  15051. /* ===========================================================================
  15052. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  15053. * (It will be regenerated if this run of deflate switches away from Huffman.)
  15054. */
  15055. function deflate_huff(s, flush) {
  15056. var bflush; /* set if current block must be flushed */
  15057. for (;;) {
  15058. /* Make sure that we have a literal to write. */
  15059. if (s.lookahead === 0) {
  15060. fill_window(s);
  15061. if (s.lookahead === 0) {
  15062. if (flush === Z_NO_FLUSH) {
  15063. return BS_NEED_MORE;
  15064. }
  15065. break; /* flush the current block */
  15066. }
  15067. }
  15068. /* Output a literal byte */
  15069. s.match_length = 0;
  15070. //Tracevv((stderr,"%c", s->window[s->strstart]));
  15071. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  15072. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  15073. s.lookahead--;
  15074. s.strstart++;
  15075. if (bflush) {
  15076. /*** FLUSH_BLOCK(s, 0); ***/
  15077. flush_block_only(s, false);
  15078. if (s.strm.avail_out === 0) {
  15079. return BS_NEED_MORE;
  15080. }
  15081. /***/
  15082. }
  15083. }
  15084. s.insert = 0;
  15085. if (flush === Z_FINISH) {
  15086. /*** FLUSH_BLOCK(s, 1); ***/
  15087. flush_block_only(s, true);
  15088. if (s.strm.avail_out === 0) {
  15089. return BS_FINISH_STARTED;
  15090. }
  15091. /***/
  15092. return BS_FINISH_DONE;
  15093. }
  15094. if (s.last_lit) {
  15095. /*** FLUSH_BLOCK(s, 0); ***/
  15096. flush_block_only(s, false);
  15097. if (s.strm.avail_out === 0) {
  15098. return BS_NEED_MORE;
  15099. }
  15100. /***/
  15101. }
  15102. return BS_BLOCK_DONE;
  15103. }
  15104. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  15105. * the desired pack level (0..9). The values given below have been tuned to
  15106. * exclude worst case performance for pathological files. Better values may be
  15107. * found for specific files.
  15108. */
  15109. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  15110. this.good_length = good_length;
  15111. this.max_lazy = max_lazy;
  15112. this.nice_length = nice_length;
  15113. this.max_chain = max_chain;
  15114. this.func = func;
  15115. };
  15116. var configuration_table;
  15117. configuration_table = [
  15118. /* good lazy nice chain */
  15119. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  15120. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  15121. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  15122. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  15123. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  15124. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  15125. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  15126. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  15127. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  15128. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  15129. ];
  15130. /* ===========================================================================
  15131. * Initialize the "longest match" routines for a new zlib stream
  15132. */
  15133. function lm_init(s) {
  15134. s.window_size = 2 * s.w_size;
  15135. /*** CLEAR_HASH(s); ***/
  15136. zero(s.head); // Fill with NIL (= 0);
  15137. /* Set the default configuration parameters:
  15138. */
  15139. s.max_lazy_match = configuration_table[s.level].max_lazy;
  15140. s.good_match = configuration_table[s.level].good_length;
  15141. s.nice_match = configuration_table[s.level].nice_length;
  15142. s.max_chain_length = configuration_table[s.level].max_chain;
  15143. s.strstart = 0;
  15144. s.block_start = 0;
  15145. s.lookahead = 0;
  15146. s.insert = 0;
  15147. s.match_length = s.prev_length = MIN_MATCH - 1;
  15148. s.match_available = 0;
  15149. s.ins_h = 0;
  15150. }
  15151. function DeflateState() {
  15152. this.strm = null; /* pointer back to this zlib stream */
  15153. this.status = 0; /* as the name implies */
  15154. this.pending_buf = null; /* output still pending */
  15155. this.pending_buf_size = 0; /* size of pending_buf */
  15156. this.pending_out = 0; /* next pending byte to output to the stream */
  15157. this.pending = 0; /* nb of bytes in the pending buffer */
  15158. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  15159. this.gzhead = null; /* gzip header information to write */
  15160. this.gzindex = 0; /* where in extra, name, or comment */
  15161. this.method = Z_DEFLATED; /* can only be DEFLATED */
  15162. this.last_flush = -1; /* value of flush param for previous deflate call */
  15163. this.w_size = 0; /* LZ77 window size (32K by default) */
  15164. this.w_bits = 0; /* log2(w_size) (8..16) */
  15165. this.w_mask = 0; /* w_size - 1 */
  15166. this.window = null;
  15167. /* Sliding window. Input bytes are read into the second half of the window,
  15168. * and move to the first half later to keep a dictionary of at least wSize
  15169. * bytes. With this organization, matches are limited to a distance of
  15170. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  15171. * performed with a length multiple of the block size.
  15172. */
  15173. this.window_size = 0;
  15174. /* Actual size of window: 2*wSize, except when the user input buffer
  15175. * is directly used as sliding window.
  15176. */
  15177. this.prev = null;
  15178. /* Link to older string with same hash index. To limit the size of this
  15179. * array to 64K, this link is maintained only for the last 32K strings.
  15180. * An index in this array is thus a window index modulo 32K.
  15181. */
  15182. this.head = null; /* Heads of the hash chains or NIL. */
  15183. this.ins_h = 0; /* hash index of string to be inserted */
  15184. this.hash_size = 0; /* number of elements in hash table */
  15185. this.hash_bits = 0; /* log2(hash_size) */
  15186. this.hash_mask = 0; /* hash_size-1 */
  15187. this.hash_shift = 0;
  15188. /* Number of bits by which ins_h must be shifted at each input
  15189. * step. It must be such that after MIN_MATCH steps, the oldest
  15190. * byte no longer takes part in the hash key, that is:
  15191. * hash_shift * MIN_MATCH >= hash_bits
  15192. */
  15193. this.block_start = 0;
  15194. /* Window position at the beginning of the current output block. Gets
  15195. * negative when the window is moved backwards.
  15196. */
  15197. this.match_length = 0; /* length of best match */
  15198. this.prev_match = 0; /* previous match */
  15199. this.match_available = 0; /* set if previous match exists */
  15200. this.strstart = 0; /* start of string to insert */
  15201. this.match_start = 0; /* start of matching string */
  15202. this.lookahead = 0; /* number of valid bytes ahead in window */
  15203. this.prev_length = 0;
  15204. /* Length of the best match at previous step. Matches not greater than this
  15205. * are discarded. This is used in the lazy match evaluation.
  15206. */
  15207. this.max_chain_length = 0;
  15208. /* To speed up deflation, hash chains are never searched beyond this
  15209. * length. A higher limit improves compression ratio but degrades the
  15210. * speed.
  15211. */
  15212. this.max_lazy_match = 0;
  15213. /* Attempt to find a better match only when the current match is strictly
  15214. * smaller than this value. This mechanism is used only for compression
  15215. * levels >= 4.
  15216. */
  15217. // That's alias to max_lazy_match, don't use directly
  15218. //this.max_insert_length = 0;
  15219. /* Insert new strings in the hash table only if the match length is not
  15220. * greater than this length. This saves time but degrades compression.
  15221. * max_insert_length is used only for compression levels <= 3.
  15222. */
  15223. this.level = 0; /* compression level (1..9) */
  15224. this.strategy = 0; /* favor or force Huffman coding*/
  15225. this.good_match = 0;
  15226. /* Use a faster search when the previous match is longer than this */
  15227. this.nice_match = 0; /* Stop searching when current match exceeds this */
  15228. /* used by trees.c: */
  15229. /* Didn't use ct_data typedef below to suppress compiler warning */
  15230. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  15231. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  15232. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  15233. // Use flat array of DOUBLE size, with interleaved fata,
  15234. // because JS does not support effective
  15235. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  15236. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  15237. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  15238. zero(this.dyn_ltree);
  15239. zero(this.dyn_dtree);
  15240. zero(this.bl_tree);
  15241. this.l_desc = null; /* desc. for literal tree */
  15242. this.d_desc = null; /* desc. for distance tree */
  15243. this.bl_desc = null; /* desc. for bit length tree */
  15244. //ush bl_count[MAX_BITS+1];
  15245. this.bl_count = new utils.Buf16(MAX_BITS+1);
  15246. /* number of codes at each bit length for an optimal tree */
  15247. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  15248. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  15249. zero(this.heap);
  15250. this.heap_len = 0; /* number of elements in the heap */
  15251. this.heap_max = 0; /* element of largest frequency */
  15252. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  15253. * The same heap array is used to build all trees.
  15254. */
  15255. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  15256. zero(this.depth);
  15257. /* Depth of each subtree used as tie breaker for trees of equal frequency
  15258. */
  15259. this.l_buf = 0; /* buffer index for literals or lengths */
  15260. this.lit_bufsize = 0;
  15261. /* Size of match buffer for literals/lengths. There are 4 reasons for
  15262. * limiting lit_bufsize to 64K:
  15263. * - frequencies can be kept in 16 bit counters
  15264. * - if compression is not successful for the first block, all input
  15265. * data is still in the window so we can still emit a stored block even
  15266. * when input comes from standard input. (This can also be done for
  15267. * all blocks if lit_bufsize is not greater than 32K.)
  15268. * - if compression is not successful for a file smaller than 64K, we can
  15269. * even emit a stored file instead of a stored block (saving 5 bytes).
  15270. * This is applicable only for zip (not gzip or zlib).
  15271. * - creating new Huffman trees less frequently may not provide fast
  15272. * adaptation to changes in the input data statistics. (Take for
  15273. * example a binary file with poorly compressible code followed by
  15274. * a highly compressible string table.) Smaller buffer sizes give
  15275. * fast adaptation but have of course the overhead of transmitting
  15276. * trees more frequently.
  15277. * - I can't count above 4
  15278. */
  15279. this.last_lit = 0; /* running index in l_buf */
  15280. this.d_buf = 0;
  15281. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  15282. * the same number of elements. To use different lengths, an extra flag
  15283. * array would be necessary.
  15284. */
  15285. this.opt_len = 0; /* bit length of current block with optimal trees */
  15286. this.static_len = 0; /* bit length of current block with static trees */
  15287. this.matches = 0; /* number of string matches in current block */
  15288. this.insert = 0; /* bytes at end of window left to insert */
  15289. this.bi_buf = 0;
  15290. /* Output buffer. bits are inserted starting at the bottom (least
  15291. * significant bits).
  15292. */
  15293. this.bi_valid = 0;
  15294. /* Number of valid bits in bi_buf. All bits above the last valid bit
  15295. * are always zero.
  15296. */
  15297. // Used for window memory init. We safely ignore it for JS. That makes
  15298. // sense only for pointers and memory check tools.
  15299. //this.high_water = 0;
  15300. /* High water mark offset in window for initialized bytes -- bytes above
  15301. * this are set to zero in order to avoid memory check warnings when
  15302. * longest match routines access bytes past the input. This is then
  15303. * updated to the new high water mark.
  15304. */
  15305. }
  15306. function deflateResetKeep(strm) {
  15307. var s;
  15308. if (!strm || !strm.state) {
  15309. return err(strm, Z_STREAM_ERROR);
  15310. }
  15311. strm.total_in = strm.total_out = 0;
  15312. strm.data_type = Z_UNKNOWN;
  15313. s = strm.state;
  15314. s.pending = 0;
  15315. s.pending_out = 0;
  15316. if (s.wrap < 0) {
  15317. s.wrap = -s.wrap;
  15318. /* was made negative by deflate(..., Z_FINISH); */
  15319. }
  15320. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  15321. strm.adler = (s.wrap === 2) ?
  15322. 0 // crc32(0, Z_NULL, 0)
  15323. :
  15324. 1; // adler32(0, Z_NULL, 0)
  15325. s.last_flush = Z_NO_FLUSH;
  15326. trees._tr_init(s);
  15327. return Z_OK;
  15328. }
  15329. function deflateReset(strm) {
  15330. var ret = deflateResetKeep(strm);
  15331. if (ret === Z_OK) {
  15332. lm_init(strm.state);
  15333. }
  15334. return ret;
  15335. }
  15336. function deflateSetHeader(strm, head) {
  15337. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15338. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  15339. strm.state.gzhead = head;
  15340. return Z_OK;
  15341. }
  15342. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  15343. if (!strm) { // === Z_NULL
  15344. return Z_STREAM_ERROR;
  15345. }
  15346. var wrap = 1;
  15347. if (level === Z_DEFAULT_COMPRESSION) {
  15348. level = 6;
  15349. }
  15350. if (windowBits < 0) { /* suppress zlib wrapper */
  15351. wrap = 0;
  15352. windowBits = -windowBits;
  15353. }
  15354. else if (windowBits > 15) {
  15355. wrap = 2; /* write gzip wrapper instead */
  15356. windowBits -= 16;
  15357. }
  15358. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  15359. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  15360. strategy < 0 || strategy > Z_FIXED) {
  15361. return err(strm, Z_STREAM_ERROR);
  15362. }
  15363. if (windowBits === 8) {
  15364. windowBits = 9;
  15365. }
  15366. /* until 256-byte window bug fixed */
  15367. var s = new DeflateState();
  15368. strm.state = s;
  15369. s.strm = strm;
  15370. s.wrap = wrap;
  15371. s.gzhead = null;
  15372. s.w_bits = windowBits;
  15373. s.w_size = 1 << s.w_bits;
  15374. s.w_mask = s.w_size - 1;
  15375. s.hash_bits = memLevel + 7;
  15376. s.hash_size = 1 << s.hash_bits;
  15377. s.hash_mask = s.hash_size - 1;
  15378. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  15379. s.window = new utils.Buf8(s.w_size * 2);
  15380. s.head = new utils.Buf16(s.hash_size);
  15381. s.prev = new utils.Buf16(s.w_size);
  15382. // Don't need mem init magic for JS.
  15383. //s.high_water = 0; /* nothing written to s->window yet */
  15384. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  15385. s.pending_buf_size = s.lit_bufsize * 4;
  15386. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  15387. s.d_buf = s.lit_bufsize >> 1;
  15388. s.l_buf = (1 + 2) * s.lit_bufsize;
  15389. s.level = level;
  15390. s.strategy = strategy;
  15391. s.method = method;
  15392. return deflateReset(strm);
  15393. }
  15394. function deflateInit(strm, level) {
  15395. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  15396. }
  15397. function deflate(strm, flush) {
  15398. var old_flush, s;
  15399. var beg, val; // for gzip header write only
  15400. if (!strm || !strm.state ||
  15401. flush > Z_BLOCK || flush < 0) {
  15402. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  15403. }
  15404. s = strm.state;
  15405. if (!strm.output ||
  15406. (!strm.input && strm.avail_in !== 0) ||
  15407. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  15408. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  15409. }
  15410. s.strm = strm; /* just in case */
  15411. old_flush = s.last_flush;
  15412. s.last_flush = flush;
  15413. /* Write the header */
  15414. if (s.status === INIT_STATE) {
  15415. if (s.wrap === 2) { // GZIP header
  15416. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  15417. put_byte(s, 31);
  15418. put_byte(s, 139);
  15419. put_byte(s, 8);
  15420. if (!s.gzhead) { // s->gzhead == Z_NULL
  15421. put_byte(s, 0);
  15422. put_byte(s, 0);
  15423. put_byte(s, 0);
  15424. put_byte(s, 0);
  15425. put_byte(s, 0);
  15426. put_byte(s, s.level === 9 ? 2 :
  15427. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  15428. 4 : 0));
  15429. put_byte(s, OS_CODE);
  15430. s.status = BUSY_STATE;
  15431. }
  15432. else {
  15433. put_byte(s, (s.gzhead.text ? 1 : 0) +
  15434. (s.gzhead.hcrc ? 2 : 0) +
  15435. (!s.gzhead.extra ? 0 : 4) +
  15436. (!s.gzhead.name ? 0 : 8) +
  15437. (!s.gzhead.comment ? 0 : 16)
  15438. );
  15439. put_byte(s, s.gzhead.time & 0xff);
  15440. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  15441. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  15442. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  15443. put_byte(s, s.level === 9 ? 2 :
  15444. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  15445. 4 : 0));
  15446. put_byte(s, s.gzhead.os & 0xff);
  15447. if (s.gzhead.extra && s.gzhead.extra.length) {
  15448. put_byte(s, s.gzhead.extra.length & 0xff);
  15449. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  15450. }
  15451. if (s.gzhead.hcrc) {
  15452. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  15453. }
  15454. s.gzindex = 0;
  15455. s.status = EXTRA_STATE;
  15456. }
  15457. }
  15458. else // DEFLATE header
  15459. {
  15460. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  15461. var level_flags = -1;
  15462. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  15463. level_flags = 0;
  15464. } else if (s.level < 6) {
  15465. level_flags = 1;
  15466. } else if (s.level === 6) {
  15467. level_flags = 2;
  15468. } else {
  15469. level_flags = 3;
  15470. }
  15471. header |= (level_flags << 6);
  15472. if (s.strstart !== 0) { header |= PRESET_DICT; }
  15473. header += 31 - (header % 31);
  15474. s.status = BUSY_STATE;
  15475. putShortMSB(s, header);
  15476. /* Save the adler32 of the preset dictionary: */
  15477. if (s.strstart !== 0) {
  15478. putShortMSB(s, strm.adler >>> 16);
  15479. putShortMSB(s, strm.adler & 0xffff);
  15480. }
  15481. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  15482. }
  15483. }
  15484. //#ifdef GZIP
  15485. if (s.status === EXTRA_STATE) {
  15486. if (s.gzhead.extra/* != Z_NULL*/) {
  15487. beg = s.pending; /* start of bytes to update crc */
  15488. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  15489. if (s.pending === s.pending_buf_size) {
  15490. if (s.gzhead.hcrc && s.pending > beg) {
  15491. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15492. }
  15493. flush_pending(strm);
  15494. beg = s.pending;
  15495. if (s.pending === s.pending_buf_size) {
  15496. break;
  15497. }
  15498. }
  15499. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  15500. s.gzindex++;
  15501. }
  15502. if (s.gzhead.hcrc && s.pending > beg) {
  15503. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15504. }
  15505. if (s.gzindex === s.gzhead.extra.length) {
  15506. s.gzindex = 0;
  15507. s.status = NAME_STATE;
  15508. }
  15509. }
  15510. else {
  15511. s.status = NAME_STATE;
  15512. }
  15513. }
  15514. if (s.status === NAME_STATE) {
  15515. if (s.gzhead.name/* != Z_NULL*/) {
  15516. beg = s.pending; /* start of bytes to update crc */
  15517. //int val;
  15518. do {
  15519. if (s.pending === s.pending_buf_size) {
  15520. if (s.gzhead.hcrc && s.pending > beg) {
  15521. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15522. }
  15523. flush_pending(strm);
  15524. beg = s.pending;
  15525. if (s.pending === s.pending_buf_size) {
  15526. val = 1;
  15527. break;
  15528. }
  15529. }
  15530. // JS specific: little magic to add zero terminator to end of string
  15531. if (s.gzindex < s.gzhead.name.length) {
  15532. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  15533. } else {
  15534. val = 0;
  15535. }
  15536. put_byte(s, val);
  15537. } while (val !== 0);
  15538. if (s.gzhead.hcrc && s.pending > beg) {
  15539. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15540. }
  15541. if (val === 0) {
  15542. s.gzindex = 0;
  15543. s.status = COMMENT_STATE;
  15544. }
  15545. }
  15546. else {
  15547. s.status = COMMENT_STATE;
  15548. }
  15549. }
  15550. if (s.status === COMMENT_STATE) {
  15551. if (s.gzhead.comment/* != Z_NULL*/) {
  15552. beg = s.pending; /* start of bytes to update crc */
  15553. //int val;
  15554. do {
  15555. if (s.pending === s.pending_buf_size) {
  15556. if (s.gzhead.hcrc && s.pending > beg) {
  15557. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15558. }
  15559. flush_pending(strm);
  15560. beg = s.pending;
  15561. if (s.pending === s.pending_buf_size) {
  15562. val = 1;
  15563. break;
  15564. }
  15565. }
  15566. // JS specific: little magic to add zero terminator to end of string
  15567. if (s.gzindex < s.gzhead.comment.length) {
  15568. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  15569. } else {
  15570. val = 0;
  15571. }
  15572. put_byte(s, val);
  15573. } while (val !== 0);
  15574. if (s.gzhead.hcrc && s.pending > beg) {
  15575. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15576. }
  15577. if (val === 0) {
  15578. s.status = HCRC_STATE;
  15579. }
  15580. }
  15581. else {
  15582. s.status = HCRC_STATE;
  15583. }
  15584. }
  15585. if (s.status === HCRC_STATE) {
  15586. if (s.gzhead.hcrc) {
  15587. if (s.pending + 2 > s.pending_buf_size) {
  15588. flush_pending(strm);
  15589. }
  15590. if (s.pending + 2 <= s.pending_buf_size) {
  15591. put_byte(s, strm.adler & 0xff);
  15592. put_byte(s, (strm.adler >> 8) & 0xff);
  15593. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  15594. s.status = BUSY_STATE;
  15595. }
  15596. }
  15597. else {
  15598. s.status = BUSY_STATE;
  15599. }
  15600. }
  15601. //#endif
  15602. /* Flush as much pending output as possible */
  15603. if (s.pending !== 0) {
  15604. flush_pending(strm);
  15605. if (strm.avail_out === 0) {
  15606. /* Since avail_out is 0, deflate will be called again with
  15607. * more output space, but possibly with both pending and
  15608. * avail_in equal to zero. There won't be anything to do,
  15609. * but this is not an error situation so make sure we
  15610. * return OK instead of BUF_ERROR at next call of deflate:
  15611. */
  15612. s.last_flush = -1;
  15613. return Z_OK;
  15614. }
  15615. /* Make sure there is something to do and avoid duplicate consecutive
  15616. * flushes. For repeated and useless calls with Z_FINISH, we keep
  15617. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  15618. */
  15619. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  15620. flush !== Z_FINISH) {
  15621. return err(strm, Z_BUF_ERROR);
  15622. }
  15623. /* User must not provide more input after the first FINISH: */
  15624. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  15625. return err(strm, Z_BUF_ERROR);
  15626. }
  15627. /* Start a new block or continue the current one.
  15628. */
  15629. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  15630. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  15631. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  15632. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  15633. configuration_table[s.level].func(s, flush));
  15634. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  15635. s.status = FINISH_STATE;
  15636. }
  15637. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  15638. if (strm.avail_out === 0) {
  15639. s.last_flush = -1;
  15640. /* avoid BUF_ERROR next call, see above */
  15641. }
  15642. return Z_OK;
  15643. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  15644. * of deflate should use the same flush parameter to make sure
  15645. * that the flush is complete. So we don't have to output an
  15646. * empty block here, this will be done at next call. This also
  15647. * ensures that for a very small output buffer, we emit at most
  15648. * one empty block.
  15649. */
  15650. }
  15651. if (bstate === BS_BLOCK_DONE) {
  15652. if (flush === Z_PARTIAL_FLUSH) {
  15653. trees._tr_align(s);
  15654. }
  15655. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  15656. trees._tr_stored_block(s, 0, 0, false);
  15657. /* For a full flush, this empty block will be recognized
  15658. * as a special marker by inflate_sync().
  15659. */
  15660. if (flush === Z_FULL_FLUSH) {
  15661. /*** CLEAR_HASH(s); ***/ /* forget history */
  15662. zero(s.head); // Fill with NIL (= 0);
  15663. if (s.lookahead === 0) {
  15664. s.strstart = 0;
  15665. s.block_start = 0;
  15666. s.insert = 0;
  15667. }
  15668. }
  15669. }
  15670. flush_pending(strm);
  15671. if (strm.avail_out === 0) {
  15672. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  15673. return Z_OK;
  15674. }
  15675. }
  15676. }
  15677. //Assert(strm->avail_out > 0, "bug2");
  15678. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  15679. if (flush !== Z_FINISH) { return Z_OK; }
  15680. if (s.wrap <= 0) { return Z_STREAM_END; }
  15681. /* Write the trailer */
  15682. if (s.wrap === 2) {
  15683. put_byte(s, strm.adler & 0xff);
  15684. put_byte(s, (strm.adler >> 8) & 0xff);
  15685. put_byte(s, (strm.adler >> 16) & 0xff);
  15686. put_byte(s, (strm.adler >> 24) & 0xff);
  15687. put_byte(s, strm.total_in & 0xff);
  15688. put_byte(s, (strm.total_in >> 8) & 0xff);
  15689. put_byte(s, (strm.total_in >> 16) & 0xff);
  15690. put_byte(s, (strm.total_in >> 24) & 0xff);
  15691. }
  15692. else
  15693. {
  15694. putShortMSB(s, strm.adler >>> 16);
  15695. putShortMSB(s, strm.adler & 0xffff);
  15696. }
  15697. flush_pending(strm);
  15698. /* If avail_out is zero, the application will call deflate again
  15699. * to flush the rest.
  15700. */
  15701. if (s.wrap > 0) { s.wrap = -s.wrap; }
  15702. /* write the trailer only once! */
  15703. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  15704. }
  15705. function deflateEnd(strm) {
  15706. var status;
  15707. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  15708. return Z_STREAM_ERROR;
  15709. }
  15710. status = strm.state.status;
  15711. if (status !== INIT_STATE &&
  15712. status !== EXTRA_STATE &&
  15713. status !== NAME_STATE &&
  15714. status !== COMMENT_STATE &&
  15715. status !== HCRC_STATE &&
  15716. status !== BUSY_STATE &&
  15717. status !== FINISH_STATE
  15718. ) {
  15719. return err(strm, Z_STREAM_ERROR);
  15720. }
  15721. strm.state = null;
  15722. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  15723. }
  15724. /* =========================================================================
  15725. * Copy the source state to the destination state
  15726. */
  15727. //function deflateCopy(dest, source) {
  15728. //
  15729. //}
  15730. exports.deflateInit = deflateInit;
  15731. exports.deflateInit2 = deflateInit2;
  15732. exports.deflateReset = deflateReset;
  15733. exports.deflateResetKeep = deflateResetKeep;
  15734. exports.deflateSetHeader = deflateSetHeader;
  15735. exports.deflate = deflate;
  15736. exports.deflateEnd = deflateEnd;
  15737. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  15738. /* Not implemented
  15739. exports.deflateBound = deflateBound;
  15740. exports.deflateCopy = deflateCopy;
  15741. exports.deflateSetDictionary = deflateSetDictionary;
  15742. exports.deflateParams = deflateParams;
  15743. exports.deflatePending = deflatePending;
  15744. exports.deflatePrime = deflatePrime;
  15745. exports.deflateTune = deflateTune;
  15746. */
  15747. },{"../utils/common":52,"./adler32":54,"./crc32":56,"./messages":62,"./trees":63}],58:[function(require,module,exports){
  15748. 'use strict';
  15749. function GZheader() {
  15750. /* true if compressed data believed to be text */
  15751. this.text = 0;
  15752. /* modification time */
  15753. this.time = 0;
  15754. /* extra flags (not used when writing a gzip file) */
  15755. this.xflags = 0;
  15756. /* operating system */
  15757. this.os = 0;
  15758. /* pointer to extra field or Z_NULL if none */
  15759. this.extra = null;
  15760. /* extra field length (valid if extra != Z_NULL) */
  15761. this.extra_len = 0; // Actually, we don't need it in JS,
  15762. // but leave for few code modifications
  15763. //
  15764. // Setup limits is not necessary because in js we should not preallocate memory
  15765. // for inflate use constant limit in 65536 bytes
  15766. //
  15767. /* space at extra (only when reading header) */
  15768. // this.extra_max = 0;
  15769. /* pointer to zero-terminated file name or Z_NULL */
  15770. this.name = '';
  15771. /* space at name (only when reading header) */
  15772. // this.name_max = 0;
  15773. /* pointer to zero-terminated comment or Z_NULL */
  15774. this.comment = '';
  15775. /* space at comment (only when reading header) */
  15776. // this.comm_max = 0;
  15777. /* true if there was or will be a header crc */
  15778. this.hcrc = 0;
  15779. /* true when done reading gzip header (not used when writing a gzip file) */
  15780. this.done = false;
  15781. }
  15782. module.exports = GZheader;
  15783. },{}],59:[function(require,module,exports){
  15784. 'use strict';
  15785. // See state defs from inflate.js
  15786. var BAD = 30; /* got a data error -- remain here until reset */
  15787. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  15788. /*
  15789. Decode literal, length, and distance codes and write out the resulting
  15790. literal and match bytes until either not enough input or output is
  15791. available, an end-of-block is encountered, or a data error is encountered.
  15792. When large enough input and output buffers are supplied to inflate(), for
  15793. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  15794. inflate execution time is spent in this routine.
  15795. Entry assumptions:
  15796. state.mode === LEN
  15797. strm.avail_in >= 6
  15798. strm.avail_out >= 258
  15799. start >= strm.avail_out
  15800. state.bits < 8
  15801. On return, state.mode is one of:
  15802. LEN -- ran out of enough output space or enough available input
  15803. TYPE -- reached end of block code, inflate() to interpret next block
  15804. BAD -- error in block data
  15805. Notes:
  15806. - The maximum input bits used by a length/distance pair is 15 bits for the
  15807. length code, 5 bits for the length extra, 15 bits for the distance code,
  15808. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  15809. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  15810. checking for available input while decoding.
  15811. - The maximum bytes that a single length/distance pair can output is 258
  15812. bytes, which is the maximum length that can be coded. inflate_fast()
  15813. requires strm.avail_out >= 258 for each loop to avoid checking for
  15814. output space.
  15815. */
  15816. module.exports = function inflate_fast(strm, start) {
  15817. var state;
  15818. var _in; /* local strm.input */
  15819. var last; /* have enough input while in < last */
  15820. var _out; /* local strm.output */
  15821. var beg; /* inflate()'s initial strm.output */
  15822. var end; /* while out < end, enough space available */
  15823. //#ifdef INFLATE_STRICT
  15824. var dmax; /* maximum distance from zlib header */
  15825. //#endif
  15826. var wsize; /* window size or zero if not using window */
  15827. var whave; /* valid bytes in the window */
  15828. var wnext; /* window write index */
  15829. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  15830. var s_window; /* allocated sliding window, if wsize != 0 */
  15831. var hold; /* local strm.hold */
  15832. var bits; /* local strm.bits */
  15833. var lcode; /* local strm.lencode */
  15834. var dcode; /* local strm.distcode */
  15835. var lmask; /* mask for first level of length codes */
  15836. var dmask; /* mask for first level of distance codes */
  15837. var here; /* retrieved table entry */
  15838. var op; /* code bits, operation, extra bits, or */
  15839. /* window position, window bytes to copy */
  15840. var len; /* match length, unused bytes */
  15841. var dist; /* match distance */
  15842. var from; /* where to copy match from */
  15843. var from_source;
  15844. var input, output; // JS specific, because we have no pointers
  15845. /* copy state to local variables */
  15846. state = strm.state;
  15847. //here = state.here;
  15848. _in = strm.next_in;
  15849. input = strm.input;
  15850. last = _in + (strm.avail_in - 5);
  15851. _out = strm.next_out;
  15852. output = strm.output;
  15853. beg = _out - (start - strm.avail_out);
  15854. end = _out + (strm.avail_out - 257);
  15855. //#ifdef INFLATE_STRICT
  15856. dmax = state.dmax;
  15857. //#endif
  15858. wsize = state.wsize;
  15859. whave = state.whave;
  15860. wnext = state.wnext;
  15861. s_window = state.window;
  15862. hold = state.hold;
  15863. bits = state.bits;
  15864. lcode = state.lencode;
  15865. dcode = state.distcode;
  15866. lmask = (1 << state.lenbits) - 1;
  15867. dmask = (1 << state.distbits) - 1;
  15868. /* decode literals and length/distances until end-of-block or not enough
  15869. input data or output space */
  15870. top:
  15871. do {
  15872. if (bits < 15) {
  15873. hold += input[_in++] << bits;
  15874. bits += 8;
  15875. hold += input[_in++] << bits;
  15876. bits += 8;
  15877. }
  15878. here = lcode[hold & lmask];
  15879. dolen:
  15880. for (;;) { // Goto emulation
  15881. op = here >>> 24/*here.bits*/;
  15882. hold >>>= op;
  15883. bits -= op;
  15884. op = (here >>> 16) & 0xff/*here.op*/;
  15885. if (op === 0) { /* literal */
  15886. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  15887. // "inflate: literal '%c'\n" :
  15888. // "inflate: literal 0x%02x\n", here.val));
  15889. output[_out++] = here & 0xffff/*here.val*/;
  15890. }
  15891. else if (op & 16) { /* length base */
  15892. len = here & 0xffff/*here.val*/;
  15893. op &= 15; /* number of extra bits */
  15894. if (op) {
  15895. if (bits < op) {
  15896. hold += input[_in++] << bits;
  15897. bits += 8;
  15898. }
  15899. len += hold & ((1 << op) - 1);
  15900. hold >>>= op;
  15901. bits -= op;
  15902. }
  15903. //Tracevv((stderr, "inflate: length %u\n", len));
  15904. if (bits < 15) {
  15905. hold += input[_in++] << bits;
  15906. bits += 8;
  15907. hold += input[_in++] << bits;
  15908. bits += 8;
  15909. }
  15910. here = dcode[hold & dmask];
  15911. dodist:
  15912. for (;;) { // goto emulation
  15913. op = here >>> 24/*here.bits*/;
  15914. hold >>>= op;
  15915. bits -= op;
  15916. op = (here >>> 16) & 0xff/*here.op*/;
  15917. if (op & 16) { /* distance base */
  15918. dist = here & 0xffff/*here.val*/;
  15919. op &= 15; /* number of extra bits */
  15920. if (bits < op) {
  15921. hold += input[_in++] << bits;
  15922. bits += 8;
  15923. if (bits < op) {
  15924. hold += input[_in++] << bits;
  15925. bits += 8;
  15926. }
  15927. }
  15928. dist += hold & ((1 << op) - 1);
  15929. //#ifdef INFLATE_STRICT
  15930. if (dist > dmax) {
  15931. strm.msg = 'invalid distance too far back';
  15932. state.mode = BAD;
  15933. break top;
  15934. }
  15935. //#endif
  15936. hold >>>= op;
  15937. bits -= op;
  15938. //Tracevv((stderr, "inflate: distance %u\n", dist));
  15939. op = _out - beg; /* max distance in output */
  15940. if (dist > op) { /* see if copy from window */
  15941. op = dist - op; /* distance back in window */
  15942. if (op > whave) {
  15943. if (state.sane) {
  15944. strm.msg = 'invalid distance too far back';
  15945. state.mode = BAD;
  15946. break top;
  15947. }
  15948. // (!) This block is disabled in zlib defailts,
  15949. // don't enable it for binary compatibility
  15950. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  15951. // if (len <= op - whave) {
  15952. // do {
  15953. // output[_out++] = 0;
  15954. // } while (--len);
  15955. // continue top;
  15956. // }
  15957. // len -= op - whave;
  15958. // do {
  15959. // output[_out++] = 0;
  15960. // } while (--op > whave);
  15961. // if (op === 0) {
  15962. // from = _out - dist;
  15963. // do {
  15964. // output[_out++] = output[from++];
  15965. // } while (--len);
  15966. // continue top;
  15967. // }
  15968. //#endif
  15969. }
  15970. from = 0; // window index
  15971. from_source = s_window;
  15972. if (wnext === 0) { /* very common case */
  15973. from += wsize - op;
  15974. if (op < len) { /* some from window */
  15975. len -= op;
  15976. do {
  15977. output[_out++] = s_window[from++];
  15978. } while (--op);
  15979. from = _out - dist; /* rest from output */
  15980. from_source = output;
  15981. }
  15982. }
  15983. else if (wnext < op) { /* wrap around window */
  15984. from += wsize + wnext - op;
  15985. op -= wnext;
  15986. if (op < len) { /* some from end of window */
  15987. len -= op;
  15988. do {
  15989. output[_out++] = s_window[from++];
  15990. } while (--op);
  15991. from = 0;
  15992. if (wnext < len) { /* some from start of window */
  15993. op = wnext;
  15994. len -= op;
  15995. do {
  15996. output[_out++] = s_window[from++];
  15997. } while (--op);
  15998. from = _out - dist; /* rest from output */
  15999. from_source = output;
  16000. }
  16001. }
  16002. }
  16003. else { /* contiguous in window */
  16004. from += wnext - op;
  16005. if (op < len) { /* some from window */
  16006. len -= op;
  16007. do {
  16008. output[_out++] = s_window[from++];
  16009. } while (--op);
  16010. from = _out - dist; /* rest from output */
  16011. from_source = output;
  16012. }
  16013. }
  16014. while (len > 2) {
  16015. output[_out++] = from_source[from++];
  16016. output[_out++] = from_source[from++];
  16017. output[_out++] = from_source[from++];
  16018. len -= 3;
  16019. }
  16020. if (len) {
  16021. output[_out++] = from_source[from++];
  16022. if (len > 1) {
  16023. output[_out++] = from_source[from++];
  16024. }
  16025. }
  16026. }
  16027. else {
  16028. from = _out - dist; /* copy direct from output */
  16029. do { /* minimum length is three */
  16030. output[_out++] = output[from++];
  16031. output[_out++] = output[from++];
  16032. output[_out++] = output[from++];
  16033. len -= 3;
  16034. } while (len > 2);
  16035. if (len) {
  16036. output[_out++] = output[from++];
  16037. if (len > 1) {
  16038. output[_out++] = output[from++];
  16039. }
  16040. }
  16041. }
  16042. }
  16043. else if ((op & 64) === 0) { /* 2nd level distance code */
  16044. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  16045. continue dodist;
  16046. }
  16047. else {
  16048. strm.msg = 'invalid distance code';
  16049. state.mode = BAD;
  16050. break top;
  16051. }
  16052. break; // need to emulate goto via "continue"
  16053. }
  16054. }
  16055. else if ((op & 64) === 0) { /* 2nd level length code */
  16056. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  16057. continue dolen;
  16058. }
  16059. else if (op & 32) { /* end-of-block */
  16060. //Tracevv((stderr, "inflate: end of block\n"));
  16061. state.mode = TYPE;
  16062. break top;
  16063. }
  16064. else {
  16065. strm.msg = 'invalid literal/length code';
  16066. state.mode = BAD;
  16067. break top;
  16068. }
  16069. break; // need to emulate goto via "continue"
  16070. }
  16071. } while (_in < last && _out < end);
  16072. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  16073. len = bits >> 3;
  16074. _in -= len;
  16075. bits -= len << 3;
  16076. hold &= (1 << bits) - 1;
  16077. /* update state and return */
  16078. strm.next_in = _in;
  16079. strm.next_out = _out;
  16080. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  16081. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  16082. state.hold = hold;
  16083. state.bits = bits;
  16084. return;
  16085. };
  16086. },{}],60:[function(require,module,exports){
  16087. 'use strict';
  16088. var utils = require('../utils/common');
  16089. var adler32 = require('./adler32');
  16090. var crc32 = require('./crc32');
  16091. var inflate_fast = require('./inffast');
  16092. var inflate_table = require('./inftrees');
  16093. var CODES = 0;
  16094. var LENS = 1;
  16095. var DISTS = 2;
  16096. /* Public constants ==========================================================*/
  16097. /* ===========================================================================*/
  16098. /* Allowed flush values; see deflate() and inflate() below for details */
  16099. //var Z_NO_FLUSH = 0;
  16100. //var Z_PARTIAL_FLUSH = 1;
  16101. //var Z_SYNC_FLUSH = 2;
  16102. //var Z_FULL_FLUSH = 3;
  16103. var Z_FINISH = 4;
  16104. var Z_BLOCK = 5;
  16105. var Z_TREES = 6;
  16106. /* Return codes for the compression/decompression functions. Negative values
  16107. * are errors, positive values are used for special but normal events.
  16108. */
  16109. var Z_OK = 0;
  16110. var Z_STREAM_END = 1;
  16111. var Z_NEED_DICT = 2;
  16112. //var Z_ERRNO = -1;
  16113. var Z_STREAM_ERROR = -2;
  16114. var Z_DATA_ERROR = -3;
  16115. var Z_MEM_ERROR = -4;
  16116. var Z_BUF_ERROR = -5;
  16117. //var Z_VERSION_ERROR = -6;
  16118. /* The deflate compression method */
  16119. var Z_DEFLATED = 8;
  16120. /* STATES ====================================================================*/
  16121. /* ===========================================================================*/
  16122. var HEAD = 1; /* i: waiting for magic header */
  16123. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  16124. var TIME = 3; /* i: waiting for modification time (gzip) */
  16125. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  16126. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  16127. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  16128. var NAME = 7; /* i: waiting for end of file name (gzip) */
  16129. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  16130. var HCRC = 9; /* i: waiting for header crc (gzip) */
  16131. var DICTID = 10; /* i: waiting for dictionary check value */
  16132. var DICT = 11; /* waiting for inflateSetDictionary() call */
  16133. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  16134. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  16135. var STORED = 14; /* i: waiting for stored size (length and complement) */
  16136. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  16137. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  16138. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  16139. var LENLENS = 18; /* i: waiting for code length code lengths */
  16140. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  16141. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  16142. var LEN = 21; /* i: waiting for length/lit/eob code */
  16143. var LENEXT = 22; /* i: waiting for length extra bits */
  16144. var DIST = 23; /* i: waiting for distance code */
  16145. var DISTEXT = 24; /* i: waiting for distance extra bits */
  16146. var MATCH = 25; /* o: waiting for output space to copy string */
  16147. var LIT = 26; /* o: waiting for output space to write literal */
  16148. var CHECK = 27; /* i: waiting for 32-bit check value */
  16149. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  16150. var DONE = 29; /* finished check, done -- remain here until reset */
  16151. var BAD = 30; /* got a data error -- remain here until reset */
  16152. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  16153. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  16154. /* ===========================================================================*/
  16155. var ENOUGH_LENS = 852;
  16156. var ENOUGH_DISTS = 592;
  16157. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  16158. var MAX_WBITS = 15;
  16159. /* 32K LZ77 window */
  16160. var DEF_WBITS = MAX_WBITS;
  16161. function ZSWAP32(q) {
  16162. return (((q >>> 24) & 0xff) +
  16163. ((q >>> 8) & 0xff00) +
  16164. ((q & 0xff00) << 8) +
  16165. ((q & 0xff) << 24));
  16166. }
  16167. function InflateState() {
  16168. this.mode = 0; /* current inflate mode */
  16169. this.last = false; /* true if processing last block */
  16170. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  16171. this.havedict = false; /* true if dictionary provided */
  16172. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  16173. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  16174. this.check = 0; /* protected copy of check value */
  16175. this.total = 0; /* protected copy of output count */
  16176. // TODO: may be {}
  16177. this.head = null; /* where to save gzip header information */
  16178. /* sliding window */
  16179. this.wbits = 0; /* log base 2 of requested window size */
  16180. this.wsize = 0; /* window size or zero if not using window */
  16181. this.whave = 0; /* valid bytes in the window */
  16182. this.wnext = 0; /* window write index */
  16183. this.window = null; /* allocated sliding window, if needed */
  16184. /* bit accumulator */
  16185. this.hold = 0; /* input bit accumulator */
  16186. this.bits = 0; /* number of bits in "in" */
  16187. /* for string and stored block copying */
  16188. this.length = 0; /* literal or length of data to copy */
  16189. this.offset = 0; /* distance back to copy string from */
  16190. /* for table and code decoding */
  16191. this.extra = 0; /* extra bits needed */
  16192. /* fixed and dynamic code tables */
  16193. this.lencode = null; /* starting table for length/literal codes */
  16194. this.distcode = null; /* starting table for distance codes */
  16195. this.lenbits = 0; /* index bits for lencode */
  16196. this.distbits = 0; /* index bits for distcode */
  16197. /* dynamic table building */
  16198. this.ncode = 0; /* number of code length code lengths */
  16199. this.nlen = 0; /* number of length code lengths */
  16200. this.ndist = 0; /* number of distance code lengths */
  16201. this.have = 0; /* number of code lengths in lens[] */
  16202. this.next = null; /* next available space in codes[] */
  16203. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  16204. this.work = new utils.Buf16(288); /* work area for code table building */
  16205. /*
  16206. because we don't have pointers in js, we use lencode and distcode directly
  16207. as buffers so we don't need codes
  16208. */
  16209. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  16210. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  16211. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  16212. this.sane = 0; /* if false, allow invalid distance too far */
  16213. this.back = 0; /* bits back of last unprocessed length/lit */
  16214. this.was = 0; /* initial length of match */
  16215. }
  16216. function inflateResetKeep(strm) {
  16217. var state;
  16218. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16219. state = strm.state;
  16220. strm.total_in = strm.total_out = state.total = 0;
  16221. strm.msg = ''; /*Z_NULL*/
  16222. if (state.wrap) { /* to support ill-conceived Java test suite */
  16223. strm.adler = state.wrap & 1;
  16224. }
  16225. state.mode = HEAD;
  16226. state.last = 0;
  16227. state.havedict = 0;
  16228. state.dmax = 32768;
  16229. state.head = null/*Z_NULL*/;
  16230. state.hold = 0;
  16231. state.bits = 0;
  16232. //state.lencode = state.distcode = state.next = state.codes;
  16233. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  16234. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  16235. state.sane = 1;
  16236. state.back = -1;
  16237. //Tracev((stderr, "inflate: reset\n"));
  16238. return Z_OK;
  16239. }
  16240. function inflateReset(strm) {
  16241. var state;
  16242. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16243. state = strm.state;
  16244. state.wsize = 0;
  16245. state.whave = 0;
  16246. state.wnext = 0;
  16247. return inflateResetKeep(strm);
  16248. }
  16249. function inflateReset2(strm, windowBits) {
  16250. var wrap;
  16251. var state;
  16252. /* get the state */
  16253. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16254. state = strm.state;
  16255. /* extract wrap request from windowBits parameter */
  16256. if (windowBits < 0) {
  16257. wrap = 0;
  16258. windowBits = -windowBits;
  16259. }
  16260. else {
  16261. wrap = (windowBits >> 4) + 1;
  16262. if (windowBits < 48) {
  16263. windowBits &= 15;
  16264. }
  16265. }
  16266. /* set number of window bits, free window if different */
  16267. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  16268. return Z_STREAM_ERROR;
  16269. }
  16270. if (state.window !== null && state.wbits !== windowBits) {
  16271. state.window = null;
  16272. }
  16273. /* update state and reset the rest of it */
  16274. state.wrap = wrap;
  16275. state.wbits = windowBits;
  16276. return inflateReset(strm);
  16277. }
  16278. function inflateInit2(strm, windowBits) {
  16279. var ret;
  16280. var state;
  16281. if (!strm) { return Z_STREAM_ERROR; }
  16282. //strm.msg = Z_NULL; /* in case we return an error */
  16283. state = new InflateState();
  16284. //if (state === Z_NULL) return Z_MEM_ERROR;
  16285. //Tracev((stderr, "inflate: allocated\n"));
  16286. strm.state = state;
  16287. state.window = null/*Z_NULL*/;
  16288. ret = inflateReset2(strm, windowBits);
  16289. if (ret !== Z_OK) {
  16290. strm.state = null/*Z_NULL*/;
  16291. }
  16292. return ret;
  16293. }
  16294. function inflateInit(strm) {
  16295. return inflateInit2(strm, DEF_WBITS);
  16296. }
  16297. /*
  16298. Return state with length and distance decoding tables and index sizes set to
  16299. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  16300. If BUILDFIXED is defined, then instead this routine builds the tables the
  16301. first time it's called, and returns those tables the first time and
  16302. thereafter. This reduces the size of the code by about 2K bytes, in
  16303. exchange for a little execution time. However, BUILDFIXED should not be
  16304. used for threaded applications, since the rewriting of the tables and virgin
  16305. may not be thread-safe.
  16306. */
  16307. var virgin = true;
  16308. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  16309. function fixedtables(state) {
  16310. /* build fixed huffman tables if first call (may not be thread safe) */
  16311. if (virgin) {
  16312. var sym;
  16313. lenfix = new utils.Buf32(512);
  16314. distfix = new utils.Buf32(32);
  16315. /* literal/length table */
  16316. sym = 0;
  16317. while (sym < 144) { state.lens[sym++] = 8; }
  16318. while (sym < 256) { state.lens[sym++] = 9; }
  16319. while (sym < 280) { state.lens[sym++] = 7; }
  16320. while (sym < 288) { state.lens[sym++] = 8; }
  16321. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  16322. /* distance table */
  16323. sym = 0;
  16324. while (sym < 32) { state.lens[sym++] = 5; }
  16325. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  16326. /* do this just once */
  16327. virgin = false;
  16328. }
  16329. state.lencode = lenfix;
  16330. state.lenbits = 9;
  16331. state.distcode = distfix;
  16332. state.distbits = 5;
  16333. }
  16334. /*
  16335. Update the window with the last wsize (normally 32K) bytes written before
  16336. returning. If window does not exist yet, create it. This is only called
  16337. when a window is already in use, or when output has been written during this
  16338. inflate call, but the end of the deflate stream has not been reached yet.
  16339. It is also called to create a window for dictionary data when a dictionary
  16340. is loaded.
  16341. Providing output buffers larger than 32K to inflate() should provide a speed
  16342. advantage, since only the last 32K of output is copied to the sliding window
  16343. upon return from inflate(), and since all distances after the first 32K of
  16344. output will fall in the output data, making match copies simpler and faster.
  16345. The advantage may be dependent on the size of the processor's data caches.
  16346. */
  16347. function updatewindow(strm, src, end, copy) {
  16348. var dist;
  16349. var state = strm.state;
  16350. /* if it hasn't been done already, allocate space for the window */
  16351. if (state.window === null) {
  16352. state.wsize = 1 << state.wbits;
  16353. state.wnext = 0;
  16354. state.whave = 0;
  16355. state.window = new utils.Buf8(state.wsize);
  16356. }
  16357. /* copy state->wsize or less output bytes into the circular window */
  16358. if (copy >= state.wsize) {
  16359. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  16360. state.wnext = 0;
  16361. state.whave = state.wsize;
  16362. }
  16363. else {
  16364. dist = state.wsize - state.wnext;
  16365. if (dist > copy) {
  16366. dist = copy;
  16367. }
  16368. //zmemcpy(state->window + state->wnext, end - copy, dist);
  16369. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  16370. copy -= dist;
  16371. if (copy) {
  16372. //zmemcpy(state->window, end - copy, copy);
  16373. utils.arraySet(state.window,src, end - copy, copy, 0);
  16374. state.wnext = copy;
  16375. state.whave = state.wsize;
  16376. }
  16377. else {
  16378. state.wnext += dist;
  16379. if (state.wnext === state.wsize) { state.wnext = 0; }
  16380. if (state.whave < state.wsize) { state.whave += dist; }
  16381. }
  16382. }
  16383. return 0;
  16384. }
  16385. function inflate(strm, flush) {
  16386. var state;
  16387. var input, output; // input/output buffers
  16388. var next; /* next input INDEX */
  16389. var put; /* next output INDEX */
  16390. var have, left; /* available input and output */
  16391. var hold; /* bit buffer */
  16392. var bits; /* bits in bit buffer */
  16393. var _in, _out; /* save starting available input and output */
  16394. var copy; /* number of stored or match bytes to copy */
  16395. var from; /* where to copy match bytes from */
  16396. var from_source;
  16397. var here = 0; /* current decoding table entry */
  16398. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  16399. //var last; /* parent table entry */
  16400. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  16401. var len; /* length to copy for repeats, bits to drop */
  16402. var ret; /* return code */
  16403. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  16404. var opts;
  16405. var n; // temporary var for NEED_BITS
  16406. var order = /* permutation of code lengths */
  16407. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  16408. if (!strm || !strm.state || !strm.output ||
  16409. (!strm.input && strm.avail_in !== 0)) {
  16410. return Z_STREAM_ERROR;
  16411. }
  16412. state = strm.state;
  16413. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  16414. //--- LOAD() ---
  16415. put = strm.next_out;
  16416. output = strm.output;
  16417. left = strm.avail_out;
  16418. next = strm.next_in;
  16419. input = strm.input;
  16420. have = strm.avail_in;
  16421. hold = state.hold;
  16422. bits = state.bits;
  16423. //---
  16424. _in = have;
  16425. _out = left;
  16426. ret = Z_OK;
  16427. inf_leave: // goto emulation
  16428. for (;;) {
  16429. switch (state.mode) {
  16430. case HEAD:
  16431. if (state.wrap === 0) {
  16432. state.mode = TYPEDO;
  16433. break;
  16434. }
  16435. //=== NEEDBITS(16);
  16436. while (bits < 16) {
  16437. if (have === 0) { break inf_leave; }
  16438. have--;
  16439. hold += input[next++] << bits;
  16440. bits += 8;
  16441. }
  16442. //===//
  16443. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  16444. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  16445. //=== CRC2(state.check, hold);
  16446. hbuf[0] = hold & 0xff;
  16447. hbuf[1] = (hold >>> 8) & 0xff;
  16448. state.check = crc32(state.check, hbuf, 2, 0);
  16449. //===//
  16450. //=== INITBITS();
  16451. hold = 0;
  16452. bits = 0;
  16453. //===//
  16454. state.mode = FLAGS;
  16455. break;
  16456. }
  16457. state.flags = 0; /* expect zlib header */
  16458. if (state.head) {
  16459. state.head.done = false;
  16460. }
  16461. if (!(state.wrap & 1) || /* check if zlib header allowed */
  16462. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  16463. strm.msg = 'incorrect header check';
  16464. state.mode = BAD;
  16465. break;
  16466. }
  16467. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  16468. strm.msg = 'unknown compression method';
  16469. state.mode = BAD;
  16470. break;
  16471. }
  16472. //--- DROPBITS(4) ---//
  16473. hold >>>= 4;
  16474. bits -= 4;
  16475. //---//
  16476. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  16477. if (state.wbits === 0) {
  16478. state.wbits = len;
  16479. }
  16480. else if (len > state.wbits) {
  16481. strm.msg = 'invalid window size';
  16482. state.mode = BAD;
  16483. break;
  16484. }
  16485. state.dmax = 1 << len;
  16486. //Tracev((stderr, "inflate: zlib header ok\n"));
  16487. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  16488. state.mode = hold & 0x200 ? DICTID : TYPE;
  16489. //=== INITBITS();
  16490. hold = 0;
  16491. bits = 0;
  16492. //===//
  16493. break;
  16494. case FLAGS:
  16495. //=== NEEDBITS(16); */
  16496. while (bits < 16) {
  16497. if (have === 0) { break inf_leave; }
  16498. have--;
  16499. hold += input[next++] << bits;
  16500. bits += 8;
  16501. }
  16502. //===//
  16503. state.flags = hold;
  16504. if ((state.flags & 0xff) !== Z_DEFLATED) {
  16505. strm.msg = 'unknown compression method';
  16506. state.mode = BAD;
  16507. break;
  16508. }
  16509. if (state.flags & 0xe000) {
  16510. strm.msg = 'unknown header flags set';
  16511. state.mode = BAD;
  16512. break;
  16513. }
  16514. if (state.head) {
  16515. state.head.text = ((hold >> 8) & 1);
  16516. }
  16517. if (state.flags & 0x0200) {
  16518. //=== CRC2(state.check, hold);
  16519. hbuf[0] = hold & 0xff;
  16520. hbuf[1] = (hold >>> 8) & 0xff;
  16521. state.check = crc32(state.check, hbuf, 2, 0);
  16522. //===//
  16523. }
  16524. //=== INITBITS();
  16525. hold = 0;
  16526. bits = 0;
  16527. //===//
  16528. state.mode = TIME;
  16529. /* falls through */
  16530. case TIME:
  16531. //=== NEEDBITS(32); */
  16532. while (bits < 32) {
  16533. if (have === 0) { break inf_leave; }
  16534. have--;
  16535. hold += input[next++] << bits;
  16536. bits += 8;
  16537. }
  16538. //===//
  16539. if (state.head) {
  16540. state.head.time = hold;
  16541. }
  16542. if (state.flags & 0x0200) {
  16543. //=== CRC4(state.check, hold)
  16544. hbuf[0] = hold & 0xff;
  16545. hbuf[1] = (hold >>> 8) & 0xff;
  16546. hbuf[2] = (hold >>> 16) & 0xff;
  16547. hbuf[3] = (hold >>> 24) & 0xff;
  16548. state.check = crc32(state.check, hbuf, 4, 0);
  16549. //===
  16550. }
  16551. //=== INITBITS();
  16552. hold = 0;
  16553. bits = 0;
  16554. //===//
  16555. state.mode = OS;
  16556. /* falls through */
  16557. case OS:
  16558. //=== NEEDBITS(16); */
  16559. while (bits < 16) {
  16560. if (have === 0) { break inf_leave; }
  16561. have--;
  16562. hold += input[next++] << bits;
  16563. bits += 8;
  16564. }
  16565. //===//
  16566. if (state.head) {
  16567. state.head.xflags = (hold & 0xff);
  16568. state.head.os = (hold >> 8);
  16569. }
  16570. if (state.flags & 0x0200) {
  16571. //=== CRC2(state.check, hold);
  16572. hbuf[0] = hold & 0xff;
  16573. hbuf[1] = (hold >>> 8) & 0xff;
  16574. state.check = crc32(state.check, hbuf, 2, 0);
  16575. //===//
  16576. }
  16577. //=== INITBITS();
  16578. hold = 0;
  16579. bits = 0;
  16580. //===//
  16581. state.mode = EXLEN;
  16582. /* falls through */
  16583. case EXLEN:
  16584. if (state.flags & 0x0400) {
  16585. //=== NEEDBITS(16); */
  16586. while (bits < 16) {
  16587. if (have === 0) { break inf_leave; }
  16588. have--;
  16589. hold += input[next++] << bits;
  16590. bits += 8;
  16591. }
  16592. //===//
  16593. state.length = hold;
  16594. if (state.head) {
  16595. state.head.extra_len = hold;
  16596. }
  16597. if (state.flags & 0x0200) {
  16598. //=== CRC2(state.check, hold);
  16599. hbuf[0] = hold & 0xff;
  16600. hbuf[1] = (hold >>> 8) & 0xff;
  16601. state.check = crc32(state.check, hbuf, 2, 0);
  16602. //===//
  16603. }
  16604. //=== INITBITS();
  16605. hold = 0;
  16606. bits = 0;
  16607. //===//
  16608. }
  16609. else if (state.head) {
  16610. state.head.extra = null/*Z_NULL*/;
  16611. }
  16612. state.mode = EXTRA;
  16613. /* falls through */
  16614. case EXTRA:
  16615. if (state.flags & 0x0400) {
  16616. copy = state.length;
  16617. if (copy > have) { copy = have; }
  16618. if (copy) {
  16619. if (state.head) {
  16620. len = state.head.extra_len - state.length;
  16621. if (!state.head.extra) {
  16622. // Use untyped array for more conveniend processing later
  16623. state.head.extra = new Array(state.head.extra_len);
  16624. }
  16625. utils.arraySet(
  16626. state.head.extra,
  16627. input,
  16628. next,
  16629. // extra field is limited to 65536 bytes
  16630. // - no need for additional size check
  16631. copy,
  16632. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  16633. len
  16634. );
  16635. //zmemcpy(state.head.extra + len, next,
  16636. // len + copy > state.head.extra_max ?
  16637. // state.head.extra_max - len : copy);
  16638. }
  16639. if (state.flags & 0x0200) {
  16640. state.check = crc32(state.check, input, copy, next);
  16641. }
  16642. have -= copy;
  16643. next += copy;
  16644. state.length -= copy;
  16645. }
  16646. if (state.length) { break inf_leave; }
  16647. }
  16648. state.length = 0;
  16649. state.mode = NAME;
  16650. /* falls through */
  16651. case NAME:
  16652. if (state.flags & 0x0800) {
  16653. if (have === 0) { break inf_leave; }
  16654. copy = 0;
  16655. do {
  16656. // TODO: 2 or 1 bytes?
  16657. len = input[next + copy++];
  16658. /* use constant limit because in js we should not preallocate memory */
  16659. if (state.head && len &&
  16660. (state.length < 65536 /*state.head.name_max*/)) {
  16661. state.head.name += String.fromCharCode(len);
  16662. }
  16663. } while (len && copy < have);
  16664. if (state.flags & 0x0200) {
  16665. state.check = crc32(state.check, input, copy, next);
  16666. }
  16667. have -= copy;
  16668. next += copy;
  16669. if (len) { break inf_leave; }
  16670. }
  16671. else if (state.head) {
  16672. state.head.name = null;
  16673. }
  16674. state.length = 0;
  16675. state.mode = COMMENT;
  16676. /* falls through */
  16677. case COMMENT:
  16678. if (state.flags & 0x1000) {
  16679. if (have === 0) { break inf_leave; }
  16680. copy = 0;
  16681. do {
  16682. len = input[next + copy++];
  16683. /* use constant limit because in js we should not preallocate memory */
  16684. if (state.head && len &&
  16685. (state.length < 65536 /*state.head.comm_max*/)) {
  16686. state.head.comment += String.fromCharCode(len);
  16687. }
  16688. } while (len && copy < have);
  16689. if (state.flags & 0x0200) {
  16690. state.check = crc32(state.check, input, copy, next);
  16691. }
  16692. have -= copy;
  16693. next += copy;
  16694. if (len) { break inf_leave; }
  16695. }
  16696. else if (state.head) {
  16697. state.head.comment = null;
  16698. }
  16699. state.mode = HCRC;
  16700. /* falls through */
  16701. case HCRC:
  16702. if (state.flags & 0x0200) {
  16703. //=== NEEDBITS(16); */
  16704. while (bits < 16) {
  16705. if (have === 0) { break inf_leave; }
  16706. have--;
  16707. hold += input[next++] << bits;
  16708. bits += 8;
  16709. }
  16710. //===//
  16711. if (hold !== (state.check & 0xffff)) {
  16712. strm.msg = 'header crc mismatch';
  16713. state.mode = BAD;
  16714. break;
  16715. }
  16716. //=== INITBITS();
  16717. hold = 0;
  16718. bits = 0;
  16719. //===//
  16720. }
  16721. if (state.head) {
  16722. state.head.hcrc = ((state.flags >> 9) & 1);
  16723. state.head.done = true;
  16724. }
  16725. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  16726. state.mode = TYPE;
  16727. break;
  16728. case DICTID:
  16729. //=== NEEDBITS(32); */
  16730. while (bits < 32) {
  16731. if (have === 0) { break inf_leave; }
  16732. have--;
  16733. hold += input[next++] << bits;
  16734. bits += 8;
  16735. }
  16736. //===//
  16737. strm.adler = state.check = ZSWAP32(hold);
  16738. //=== INITBITS();
  16739. hold = 0;
  16740. bits = 0;
  16741. //===//
  16742. state.mode = DICT;
  16743. /* falls through */
  16744. case DICT:
  16745. if (state.havedict === 0) {
  16746. //--- RESTORE() ---
  16747. strm.next_out = put;
  16748. strm.avail_out = left;
  16749. strm.next_in = next;
  16750. strm.avail_in = have;
  16751. state.hold = hold;
  16752. state.bits = bits;
  16753. //---
  16754. return Z_NEED_DICT;
  16755. }
  16756. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  16757. state.mode = TYPE;
  16758. /* falls through */
  16759. case TYPE:
  16760. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  16761. /* falls through */
  16762. case TYPEDO:
  16763. if (state.last) {
  16764. //--- BYTEBITS() ---//
  16765. hold >>>= bits & 7;
  16766. bits -= bits & 7;
  16767. //---//
  16768. state.mode = CHECK;
  16769. break;
  16770. }
  16771. //=== NEEDBITS(3); */
  16772. while (bits < 3) {
  16773. if (have === 0) { break inf_leave; }
  16774. have--;
  16775. hold += input[next++] << bits;
  16776. bits += 8;
  16777. }
  16778. //===//
  16779. state.last = (hold & 0x01)/*BITS(1)*/;
  16780. //--- DROPBITS(1) ---//
  16781. hold >>>= 1;
  16782. bits -= 1;
  16783. //---//
  16784. switch ((hold & 0x03)/*BITS(2)*/) {
  16785. case 0: /* stored block */
  16786. //Tracev((stderr, "inflate: stored block%s\n",
  16787. // state.last ? " (last)" : ""));
  16788. state.mode = STORED;
  16789. break;
  16790. case 1: /* fixed block */
  16791. fixedtables(state);
  16792. //Tracev((stderr, "inflate: fixed codes block%s\n",
  16793. // state.last ? " (last)" : ""));
  16794. state.mode = LEN_; /* decode codes */
  16795. if (flush === Z_TREES) {
  16796. //--- DROPBITS(2) ---//
  16797. hold >>>= 2;
  16798. bits -= 2;
  16799. //---//
  16800. break inf_leave;
  16801. }
  16802. break;
  16803. case 2: /* dynamic block */
  16804. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  16805. // state.last ? " (last)" : ""));
  16806. state.mode = TABLE;
  16807. break;
  16808. case 3:
  16809. strm.msg = 'invalid block type';
  16810. state.mode = BAD;
  16811. }
  16812. //--- DROPBITS(2) ---//
  16813. hold >>>= 2;
  16814. bits -= 2;
  16815. //---//
  16816. break;
  16817. case STORED:
  16818. //--- BYTEBITS() ---// /* go to byte boundary */
  16819. hold >>>= bits & 7;
  16820. bits -= bits & 7;
  16821. //---//
  16822. //=== NEEDBITS(32); */
  16823. while (bits < 32) {
  16824. if (have === 0) { break inf_leave; }
  16825. have--;
  16826. hold += input[next++] << bits;
  16827. bits += 8;
  16828. }
  16829. //===//
  16830. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  16831. strm.msg = 'invalid stored block lengths';
  16832. state.mode = BAD;
  16833. break;
  16834. }
  16835. state.length = hold & 0xffff;
  16836. //Tracev((stderr, "inflate: stored length %u\n",
  16837. // state.length));
  16838. //=== INITBITS();
  16839. hold = 0;
  16840. bits = 0;
  16841. //===//
  16842. state.mode = COPY_;
  16843. if (flush === Z_TREES) { break inf_leave; }
  16844. /* falls through */
  16845. case COPY_:
  16846. state.mode = COPY;
  16847. /* falls through */
  16848. case COPY:
  16849. copy = state.length;
  16850. if (copy) {
  16851. if (copy > have) { copy = have; }
  16852. if (copy > left) { copy = left; }
  16853. if (copy === 0) { break inf_leave; }
  16854. //--- zmemcpy(put, next, copy); ---
  16855. utils.arraySet(output, input, next, copy, put);
  16856. //---//
  16857. have -= copy;
  16858. next += copy;
  16859. left -= copy;
  16860. put += copy;
  16861. state.length -= copy;
  16862. break;
  16863. }
  16864. //Tracev((stderr, "inflate: stored end\n"));
  16865. state.mode = TYPE;
  16866. break;
  16867. case TABLE:
  16868. //=== NEEDBITS(14); */
  16869. while (bits < 14) {
  16870. if (have === 0) { break inf_leave; }
  16871. have--;
  16872. hold += input[next++] << bits;
  16873. bits += 8;
  16874. }
  16875. //===//
  16876. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  16877. //--- DROPBITS(5) ---//
  16878. hold >>>= 5;
  16879. bits -= 5;
  16880. //---//
  16881. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  16882. //--- DROPBITS(5) ---//
  16883. hold >>>= 5;
  16884. bits -= 5;
  16885. //---//
  16886. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  16887. //--- DROPBITS(4) ---//
  16888. hold >>>= 4;
  16889. bits -= 4;
  16890. //---//
  16891. //#ifndef PKZIP_BUG_WORKAROUND
  16892. if (state.nlen > 286 || state.ndist > 30) {
  16893. strm.msg = 'too many length or distance symbols';
  16894. state.mode = BAD;
  16895. break;
  16896. }
  16897. //#endif
  16898. //Tracev((stderr, "inflate: table sizes ok\n"));
  16899. state.have = 0;
  16900. state.mode = LENLENS;
  16901. /* falls through */
  16902. case LENLENS:
  16903. while (state.have < state.ncode) {
  16904. //=== NEEDBITS(3);
  16905. while (bits < 3) {
  16906. if (have === 0) { break inf_leave; }
  16907. have--;
  16908. hold += input[next++] << bits;
  16909. bits += 8;
  16910. }
  16911. //===//
  16912. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  16913. //--- DROPBITS(3) ---//
  16914. hold >>>= 3;
  16915. bits -= 3;
  16916. //---//
  16917. }
  16918. while (state.have < 19) {
  16919. state.lens[order[state.have++]] = 0;
  16920. }
  16921. // We have separate tables & no pointers. 2 commented lines below not needed.
  16922. //state.next = state.codes;
  16923. //state.lencode = state.next;
  16924. // Switch to use dynamic table
  16925. state.lencode = state.lendyn;
  16926. state.lenbits = 7;
  16927. opts = {bits: state.lenbits};
  16928. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  16929. state.lenbits = opts.bits;
  16930. if (ret) {
  16931. strm.msg = 'invalid code lengths set';
  16932. state.mode = BAD;
  16933. break;
  16934. }
  16935. //Tracev((stderr, "inflate: code lengths ok\n"));
  16936. state.have = 0;
  16937. state.mode = CODELENS;
  16938. /* falls through */
  16939. case CODELENS:
  16940. while (state.have < state.nlen + state.ndist) {
  16941. for (;;) {
  16942. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  16943. here_bits = here >>> 24;
  16944. here_op = (here >>> 16) & 0xff;
  16945. here_val = here & 0xffff;
  16946. if ((here_bits) <= bits) { break; }
  16947. //--- PULLBYTE() ---//
  16948. if (have === 0) { break inf_leave; }
  16949. have--;
  16950. hold += input[next++] << bits;
  16951. bits += 8;
  16952. //---//
  16953. }
  16954. if (here_val < 16) {
  16955. //--- DROPBITS(here.bits) ---//
  16956. hold >>>= here_bits;
  16957. bits -= here_bits;
  16958. //---//
  16959. state.lens[state.have++] = here_val;
  16960. }
  16961. else {
  16962. if (here_val === 16) {
  16963. //=== NEEDBITS(here.bits + 2);
  16964. n = here_bits + 2;
  16965. while (bits < n) {
  16966. if (have === 0) { break inf_leave; }
  16967. have--;
  16968. hold += input[next++] << bits;
  16969. bits += 8;
  16970. }
  16971. //===//
  16972. //--- DROPBITS(here.bits) ---//
  16973. hold >>>= here_bits;
  16974. bits -= here_bits;
  16975. //---//
  16976. if (state.have === 0) {
  16977. strm.msg = 'invalid bit length repeat';
  16978. state.mode = BAD;
  16979. break;
  16980. }
  16981. len = state.lens[state.have - 1];
  16982. copy = 3 + (hold & 0x03);//BITS(2);
  16983. //--- DROPBITS(2) ---//
  16984. hold >>>= 2;
  16985. bits -= 2;
  16986. //---//
  16987. }
  16988. else if (here_val === 17) {
  16989. //=== NEEDBITS(here.bits + 3);
  16990. n = here_bits + 3;
  16991. while (bits < n) {
  16992. if (have === 0) { break inf_leave; }
  16993. have--;
  16994. hold += input[next++] << bits;
  16995. bits += 8;
  16996. }
  16997. //===//
  16998. //--- DROPBITS(here.bits) ---//
  16999. hold >>>= here_bits;
  17000. bits -= here_bits;
  17001. //---//
  17002. len = 0;
  17003. copy = 3 + (hold & 0x07);//BITS(3);
  17004. //--- DROPBITS(3) ---//
  17005. hold >>>= 3;
  17006. bits -= 3;
  17007. //---//
  17008. }
  17009. else {
  17010. //=== NEEDBITS(here.bits + 7);
  17011. n = here_bits + 7;
  17012. while (bits < n) {
  17013. if (have === 0) { break inf_leave; }
  17014. have--;
  17015. hold += input[next++] << bits;
  17016. bits += 8;
  17017. }
  17018. //===//
  17019. //--- DROPBITS(here.bits) ---//
  17020. hold >>>= here_bits;
  17021. bits -= here_bits;
  17022. //---//
  17023. len = 0;
  17024. copy = 11 + (hold & 0x7f);//BITS(7);
  17025. //--- DROPBITS(7) ---//
  17026. hold >>>= 7;
  17027. bits -= 7;
  17028. //---//
  17029. }
  17030. if (state.have + copy > state.nlen + state.ndist) {
  17031. strm.msg = 'invalid bit length repeat';
  17032. state.mode = BAD;
  17033. break;
  17034. }
  17035. while (copy--) {
  17036. state.lens[state.have++] = len;
  17037. }
  17038. }
  17039. }
  17040. /* handle error breaks in while */
  17041. if (state.mode === BAD) { break; }
  17042. /* check for end-of-block code (better have one) */
  17043. if (state.lens[256] === 0) {
  17044. strm.msg = 'invalid code -- missing end-of-block';
  17045. state.mode = BAD;
  17046. break;
  17047. }
  17048. /* build code tables -- note: do not change the lenbits or distbits
  17049. values here (9 and 6) without reading the comments in inftrees.h
  17050. concerning the ENOUGH constants, which depend on those values */
  17051. state.lenbits = 9;
  17052. opts = {bits: state.lenbits};
  17053. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  17054. // We have separate tables & no pointers. 2 commented lines below not needed.
  17055. // state.next_index = opts.table_index;
  17056. state.lenbits = opts.bits;
  17057. // state.lencode = state.next;
  17058. if (ret) {
  17059. strm.msg = 'invalid literal/lengths set';
  17060. state.mode = BAD;
  17061. break;
  17062. }
  17063. state.distbits = 6;
  17064. //state.distcode.copy(state.codes);
  17065. // Switch to use dynamic table
  17066. state.distcode = state.distdyn;
  17067. opts = {bits: state.distbits};
  17068. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  17069. // We have separate tables & no pointers. 2 commented lines below not needed.
  17070. // state.next_index = opts.table_index;
  17071. state.distbits = opts.bits;
  17072. // state.distcode = state.next;
  17073. if (ret) {
  17074. strm.msg = 'invalid distances set';
  17075. state.mode = BAD;
  17076. break;
  17077. }
  17078. //Tracev((stderr, 'inflate: codes ok\n'));
  17079. state.mode = LEN_;
  17080. if (flush === Z_TREES) { break inf_leave; }
  17081. /* falls through */
  17082. case LEN_:
  17083. state.mode = LEN;
  17084. /* falls through */
  17085. case LEN:
  17086. if (have >= 6 && left >= 258) {
  17087. //--- RESTORE() ---
  17088. strm.next_out = put;
  17089. strm.avail_out = left;
  17090. strm.next_in = next;
  17091. strm.avail_in = have;
  17092. state.hold = hold;
  17093. state.bits = bits;
  17094. //---
  17095. inflate_fast(strm, _out);
  17096. //--- LOAD() ---
  17097. put = strm.next_out;
  17098. output = strm.output;
  17099. left = strm.avail_out;
  17100. next = strm.next_in;
  17101. input = strm.input;
  17102. have = strm.avail_in;
  17103. hold = state.hold;
  17104. bits = state.bits;
  17105. //---
  17106. if (state.mode === TYPE) {
  17107. state.back = -1;
  17108. }
  17109. break;
  17110. }
  17111. state.back = 0;
  17112. for (;;) {
  17113. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  17114. here_bits = here >>> 24;
  17115. here_op = (here >>> 16) & 0xff;
  17116. here_val = here & 0xffff;
  17117. if (here_bits <= bits) { break; }
  17118. //--- PULLBYTE() ---//
  17119. if (have === 0) { break inf_leave; }
  17120. have--;
  17121. hold += input[next++] << bits;
  17122. bits += 8;
  17123. //---//
  17124. }
  17125. if (here_op && (here_op & 0xf0) === 0) {
  17126. last_bits = here_bits;
  17127. last_op = here_op;
  17128. last_val = here_val;
  17129. for (;;) {
  17130. here = state.lencode[last_val +
  17131. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  17132. here_bits = here >>> 24;
  17133. here_op = (here >>> 16) & 0xff;
  17134. here_val = here & 0xffff;
  17135. if ((last_bits + here_bits) <= bits) { break; }
  17136. //--- PULLBYTE() ---//
  17137. if (have === 0) { break inf_leave; }
  17138. have--;
  17139. hold += input[next++] << bits;
  17140. bits += 8;
  17141. //---//
  17142. }
  17143. //--- DROPBITS(last.bits) ---//
  17144. hold >>>= last_bits;
  17145. bits -= last_bits;
  17146. //---//
  17147. state.back += last_bits;
  17148. }
  17149. //--- DROPBITS(here.bits) ---//
  17150. hold >>>= here_bits;
  17151. bits -= here_bits;
  17152. //---//
  17153. state.back += here_bits;
  17154. state.length = here_val;
  17155. if (here_op === 0) {
  17156. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  17157. // "inflate: literal '%c'\n" :
  17158. // "inflate: literal 0x%02x\n", here.val));
  17159. state.mode = LIT;
  17160. break;
  17161. }
  17162. if (here_op & 32) {
  17163. //Tracevv((stderr, "inflate: end of block\n"));
  17164. state.back = -1;
  17165. state.mode = TYPE;
  17166. break;
  17167. }
  17168. if (here_op & 64) {
  17169. strm.msg = 'invalid literal/length code';
  17170. state.mode = BAD;
  17171. break;
  17172. }
  17173. state.extra = here_op & 15;
  17174. state.mode = LENEXT;
  17175. /* falls through */
  17176. case LENEXT:
  17177. if (state.extra) {
  17178. //=== NEEDBITS(state.extra);
  17179. n = state.extra;
  17180. while (bits < n) {
  17181. if (have === 0) { break inf_leave; }
  17182. have--;
  17183. hold += input[next++] << bits;
  17184. bits += 8;
  17185. }
  17186. //===//
  17187. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  17188. //--- DROPBITS(state.extra) ---//
  17189. hold >>>= state.extra;
  17190. bits -= state.extra;
  17191. //---//
  17192. state.back += state.extra;
  17193. }
  17194. //Tracevv((stderr, "inflate: length %u\n", state.length));
  17195. state.was = state.length;
  17196. state.mode = DIST;
  17197. /* falls through */
  17198. case DIST:
  17199. for (;;) {
  17200. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  17201. here_bits = here >>> 24;
  17202. here_op = (here >>> 16) & 0xff;
  17203. here_val = here & 0xffff;
  17204. if ((here_bits) <= bits) { break; }
  17205. //--- PULLBYTE() ---//
  17206. if (have === 0) { break inf_leave; }
  17207. have--;
  17208. hold += input[next++] << bits;
  17209. bits += 8;
  17210. //---//
  17211. }
  17212. if ((here_op & 0xf0) === 0) {
  17213. last_bits = here_bits;
  17214. last_op = here_op;
  17215. last_val = here_val;
  17216. for (;;) {
  17217. here = state.distcode[last_val +
  17218. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  17219. here_bits = here >>> 24;
  17220. here_op = (here >>> 16) & 0xff;
  17221. here_val = here & 0xffff;
  17222. if ((last_bits + here_bits) <= bits) { break; }
  17223. //--- PULLBYTE() ---//
  17224. if (have === 0) { break inf_leave; }
  17225. have--;
  17226. hold += input[next++] << bits;
  17227. bits += 8;
  17228. //---//
  17229. }
  17230. //--- DROPBITS(last.bits) ---//
  17231. hold >>>= last_bits;
  17232. bits -= last_bits;
  17233. //---//
  17234. state.back += last_bits;
  17235. }
  17236. //--- DROPBITS(here.bits) ---//
  17237. hold >>>= here_bits;
  17238. bits -= here_bits;
  17239. //---//
  17240. state.back += here_bits;
  17241. if (here_op & 64) {
  17242. strm.msg = 'invalid distance code';
  17243. state.mode = BAD;
  17244. break;
  17245. }
  17246. state.offset = here_val;
  17247. state.extra = (here_op) & 15;
  17248. state.mode = DISTEXT;
  17249. /* falls through */
  17250. case DISTEXT:
  17251. if (state.extra) {
  17252. //=== NEEDBITS(state.extra);
  17253. n = state.extra;
  17254. while (bits < n) {
  17255. if (have === 0) { break inf_leave; }
  17256. have--;
  17257. hold += input[next++] << bits;
  17258. bits += 8;
  17259. }
  17260. //===//
  17261. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  17262. //--- DROPBITS(state.extra) ---//
  17263. hold >>>= state.extra;
  17264. bits -= state.extra;
  17265. //---//
  17266. state.back += state.extra;
  17267. }
  17268. //#ifdef INFLATE_STRICT
  17269. if (state.offset > state.dmax) {
  17270. strm.msg = 'invalid distance too far back';
  17271. state.mode = BAD;
  17272. break;
  17273. }
  17274. //#endif
  17275. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  17276. state.mode = MATCH;
  17277. /* falls through */
  17278. case MATCH:
  17279. if (left === 0) { break inf_leave; }
  17280. copy = _out - left;
  17281. if (state.offset > copy) { /* copy from window */
  17282. copy = state.offset - copy;
  17283. if (copy > state.whave) {
  17284. if (state.sane) {
  17285. strm.msg = 'invalid distance too far back';
  17286. state.mode = BAD;
  17287. break;
  17288. }
  17289. // (!) This block is disabled in zlib defailts,
  17290. // don't enable it for binary compatibility
  17291. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  17292. // Trace((stderr, "inflate.c too far\n"));
  17293. // copy -= state.whave;
  17294. // if (copy > state.length) { copy = state.length; }
  17295. // if (copy > left) { copy = left; }
  17296. // left -= copy;
  17297. // state.length -= copy;
  17298. // do {
  17299. // output[put++] = 0;
  17300. // } while (--copy);
  17301. // if (state.length === 0) { state.mode = LEN; }
  17302. // break;
  17303. //#endif
  17304. }
  17305. if (copy > state.wnext) {
  17306. copy -= state.wnext;
  17307. from = state.wsize - copy;
  17308. }
  17309. else {
  17310. from = state.wnext - copy;
  17311. }
  17312. if (copy > state.length) { copy = state.length; }
  17313. from_source = state.window;
  17314. }
  17315. else { /* copy from output */
  17316. from_source = output;
  17317. from = put - state.offset;
  17318. copy = state.length;
  17319. }
  17320. if (copy > left) { copy = left; }
  17321. left -= copy;
  17322. state.length -= copy;
  17323. do {
  17324. output[put++] = from_source[from++];
  17325. } while (--copy);
  17326. if (state.length === 0) { state.mode = LEN; }
  17327. break;
  17328. case LIT:
  17329. if (left === 0) { break inf_leave; }
  17330. output[put++] = state.length;
  17331. left--;
  17332. state.mode = LEN;
  17333. break;
  17334. case CHECK:
  17335. if (state.wrap) {
  17336. //=== NEEDBITS(32);
  17337. while (bits < 32) {
  17338. if (have === 0) { break inf_leave; }
  17339. have--;
  17340. // Use '|' insdead of '+' to make sure that result is signed
  17341. hold |= input[next++] << bits;
  17342. bits += 8;
  17343. }
  17344. //===//
  17345. _out -= left;
  17346. strm.total_out += _out;
  17347. state.total += _out;
  17348. if (_out) {
  17349. strm.adler = state.check =
  17350. /*UPDATE(state.check, put - _out, _out);*/
  17351. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  17352. }
  17353. _out = left;
  17354. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  17355. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  17356. strm.msg = 'incorrect data check';
  17357. state.mode = BAD;
  17358. break;
  17359. }
  17360. //=== INITBITS();
  17361. hold = 0;
  17362. bits = 0;
  17363. //===//
  17364. //Tracev((stderr, "inflate: check matches trailer\n"));
  17365. }
  17366. state.mode = LENGTH;
  17367. /* falls through */
  17368. case LENGTH:
  17369. if (state.wrap && state.flags) {
  17370. //=== NEEDBITS(32);
  17371. while (bits < 32) {
  17372. if (have === 0) { break inf_leave; }
  17373. have--;
  17374. hold += input[next++] << bits;
  17375. bits += 8;
  17376. }
  17377. //===//
  17378. if (hold !== (state.total & 0xffffffff)) {
  17379. strm.msg = 'incorrect length check';
  17380. state.mode = BAD;
  17381. break;
  17382. }
  17383. //=== INITBITS();
  17384. hold = 0;
  17385. bits = 0;
  17386. //===//
  17387. //Tracev((stderr, "inflate: length matches trailer\n"));
  17388. }
  17389. state.mode = DONE;
  17390. /* falls through */
  17391. case DONE:
  17392. ret = Z_STREAM_END;
  17393. break inf_leave;
  17394. case BAD:
  17395. ret = Z_DATA_ERROR;
  17396. break inf_leave;
  17397. case MEM:
  17398. return Z_MEM_ERROR;
  17399. case SYNC:
  17400. /* falls through */
  17401. default:
  17402. return Z_STREAM_ERROR;
  17403. }
  17404. }
  17405. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  17406. /*
  17407. Return from inflate(), updating the total counts and the check value.
  17408. If there was no progress during the inflate() call, return a buffer
  17409. error. Call updatewindow() to create and/or update the window state.
  17410. Note: a memory error from inflate() is non-recoverable.
  17411. */
  17412. //--- RESTORE() ---
  17413. strm.next_out = put;
  17414. strm.avail_out = left;
  17415. strm.next_in = next;
  17416. strm.avail_in = have;
  17417. state.hold = hold;
  17418. state.bits = bits;
  17419. //---
  17420. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  17421. (state.mode < CHECK || flush !== Z_FINISH))) {
  17422. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  17423. state.mode = MEM;
  17424. return Z_MEM_ERROR;
  17425. }
  17426. }
  17427. _in -= strm.avail_in;
  17428. _out -= strm.avail_out;
  17429. strm.total_in += _in;
  17430. strm.total_out += _out;
  17431. state.total += _out;
  17432. if (state.wrap && _out) {
  17433. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  17434. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  17435. }
  17436. strm.data_type = state.bits + (state.last ? 64 : 0) +
  17437. (state.mode === TYPE ? 128 : 0) +
  17438. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  17439. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  17440. ret = Z_BUF_ERROR;
  17441. }
  17442. return ret;
  17443. }
  17444. function inflateEnd(strm) {
  17445. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  17446. return Z_STREAM_ERROR;
  17447. }
  17448. var state = strm.state;
  17449. if (state.window) {
  17450. state.window = null;
  17451. }
  17452. strm.state = null;
  17453. return Z_OK;
  17454. }
  17455. function inflateGetHeader(strm, head) {
  17456. var state;
  17457. /* check state */
  17458. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17459. state = strm.state;
  17460. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  17461. /* save header structure */
  17462. state.head = head;
  17463. head.done = false;
  17464. return Z_OK;
  17465. }
  17466. exports.inflateReset = inflateReset;
  17467. exports.inflateReset2 = inflateReset2;
  17468. exports.inflateResetKeep = inflateResetKeep;
  17469. exports.inflateInit = inflateInit;
  17470. exports.inflateInit2 = inflateInit2;
  17471. exports.inflate = inflate;
  17472. exports.inflateEnd = inflateEnd;
  17473. exports.inflateGetHeader = inflateGetHeader;
  17474. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  17475. /* Not implemented
  17476. exports.inflateCopy = inflateCopy;
  17477. exports.inflateGetDictionary = inflateGetDictionary;
  17478. exports.inflateMark = inflateMark;
  17479. exports.inflatePrime = inflatePrime;
  17480. exports.inflateSetDictionary = inflateSetDictionary;
  17481. exports.inflateSync = inflateSync;
  17482. exports.inflateSyncPoint = inflateSyncPoint;
  17483. exports.inflateUndermine = inflateUndermine;
  17484. */
  17485. },{"../utils/common":52,"./adler32":54,"./crc32":56,"./inffast":59,"./inftrees":61}],61:[function(require,module,exports){
  17486. 'use strict';
  17487. var utils = require('../utils/common');
  17488. var MAXBITS = 15;
  17489. var ENOUGH_LENS = 852;
  17490. var ENOUGH_DISTS = 592;
  17491. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  17492. var CODES = 0;
  17493. var LENS = 1;
  17494. var DISTS = 2;
  17495. var lbase = [ /* Length codes 257..285 base */
  17496. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  17497. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  17498. ];
  17499. var lext = [ /* Length codes 257..285 extra */
  17500. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  17501. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  17502. ];
  17503. var dbase = [ /* Distance codes 0..29 base */
  17504. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  17505. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  17506. 8193, 12289, 16385, 24577, 0, 0
  17507. ];
  17508. var dext = [ /* Distance codes 0..29 extra */
  17509. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  17510. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  17511. 28, 28, 29, 29, 64, 64
  17512. ];
  17513. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  17514. {
  17515. var bits = opts.bits;
  17516. //here = opts.here; /* table entry for duplication */
  17517. var len = 0; /* a code's length in bits */
  17518. var sym = 0; /* index of code symbols */
  17519. var min = 0, max = 0; /* minimum and maximum code lengths */
  17520. var root = 0; /* number of index bits for root table */
  17521. var curr = 0; /* number of index bits for current table */
  17522. var drop = 0; /* code bits to drop for sub-table */
  17523. var left = 0; /* number of prefix codes available */
  17524. var used = 0; /* code entries in table used */
  17525. var huff = 0; /* Huffman code */
  17526. var incr; /* for incrementing code, index */
  17527. var fill; /* index for replicating entries */
  17528. var low; /* low bits for current root entry */
  17529. var mask; /* mask for low root bits */
  17530. var next; /* next available space in table */
  17531. var base = null; /* base value table to use */
  17532. var base_index = 0;
  17533. // var shoextra; /* extra bits table to use */
  17534. var end; /* use base and extra for symbol > end */
  17535. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  17536. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  17537. var extra = null;
  17538. var extra_index = 0;
  17539. var here_bits, here_op, here_val;
  17540. /*
  17541. Process a set of code lengths to create a canonical Huffman code. The
  17542. code lengths are lens[0..codes-1]. Each length corresponds to the
  17543. symbols 0..codes-1. The Huffman code is generated by first sorting the
  17544. symbols by length from short to long, and retaining the symbol order
  17545. for codes with equal lengths. Then the code starts with all zero bits
  17546. for the first code of the shortest length, and the codes are integer
  17547. increments for the same length, and zeros are appended as the length
  17548. increases. For the deflate format, these bits are stored backwards
  17549. from their more natural integer increment ordering, and so when the
  17550. decoding tables are built in the large loop below, the integer codes
  17551. are incremented backwards.
  17552. This routine assumes, but does not check, that all of the entries in
  17553. lens[] are in the range 0..MAXBITS. The caller must assure this.
  17554. 1..MAXBITS is interpreted as that code length. zero means that that
  17555. symbol does not occur in this code.
  17556. The codes are sorted by computing a count of codes for each length,
  17557. creating from that a table of starting indices for each length in the
  17558. sorted table, and then entering the symbols in order in the sorted
  17559. table. The sorted table is work[], with that space being provided by
  17560. the caller.
  17561. The length counts are used for other purposes as well, i.e. finding
  17562. the minimum and maximum length codes, determining if there are any
  17563. codes at all, checking for a valid set of lengths, and looking ahead
  17564. at length counts to determine sub-table sizes when building the
  17565. decoding tables.
  17566. */
  17567. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  17568. for (len = 0; len <= MAXBITS; len++) {
  17569. count[len] = 0;
  17570. }
  17571. for (sym = 0; sym < codes; sym++) {
  17572. count[lens[lens_index + sym]]++;
  17573. }
  17574. /* bound code lengths, force root to be within code lengths */
  17575. root = bits;
  17576. for (max = MAXBITS; max >= 1; max--) {
  17577. if (count[max] !== 0) { break; }
  17578. }
  17579. if (root > max) {
  17580. root = max;
  17581. }
  17582. if (max === 0) { /* no symbols to code at all */
  17583. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  17584. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  17585. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  17586. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  17587. //table.op[opts.table_index] = 64;
  17588. //table.bits[opts.table_index] = 1;
  17589. //table.val[opts.table_index++] = 0;
  17590. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  17591. opts.bits = 1;
  17592. return 0; /* no symbols, but wait for decoding to report error */
  17593. }
  17594. for (min = 1; min < max; min++) {
  17595. if (count[min] !== 0) { break; }
  17596. }
  17597. if (root < min) {
  17598. root = min;
  17599. }
  17600. /* check for an over-subscribed or incomplete set of lengths */
  17601. left = 1;
  17602. for (len = 1; len <= MAXBITS; len++) {
  17603. left <<= 1;
  17604. left -= count[len];
  17605. if (left < 0) {
  17606. return -1;
  17607. } /* over-subscribed */
  17608. }
  17609. if (left > 0 && (type === CODES || max !== 1)) {
  17610. return -1; /* incomplete set */
  17611. }
  17612. /* generate offsets into symbol table for each length for sorting */
  17613. offs[1] = 0;
  17614. for (len = 1; len < MAXBITS; len++) {
  17615. offs[len + 1] = offs[len] + count[len];
  17616. }
  17617. /* sort symbols by length, by symbol order within each length */
  17618. for (sym = 0; sym < codes; sym++) {
  17619. if (lens[lens_index + sym] !== 0) {
  17620. work[offs[lens[lens_index + sym]]++] = sym;
  17621. }
  17622. }
  17623. /*
  17624. Create and fill in decoding tables. In this loop, the table being
  17625. filled is at next and has curr index bits. The code being used is huff
  17626. with length len. That code is converted to an index by dropping drop
  17627. bits off of the bottom. For codes where len is less than drop + curr,
  17628. those top drop + curr - len bits are incremented through all values to
  17629. fill the table with replicated entries.
  17630. root is the number of index bits for the root table. When len exceeds
  17631. root, sub-tables are created pointed to by the root entry with an index
  17632. of the low root bits of huff. This is saved in low to check for when a
  17633. new sub-table should be started. drop is zero when the root table is
  17634. being filled, and drop is root when sub-tables are being filled.
  17635. When a new sub-table is needed, it is necessary to look ahead in the
  17636. code lengths to determine what size sub-table is needed. The length
  17637. counts are used for this, and so count[] is decremented as codes are
  17638. entered in the tables.
  17639. used keeps track of how many table entries have been allocated from the
  17640. provided *table space. It is checked for LENS and DIST tables against
  17641. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  17642. the initial root table size constants. See the comments in inftrees.h
  17643. for more information.
  17644. sym increments through all symbols, and the loop terminates when
  17645. all codes of length max, i.e. all codes, have been processed. This
  17646. routine permits incomplete codes, so another loop after this one fills
  17647. in the rest of the decoding tables with invalid code markers.
  17648. */
  17649. /* set up for code type */
  17650. // poor man optimization - use if-else instead of switch,
  17651. // to avoid deopts in old v8
  17652. if (type === CODES) {
  17653. base = extra = work; /* dummy value--not used */
  17654. end = 19;
  17655. } else if (type === LENS) {
  17656. base = lbase;
  17657. base_index -= 257;
  17658. extra = lext;
  17659. extra_index -= 257;
  17660. end = 256;
  17661. } else { /* DISTS */
  17662. base = dbase;
  17663. extra = dext;
  17664. end = -1;
  17665. }
  17666. /* initialize opts for loop */
  17667. huff = 0; /* starting code */
  17668. sym = 0; /* starting code symbol */
  17669. len = min; /* starting code length */
  17670. next = table_index; /* current table to fill in */
  17671. curr = root; /* current table index bits */
  17672. drop = 0; /* current bits to drop from code for index */
  17673. low = -1; /* trigger new sub-table when len > root */
  17674. used = 1 << root; /* use root table entries */
  17675. mask = used - 1; /* mask for comparing low */
  17676. /* check available table space */
  17677. if ((type === LENS && used > ENOUGH_LENS) ||
  17678. (type === DISTS && used > ENOUGH_DISTS)) {
  17679. return 1;
  17680. }
  17681. var i=0;
  17682. /* process all codes and make table entries */
  17683. for (;;) {
  17684. i++;
  17685. /* create table entry */
  17686. here_bits = len - drop;
  17687. if (work[sym] < end) {
  17688. here_op = 0;
  17689. here_val = work[sym];
  17690. }
  17691. else if (work[sym] > end) {
  17692. here_op = extra[extra_index + work[sym]];
  17693. here_val = base[base_index + work[sym]];
  17694. }
  17695. else {
  17696. here_op = 32 + 64; /* end of block */
  17697. here_val = 0;
  17698. }
  17699. /* replicate for those indices with low len bits equal to huff */
  17700. incr = 1 << (len - drop);
  17701. fill = 1 << curr;
  17702. min = fill; /* save offset to next table */
  17703. do {
  17704. fill -= incr;
  17705. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  17706. } while (fill !== 0);
  17707. /* backwards increment the len-bit code huff */
  17708. incr = 1 << (len - 1);
  17709. while (huff & incr) {
  17710. incr >>= 1;
  17711. }
  17712. if (incr !== 0) {
  17713. huff &= incr - 1;
  17714. huff += incr;
  17715. } else {
  17716. huff = 0;
  17717. }
  17718. /* go to next symbol, update count, len */
  17719. sym++;
  17720. if (--count[len] === 0) {
  17721. if (len === max) { break; }
  17722. len = lens[lens_index + work[sym]];
  17723. }
  17724. /* create new sub-table if needed */
  17725. if (len > root && (huff & mask) !== low) {
  17726. /* if first time, transition to sub-tables */
  17727. if (drop === 0) {
  17728. drop = root;
  17729. }
  17730. /* increment past last table */
  17731. next += min; /* here min is 1 << curr */
  17732. /* determine length of next table */
  17733. curr = len - drop;
  17734. left = 1 << curr;
  17735. while (curr + drop < max) {
  17736. left -= count[curr + drop];
  17737. if (left <= 0) { break; }
  17738. curr++;
  17739. left <<= 1;
  17740. }
  17741. /* check for enough space */
  17742. used += 1 << curr;
  17743. if ((type === LENS && used > ENOUGH_LENS) ||
  17744. (type === DISTS && used > ENOUGH_DISTS)) {
  17745. return 1;
  17746. }
  17747. /* point entry in root table to sub-table */
  17748. low = huff & mask;
  17749. /*table.op[low] = curr;
  17750. table.bits[low] = root;
  17751. table.val[low] = next - opts.table_index;*/
  17752. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  17753. }
  17754. }
  17755. /* fill in remaining table entry if code is incomplete (guaranteed to have
  17756. at most one remaining entry, since if the code is incomplete, the
  17757. maximum code length that was allowed to get this far is one bit) */
  17758. if (huff !== 0) {
  17759. //table.op[next + huff] = 64; /* invalid code marker */
  17760. //table.bits[next + huff] = len - drop;
  17761. //table.val[next + huff] = 0;
  17762. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  17763. }
  17764. /* set return parameters */
  17765. //opts.table_index += used;
  17766. opts.bits = root;
  17767. return 0;
  17768. };
  17769. },{"../utils/common":52}],62:[function(require,module,exports){
  17770. 'use strict';
  17771. module.exports = {
  17772. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  17773. '1': 'stream end', /* Z_STREAM_END 1 */
  17774. '0': '', /* Z_OK 0 */
  17775. '-1': 'file error', /* Z_ERRNO (-1) */
  17776. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  17777. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  17778. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  17779. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  17780. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  17781. };
  17782. },{}],63:[function(require,module,exports){
  17783. 'use strict';
  17784. var utils = require('../utils/common');
  17785. /* Public constants ==========================================================*/
  17786. /* ===========================================================================*/
  17787. //var Z_FILTERED = 1;
  17788. //var Z_HUFFMAN_ONLY = 2;
  17789. //var Z_RLE = 3;
  17790. var Z_FIXED = 4;
  17791. //var Z_DEFAULT_STRATEGY = 0;
  17792. /* Possible values of the data_type field (though see inflate()) */
  17793. var Z_BINARY = 0;
  17794. var Z_TEXT = 1;
  17795. //var Z_ASCII = 1; // = Z_TEXT
  17796. var Z_UNKNOWN = 2;
  17797. /*============================================================================*/
  17798. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  17799. // From zutil.h
  17800. var STORED_BLOCK = 0;
  17801. var STATIC_TREES = 1;
  17802. var DYN_TREES = 2;
  17803. /* The three kinds of block type */
  17804. var MIN_MATCH = 3;
  17805. var MAX_MATCH = 258;
  17806. /* The minimum and maximum match lengths */
  17807. // From deflate.h
  17808. /* ===========================================================================
  17809. * Internal compression state.
  17810. */
  17811. var LENGTH_CODES = 29;
  17812. /* number of length codes, not counting the special END_BLOCK code */
  17813. var LITERALS = 256;
  17814. /* number of literal bytes 0..255 */
  17815. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  17816. /* number of Literal or Length codes, including the END_BLOCK code */
  17817. var D_CODES = 30;
  17818. /* number of distance codes */
  17819. var BL_CODES = 19;
  17820. /* number of codes used to transfer the bit lengths */
  17821. var HEAP_SIZE = 2*L_CODES + 1;
  17822. /* maximum heap size */
  17823. var MAX_BITS = 15;
  17824. /* All codes must not exceed MAX_BITS bits */
  17825. var Buf_size = 16;
  17826. /* size of bit buffer in bi_buf */
  17827. /* ===========================================================================
  17828. * Constants
  17829. */
  17830. var MAX_BL_BITS = 7;
  17831. /* Bit length codes must not exceed MAX_BL_BITS bits */
  17832. var END_BLOCK = 256;
  17833. /* end of block literal code */
  17834. var REP_3_6 = 16;
  17835. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  17836. var REPZ_3_10 = 17;
  17837. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  17838. var REPZ_11_138 = 18;
  17839. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  17840. var extra_lbits = /* extra bits for each length code */
  17841. [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];
  17842. var extra_dbits = /* extra bits for each distance code */
  17843. [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];
  17844. var extra_blbits = /* extra bits for each bit length code */
  17845. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  17846. var bl_order =
  17847. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  17848. /* The lengths of the bit length codes are sent in order of decreasing
  17849. * probability, to avoid transmitting the lengths for unused bit length codes.
  17850. */
  17851. /* ===========================================================================
  17852. * Local data. These are initialized only once.
  17853. */
  17854. // We pre-fill arrays with 0 to avoid uninitialized gaps
  17855. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  17856. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  17857. var static_ltree = new Array((L_CODES+2) * 2);
  17858. zero(static_ltree);
  17859. /* The static literal tree. Since the bit lengths are imposed, there is no
  17860. * need for the L_CODES extra codes used during heap construction. However
  17861. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  17862. * below).
  17863. */
  17864. var static_dtree = new Array(D_CODES * 2);
  17865. zero(static_dtree);
  17866. /* The static distance tree. (Actually a trivial tree since all codes use
  17867. * 5 bits.)
  17868. */
  17869. var _dist_code = new Array(DIST_CODE_LEN);
  17870. zero(_dist_code);
  17871. /* Distance codes. The first 256 values correspond to the distances
  17872. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  17873. * the 15 bit distances.
  17874. */
  17875. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  17876. zero(_length_code);
  17877. /* length code for each normalized match length (0 == MIN_MATCH) */
  17878. var base_length = new Array(LENGTH_CODES);
  17879. zero(base_length);
  17880. /* First normalized length for each code (0 = MIN_MATCH) */
  17881. var base_dist = new Array(D_CODES);
  17882. zero(base_dist);
  17883. /* First normalized distance for each code (0 = distance of 1) */
  17884. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  17885. this.static_tree = static_tree; /* static tree or NULL */
  17886. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  17887. this.extra_base = extra_base; /* base index for extra_bits */
  17888. this.elems = elems; /* max number of elements in the tree */
  17889. this.max_length = max_length; /* max bit length for the codes */
  17890. // show if `static_tree` has data or dummy - needed for monomorphic objects
  17891. this.has_stree = static_tree && static_tree.length;
  17892. };
  17893. var static_l_desc;
  17894. var static_d_desc;
  17895. var static_bl_desc;
  17896. var TreeDesc = function(dyn_tree, stat_desc) {
  17897. this.dyn_tree = dyn_tree; /* the dynamic tree */
  17898. this.max_code = 0; /* largest code with non zero frequency */
  17899. this.stat_desc = stat_desc; /* the corresponding static tree */
  17900. };
  17901. function d_code(dist) {
  17902. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  17903. }
  17904. /* ===========================================================================
  17905. * Output a short LSB first on the stream.
  17906. * IN assertion: there is enough room in pendingBuf.
  17907. */
  17908. function put_short (s, w) {
  17909. // put_byte(s, (uch)((w) & 0xff));
  17910. // put_byte(s, (uch)((ush)(w) >> 8));
  17911. s.pending_buf[s.pending++] = (w) & 0xff;
  17912. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  17913. }
  17914. /* ===========================================================================
  17915. * Send a value on a given number of bits.
  17916. * IN assertion: length <= 16 and value fits in length bits.
  17917. */
  17918. function send_bits(s, value, length) {
  17919. if (s.bi_valid > (Buf_size - length)) {
  17920. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  17921. put_short(s, s.bi_buf);
  17922. s.bi_buf = value >> (Buf_size - s.bi_valid);
  17923. s.bi_valid += length - Buf_size;
  17924. } else {
  17925. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  17926. s.bi_valid += length;
  17927. }
  17928. }
  17929. function send_code(s, c, tree) {
  17930. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  17931. }
  17932. /* ===========================================================================
  17933. * Reverse the first len bits of a code, using straightforward code (a faster
  17934. * method would use a table)
  17935. * IN assertion: 1 <= len <= 15
  17936. */
  17937. function bi_reverse(code, len) {
  17938. var res = 0;
  17939. do {
  17940. res |= code & 1;
  17941. code >>>= 1;
  17942. res <<= 1;
  17943. } while (--len > 0);
  17944. return res >>> 1;
  17945. }
  17946. /* ===========================================================================
  17947. * Flush the bit buffer, keeping at most 7 bits in it.
  17948. */
  17949. function bi_flush(s) {
  17950. if (s.bi_valid === 16) {
  17951. put_short(s, s.bi_buf);
  17952. s.bi_buf = 0;
  17953. s.bi_valid = 0;
  17954. } else if (s.bi_valid >= 8) {
  17955. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  17956. s.bi_buf >>= 8;
  17957. s.bi_valid -= 8;
  17958. }
  17959. }
  17960. /* ===========================================================================
  17961. * Compute the optimal bit lengths for a tree and update the total bit length
  17962. * for the current block.
  17963. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  17964. * above are the tree nodes sorted by increasing frequency.
  17965. * OUT assertions: the field len is set to the optimal bit length, the
  17966. * array bl_count contains the frequencies for each bit length.
  17967. * The length opt_len is updated; static_len is also updated if stree is
  17968. * not null.
  17969. */
  17970. function gen_bitlen(s, desc)
  17971. // deflate_state *s;
  17972. // tree_desc *desc; /* the tree descriptor */
  17973. {
  17974. var tree = desc.dyn_tree;
  17975. var max_code = desc.max_code;
  17976. var stree = desc.stat_desc.static_tree;
  17977. var has_stree = desc.stat_desc.has_stree;
  17978. var extra = desc.stat_desc.extra_bits;
  17979. var base = desc.stat_desc.extra_base;
  17980. var max_length = desc.stat_desc.max_length;
  17981. var h; /* heap index */
  17982. var n, m; /* iterate over the tree elements */
  17983. var bits; /* bit length */
  17984. var xbits; /* extra bits */
  17985. var f; /* frequency */
  17986. var overflow = 0; /* number of elements with bit length too large */
  17987. for (bits = 0; bits <= MAX_BITS; bits++) {
  17988. s.bl_count[bits] = 0;
  17989. }
  17990. /* In a first pass, compute the optimal bit lengths (which may
  17991. * overflow in the case of the bit length tree).
  17992. */
  17993. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  17994. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  17995. n = s.heap[h];
  17996. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  17997. if (bits > max_length) {
  17998. bits = max_length;
  17999. overflow++;
  18000. }
  18001. tree[n*2 + 1]/*.Len*/ = bits;
  18002. /* We overwrite tree[n].Dad which is no longer needed */
  18003. if (n > max_code) { continue; } /* not a leaf node */
  18004. s.bl_count[bits]++;
  18005. xbits = 0;
  18006. if (n >= base) {
  18007. xbits = extra[n-base];
  18008. }
  18009. f = tree[n * 2]/*.Freq*/;
  18010. s.opt_len += f * (bits + xbits);
  18011. if (has_stree) {
  18012. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  18013. }
  18014. }
  18015. if (overflow === 0) { return; }
  18016. // Trace((stderr,"\nbit length overflow\n"));
  18017. /* This happens for example on obj2 and pic of the Calgary corpus */
  18018. /* Find the first bit length which could increase: */
  18019. do {
  18020. bits = max_length-1;
  18021. while (s.bl_count[bits] === 0) { bits--; }
  18022. s.bl_count[bits]--; /* move one leaf down the tree */
  18023. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  18024. s.bl_count[max_length]--;
  18025. /* The brother of the overflow item also moves one step up,
  18026. * but this does not affect bl_count[max_length]
  18027. */
  18028. overflow -= 2;
  18029. } while (overflow > 0);
  18030. /* Now recompute all bit lengths, scanning in increasing frequency.
  18031. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  18032. * lengths instead of fixing only the wrong ones. This idea is taken
  18033. * from 'ar' written by Haruhiko Okumura.)
  18034. */
  18035. for (bits = max_length; bits !== 0; bits--) {
  18036. n = s.bl_count[bits];
  18037. while (n !== 0) {
  18038. m = s.heap[--h];
  18039. if (m > max_code) { continue; }
  18040. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  18041. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  18042. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  18043. tree[m*2 + 1]/*.Len*/ = bits;
  18044. }
  18045. n--;
  18046. }
  18047. }
  18048. }
  18049. /* ===========================================================================
  18050. * Generate the codes for a given tree and bit counts (which need not be
  18051. * optimal).
  18052. * IN assertion: the array bl_count contains the bit length statistics for
  18053. * the given tree and the field len is set for all tree elements.
  18054. * OUT assertion: the field code is set for all tree elements of non
  18055. * zero code length.
  18056. */
  18057. function gen_codes(tree, max_code, bl_count)
  18058. // ct_data *tree; /* the tree to decorate */
  18059. // int max_code; /* largest code with non zero frequency */
  18060. // ushf *bl_count; /* number of codes at each bit length */
  18061. {
  18062. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  18063. var code = 0; /* running code value */
  18064. var bits; /* bit index */
  18065. var n; /* code index */
  18066. /* The distribution counts are first used to generate the code values
  18067. * without bit reversal.
  18068. */
  18069. for (bits = 1; bits <= MAX_BITS; bits++) {
  18070. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  18071. }
  18072. /* Check that the bit counts in bl_count are consistent. The last code
  18073. * must be all ones.
  18074. */
  18075. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  18076. // "inconsistent bit counts");
  18077. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  18078. for (n = 0; n <= max_code; n++) {
  18079. var len = tree[n*2 + 1]/*.Len*/;
  18080. if (len === 0) { continue; }
  18081. /* Now reverse the bits */
  18082. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  18083. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  18084. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  18085. }
  18086. }
  18087. /* ===========================================================================
  18088. * Initialize the various 'constant' tables.
  18089. */
  18090. function tr_static_init() {
  18091. var n; /* iterates over tree elements */
  18092. var bits; /* bit counter */
  18093. var length; /* length value */
  18094. var code; /* code value */
  18095. var dist; /* distance index */
  18096. var bl_count = new Array(MAX_BITS+1);
  18097. /* number of codes at each bit length for an optimal tree */
  18098. // do check in _tr_init()
  18099. //if (static_init_done) return;
  18100. /* For some embedded targets, global variables are not initialized: */
  18101. /*#ifdef NO_INIT_GLOBAL_POINTERS
  18102. static_l_desc.static_tree = static_ltree;
  18103. static_l_desc.extra_bits = extra_lbits;
  18104. static_d_desc.static_tree = static_dtree;
  18105. static_d_desc.extra_bits = extra_dbits;
  18106. static_bl_desc.extra_bits = extra_blbits;
  18107. #endif*/
  18108. /* Initialize the mapping length (0..255) -> length code (0..28) */
  18109. length = 0;
  18110. for (code = 0; code < LENGTH_CODES-1; code++) {
  18111. base_length[code] = length;
  18112. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  18113. _length_code[length++] = code;
  18114. }
  18115. }
  18116. //Assert (length == 256, "tr_static_init: length != 256");
  18117. /* Note that the length 255 (match length 258) can be represented
  18118. * in two different ways: code 284 + 5 bits or code 285, so we
  18119. * overwrite length_code[255] to use the best encoding:
  18120. */
  18121. _length_code[length-1] = code;
  18122. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  18123. dist = 0;
  18124. for (code = 0 ; code < 16; code++) {
  18125. base_dist[code] = dist;
  18126. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  18127. _dist_code[dist++] = code;
  18128. }
  18129. }
  18130. //Assert (dist == 256, "tr_static_init: dist != 256");
  18131. dist >>= 7; /* from now on, all distances are divided by 128 */
  18132. for (; code < D_CODES; code++) {
  18133. base_dist[code] = dist << 7;
  18134. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  18135. _dist_code[256 + dist++] = code;
  18136. }
  18137. }
  18138. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  18139. /* Construct the codes of the static literal tree */
  18140. for (bits = 0; bits <= MAX_BITS; bits++) {
  18141. bl_count[bits] = 0;
  18142. }
  18143. n = 0;
  18144. while (n <= 143) {
  18145. static_ltree[n*2 + 1]/*.Len*/ = 8;
  18146. n++;
  18147. bl_count[8]++;
  18148. }
  18149. while (n <= 255) {
  18150. static_ltree[n*2 + 1]/*.Len*/ = 9;
  18151. n++;
  18152. bl_count[9]++;
  18153. }
  18154. while (n <= 279) {
  18155. static_ltree[n*2 + 1]/*.Len*/ = 7;
  18156. n++;
  18157. bl_count[7]++;
  18158. }
  18159. while (n <= 287) {
  18160. static_ltree[n*2 + 1]/*.Len*/ = 8;
  18161. n++;
  18162. bl_count[8]++;
  18163. }
  18164. /* Codes 286 and 287 do not exist, but we must include them in the
  18165. * tree construction to get a canonical Huffman tree (longest code
  18166. * all ones)
  18167. */
  18168. gen_codes(static_ltree, L_CODES+1, bl_count);
  18169. /* The static distance tree is trivial: */
  18170. for (n = 0; n < D_CODES; n++) {
  18171. static_dtree[n*2 + 1]/*.Len*/ = 5;
  18172. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  18173. }
  18174. // Now data ready and we can init static trees
  18175. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  18176. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  18177. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  18178. //static_init_done = true;
  18179. }
  18180. /* ===========================================================================
  18181. * Initialize a new block.
  18182. */
  18183. function init_block(s) {
  18184. var n; /* iterates over tree elements */
  18185. /* Initialize the trees. */
  18186. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  18187. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  18188. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  18189. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  18190. s.opt_len = s.static_len = 0;
  18191. s.last_lit = s.matches = 0;
  18192. }
  18193. /* ===========================================================================
  18194. * Flush the bit buffer and align the output on a byte boundary
  18195. */
  18196. function bi_windup(s)
  18197. {
  18198. if (s.bi_valid > 8) {
  18199. put_short(s, s.bi_buf);
  18200. } else if (s.bi_valid > 0) {
  18201. //put_byte(s, (Byte)s->bi_buf);
  18202. s.pending_buf[s.pending++] = s.bi_buf;
  18203. }
  18204. s.bi_buf = 0;
  18205. s.bi_valid = 0;
  18206. }
  18207. /* ===========================================================================
  18208. * Copy a stored block, storing first the length and its
  18209. * one's complement if requested.
  18210. */
  18211. function copy_block(s, buf, len, header)
  18212. //DeflateState *s;
  18213. //charf *buf; /* the input data */
  18214. //unsigned len; /* its length */
  18215. //int header; /* true if block header must be written */
  18216. {
  18217. bi_windup(s); /* align on byte boundary */
  18218. if (header) {
  18219. put_short(s, len);
  18220. put_short(s, ~len);
  18221. }
  18222. // while (len--) {
  18223. // put_byte(s, *buf++);
  18224. // }
  18225. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  18226. s.pending += len;
  18227. }
  18228. /* ===========================================================================
  18229. * Compares to subtrees, using the tree depth as tie breaker when
  18230. * the subtrees have equal frequency. This minimizes the worst case length.
  18231. */
  18232. function smaller(tree, n, m, depth) {
  18233. var _n2 = n*2;
  18234. var _m2 = m*2;
  18235. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  18236. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  18237. }
  18238. /* ===========================================================================
  18239. * Restore the heap property by moving down the tree starting at node k,
  18240. * exchanging a node with the smallest of its two sons if necessary, stopping
  18241. * when the heap property is re-established (each father smaller than its
  18242. * two sons).
  18243. */
  18244. function pqdownheap(s, tree, k)
  18245. // deflate_state *s;
  18246. // ct_data *tree; /* the tree to restore */
  18247. // int k; /* node to move down */
  18248. {
  18249. var v = s.heap[k];
  18250. var j = k << 1; /* left son of k */
  18251. while (j <= s.heap_len) {
  18252. /* Set j to the smallest of the two sons: */
  18253. if (j < s.heap_len &&
  18254. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  18255. j++;
  18256. }
  18257. /* Exit if v is smaller than both sons */
  18258. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  18259. /* Exchange v with the smallest son */
  18260. s.heap[k] = s.heap[j];
  18261. k = j;
  18262. /* And continue down the tree, setting j to the left son of k */
  18263. j <<= 1;
  18264. }
  18265. s.heap[k] = v;
  18266. }
  18267. // inlined manually
  18268. // var SMALLEST = 1;
  18269. /* ===========================================================================
  18270. * Send the block data compressed using the given Huffman trees
  18271. */
  18272. function compress_block(s, ltree, dtree)
  18273. // deflate_state *s;
  18274. // const ct_data *ltree; /* literal tree */
  18275. // const ct_data *dtree; /* distance tree */
  18276. {
  18277. var dist; /* distance of matched string */
  18278. var lc; /* match length or unmatched char (if dist == 0) */
  18279. var lx = 0; /* running index in l_buf */
  18280. var code; /* the code to send */
  18281. var extra; /* number of extra bits to send */
  18282. if (s.last_lit !== 0) {
  18283. do {
  18284. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  18285. lc = s.pending_buf[s.l_buf + lx];
  18286. lx++;
  18287. if (dist === 0) {
  18288. send_code(s, lc, ltree); /* send a literal byte */
  18289. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  18290. } else {
  18291. /* Here, lc is the match length - MIN_MATCH */
  18292. code = _length_code[lc];
  18293. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  18294. extra = extra_lbits[code];
  18295. if (extra !== 0) {
  18296. lc -= base_length[code];
  18297. send_bits(s, lc, extra); /* send the extra length bits */
  18298. }
  18299. dist--; /* dist is now the match distance - 1 */
  18300. code = d_code(dist);
  18301. //Assert (code < D_CODES, "bad d_code");
  18302. send_code(s, code, dtree); /* send the distance code */
  18303. extra = extra_dbits[code];
  18304. if (extra !== 0) {
  18305. dist -= base_dist[code];
  18306. send_bits(s, dist, extra); /* send the extra distance bits */
  18307. }
  18308. } /* literal or match pair ? */
  18309. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  18310. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  18311. // "pendingBuf overflow");
  18312. } while (lx < s.last_lit);
  18313. }
  18314. send_code(s, END_BLOCK, ltree);
  18315. }
  18316. /* ===========================================================================
  18317. * Construct one Huffman tree and assigns the code bit strings and lengths.
  18318. * Update the total bit length for the current block.
  18319. * IN assertion: the field freq is set for all tree elements.
  18320. * OUT assertions: the fields len and code are set to the optimal bit length
  18321. * and corresponding code. The length opt_len is updated; static_len is
  18322. * also updated if stree is not null. The field max_code is set.
  18323. */
  18324. function build_tree(s, desc)
  18325. // deflate_state *s;
  18326. // tree_desc *desc; /* the tree descriptor */
  18327. {
  18328. var tree = desc.dyn_tree;
  18329. var stree = desc.stat_desc.static_tree;
  18330. var has_stree = desc.stat_desc.has_stree;
  18331. var elems = desc.stat_desc.elems;
  18332. var n, m; /* iterate over heap elements */
  18333. var max_code = -1; /* largest code with non zero frequency */
  18334. var node; /* new node being created */
  18335. /* Construct the initial heap, with least frequent element in
  18336. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  18337. * heap[0] is not used.
  18338. */
  18339. s.heap_len = 0;
  18340. s.heap_max = HEAP_SIZE;
  18341. for (n = 0; n < elems; n++) {
  18342. if (tree[n * 2]/*.Freq*/ !== 0) {
  18343. s.heap[++s.heap_len] = max_code = n;
  18344. s.depth[n] = 0;
  18345. } else {
  18346. tree[n*2 + 1]/*.Len*/ = 0;
  18347. }
  18348. }
  18349. /* The pkzip format requires that at least one distance code exists,
  18350. * and that at least one bit should be sent even if there is only one
  18351. * possible code. So to avoid special checks later on we force at least
  18352. * two codes of non zero frequency.
  18353. */
  18354. while (s.heap_len < 2) {
  18355. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  18356. tree[node * 2]/*.Freq*/ = 1;
  18357. s.depth[node] = 0;
  18358. s.opt_len--;
  18359. if (has_stree) {
  18360. s.static_len -= stree[node*2 + 1]/*.Len*/;
  18361. }
  18362. /* node is 0 or 1 so it does not have extra bits */
  18363. }
  18364. desc.max_code = max_code;
  18365. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  18366. * establish sub-heaps of increasing lengths:
  18367. */
  18368. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  18369. /* Construct the Huffman tree by repeatedly combining the least two
  18370. * frequent nodes.
  18371. */
  18372. node = elems; /* next internal node of the tree */
  18373. do {
  18374. //pqremove(s, tree, n); /* n = node of least frequency */
  18375. /*** pqremove ***/
  18376. n = s.heap[1/*SMALLEST*/];
  18377. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  18378. pqdownheap(s, tree, 1/*SMALLEST*/);
  18379. /***/
  18380. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  18381. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  18382. s.heap[--s.heap_max] = m;
  18383. /* Create a new node father of n and m */
  18384. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  18385. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  18386. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  18387. /* and insert the new node in the heap */
  18388. s.heap[1/*SMALLEST*/] = node++;
  18389. pqdownheap(s, tree, 1/*SMALLEST*/);
  18390. } while (s.heap_len >= 2);
  18391. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  18392. /* At this point, the fields freq and dad are set. We can now
  18393. * generate the bit lengths.
  18394. */
  18395. gen_bitlen(s, desc);
  18396. /* The field len is now set, we can generate the bit codes */
  18397. gen_codes(tree, max_code, s.bl_count);
  18398. }
  18399. /* ===========================================================================
  18400. * Scan a literal or distance tree to determine the frequencies of the codes
  18401. * in the bit length tree.
  18402. */
  18403. function scan_tree(s, tree, max_code)
  18404. // deflate_state *s;
  18405. // ct_data *tree; /* the tree to be scanned */
  18406. // int max_code; /* and its largest code of non zero frequency */
  18407. {
  18408. var n; /* iterates over all tree elements */
  18409. var prevlen = -1; /* last emitted length */
  18410. var curlen; /* length of current code */
  18411. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  18412. var count = 0; /* repeat count of the current code */
  18413. var max_count = 7; /* max repeat count */
  18414. var min_count = 4; /* min repeat count */
  18415. if (nextlen === 0) {
  18416. max_count = 138;
  18417. min_count = 3;
  18418. }
  18419. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  18420. for (n = 0; n <= max_code; n++) {
  18421. curlen = nextlen;
  18422. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  18423. if (++count < max_count && curlen === nextlen) {
  18424. continue;
  18425. } else if (count < min_count) {
  18426. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  18427. } else if (curlen !== 0) {
  18428. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  18429. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  18430. } else if (count <= 10) {
  18431. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  18432. } else {
  18433. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  18434. }
  18435. count = 0;
  18436. prevlen = curlen;
  18437. if (nextlen === 0) {
  18438. max_count = 138;
  18439. min_count = 3;
  18440. } else if (curlen === nextlen) {
  18441. max_count = 6;
  18442. min_count = 3;
  18443. } else {
  18444. max_count = 7;
  18445. min_count = 4;
  18446. }
  18447. }
  18448. }
  18449. /* ===========================================================================
  18450. * Send a literal or distance tree in compressed form, using the codes in
  18451. * bl_tree.
  18452. */
  18453. function send_tree(s, tree, max_code)
  18454. // deflate_state *s;
  18455. // ct_data *tree; /* the tree to be scanned */
  18456. // int max_code; /* and its largest code of non zero frequency */
  18457. {
  18458. var n; /* iterates over all tree elements */
  18459. var prevlen = -1; /* last emitted length */
  18460. var curlen; /* length of current code */
  18461. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  18462. var count = 0; /* repeat count of the current code */
  18463. var max_count = 7; /* max repeat count */
  18464. var min_count = 4; /* min repeat count */
  18465. /* tree[max_code+1].Len = -1; */ /* guard already set */
  18466. if (nextlen === 0) {
  18467. max_count = 138;
  18468. min_count = 3;
  18469. }
  18470. for (n = 0; n <= max_code; n++) {
  18471. curlen = nextlen;
  18472. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  18473. if (++count < max_count && curlen === nextlen) {
  18474. continue;
  18475. } else if (count < min_count) {
  18476. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  18477. } else if (curlen !== 0) {
  18478. if (curlen !== prevlen) {
  18479. send_code(s, curlen, s.bl_tree);
  18480. count--;
  18481. }
  18482. //Assert(count >= 3 && count <= 6, " 3_6?");
  18483. send_code(s, REP_3_6, s.bl_tree);
  18484. send_bits(s, count-3, 2);
  18485. } else if (count <= 10) {
  18486. send_code(s, REPZ_3_10, s.bl_tree);
  18487. send_bits(s, count-3, 3);
  18488. } else {
  18489. send_code(s, REPZ_11_138, s.bl_tree);
  18490. send_bits(s, count-11, 7);
  18491. }
  18492. count = 0;
  18493. prevlen = curlen;
  18494. if (nextlen === 0) {
  18495. max_count = 138;
  18496. min_count = 3;
  18497. } else if (curlen === nextlen) {
  18498. max_count = 6;
  18499. min_count = 3;
  18500. } else {
  18501. max_count = 7;
  18502. min_count = 4;
  18503. }
  18504. }
  18505. }
  18506. /* ===========================================================================
  18507. * Construct the Huffman tree for the bit lengths and return the index in
  18508. * bl_order of the last bit length code to send.
  18509. */
  18510. function build_bl_tree(s) {
  18511. var max_blindex; /* index of last bit length code of non zero freq */
  18512. /* Determine the bit length frequencies for literal and distance trees */
  18513. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  18514. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  18515. /* Build the bit length tree: */
  18516. build_tree(s, s.bl_desc);
  18517. /* opt_len now includes the length of the tree representations, except
  18518. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  18519. */
  18520. /* Determine the number of bit length codes to send. The pkzip format
  18521. * requires that at least 4 bit length codes be sent. (appnote.txt says
  18522. * 3 but the actual value used is 4.)
  18523. */
  18524. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  18525. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  18526. break;
  18527. }
  18528. }
  18529. /* Update opt_len to include the bit length tree and counts */
  18530. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  18531. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  18532. // s->opt_len, s->static_len));
  18533. return max_blindex;
  18534. }
  18535. /* ===========================================================================
  18536. * Send the header for a block using dynamic Huffman trees: the counts, the
  18537. * lengths of the bit length codes, the literal tree and the distance tree.
  18538. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  18539. */
  18540. function send_all_trees(s, lcodes, dcodes, blcodes)
  18541. // deflate_state *s;
  18542. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  18543. {
  18544. var rank; /* index in bl_order */
  18545. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  18546. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  18547. // "too many codes");
  18548. //Tracev((stderr, "\nbl counts: "));
  18549. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  18550. send_bits(s, dcodes-1, 5);
  18551. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  18552. for (rank = 0; rank < blcodes; rank++) {
  18553. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  18554. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  18555. }
  18556. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  18557. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  18558. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  18559. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  18560. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  18561. }
  18562. /* ===========================================================================
  18563. * Check if the data type is TEXT or BINARY, using the following algorithm:
  18564. * - TEXT if the two conditions below are satisfied:
  18565. * a) There are no non-portable control characters belonging to the
  18566. * "black list" (0..6, 14..25, 28..31).
  18567. * b) There is at least one printable character belonging to the
  18568. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  18569. * - BINARY otherwise.
  18570. * - The following partially-portable control characters form a
  18571. * "gray list" that is ignored in this detection algorithm:
  18572. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  18573. * IN assertion: the fields Freq of dyn_ltree are set.
  18574. */
  18575. function detect_data_type(s) {
  18576. /* black_mask is the bit mask of black-listed bytes
  18577. * set bits 0..6, 14..25, and 28..31
  18578. * 0xf3ffc07f = binary 11110011111111111100000001111111
  18579. */
  18580. var black_mask = 0xf3ffc07f;
  18581. var n;
  18582. /* Check for non-textual ("black-listed") bytes. */
  18583. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  18584. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  18585. return Z_BINARY;
  18586. }
  18587. }
  18588. /* Check for textual ("white-listed") bytes. */
  18589. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  18590. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  18591. return Z_TEXT;
  18592. }
  18593. for (n = 32; n < LITERALS; n++) {
  18594. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  18595. return Z_TEXT;
  18596. }
  18597. }
  18598. /* There are no "black-listed" or "white-listed" bytes:
  18599. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  18600. */
  18601. return Z_BINARY;
  18602. }
  18603. var static_init_done = false;
  18604. /* ===========================================================================
  18605. * Initialize the tree data structures for a new zlib stream.
  18606. */
  18607. function _tr_init(s)
  18608. {
  18609. if (!static_init_done) {
  18610. tr_static_init();
  18611. static_init_done = true;
  18612. }
  18613. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  18614. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  18615. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  18616. s.bi_buf = 0;
  18617. s.bi_valid = 0;
  18618. /* Initialize the first block of the first file: */
  18619. init_block(s);
  18620. }
  18621. /* ===========================================================================
  18622. * Send a stored block
  18623. */
  18624. function _tr_stored_block(s, buf, stored_len, last)
  18625. //DeflateState *s;
  18626. //charf *buf; /* input block */
  18627. //ulg stored_len; /* length of input block */
  18628. //int last; /* one if this is the last block for a file */
  18629. {
  18630. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  18631. copy_block(s, buf, stored_len, true); /* with header */
  18632. }
  18633. /* ===========================================================================
  18634. * Send one empty static block to give enough lookahead for inflate.
  18635. * This takes 10 bits, of which 7 may remain in the bit buffer.
  18636. */
  18637. function _tr_align(s) {
  18638. send_bits(s, STATIC_TREES<<1, 3);
  18639. send_code(s, END_BLOCK, static_ltree);
  18640. bi_flush(s);
  18641. }
  18642. /* ===========================================================================
  18643. * Determine the best encoding for the current block: dynamic trees, static
  18644. * trees or store, and output the encoded block to the zip file.
  18645. */
  18646. function _tr_flush_block(s, buf, stored_len, last)
  18647. //DeflateState *s;
  18648. //charf *buf; /* input block, or NULL if too old */
  18649. //ulg stored_len; /* length of input block */
  18650. //int last; /* one if this is the last block for a file */
  18651. {
  18652. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  18653. var max_blindex = 0; /* index of last bit length code of non zero freq */
  18654. /* Build the Huffman trees unless a stored block is forced */
  18655. if (s.level > 0) {
  18656. /* Check if the file is binary or text */
  18657. if (s.strm.data_type === Z_UNKNOWN) {
  18658. s.strm.data_type = detect_data_type(s);
  18659. }
  18660. /* Construct the literal and distance trees */
  18661. build_tree(s, s.l_desc);
  18662. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  18663. // s->static_len));
  18664. build_tree(s, s.d_desc);
  18665. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  18666. // s->static_len));
  18667. /* At this point, opt_len and static_len are the total bit lengths of
  18668. * the compressed block data, excluding the tree representations.
  18669. */
  18670. /* Build the bit length tree for the above two trees, and get the index
  18671. * in bl_order of the last bit length code to send.
  18672. */
  18673. max_blindex = build_bl_tree(s);
  18674. /* Determine the best encoding. Compute the block lengths in bytes. */
  18675. opt_lenb = (s.opt_len+3+7) >>> 3;
  18676. static_lenb = (s.static_len+3+7) >>> 3;
  18677. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  18678. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  18679. // s->last_lit));
  18680. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  18681. } else {
  18682. // Assert(buf != (char*)0, "lost buf");
  18683. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  18684. }
  18685. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  18686. /* 4: two words for the lengths */
  18687. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  18688. * Otherwise we can't have processed more than WSIZE input bytes since
  18689. * the last block flush, because compression would have been
  18690. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  18691. * transform a block into a stored block.
  18692. */
  18693. _tr_stored_block(s, buf, stored_len, last);
  18694. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  18695. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  18696. compress_block(s, static_ltree, static_dtree);
  18697. } else {
  18698. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  18699. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  18700. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  18701. }
  18702. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  18703. /* The above check is made mod 2^32, for files larger than 512 MB
  18704. * and uLong implemented on 32 bits.
  18705. */
  18706. init_block(s);
  18707. if (last) {
  18708. bi_windup(s);
  18709. }
  18710. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  18711. // s->compressed_len-7*last));
  18712. }
  18713. /* ===========================================================================
  18714. * Save the match info and tally the frequency counts. Return true if
  18715. * the current block must be flushed.
  18716. */
  18717. function _tr_tally(s, dist, lc)
  18718. // deflate_state *s;
  18719. // unsigned dist; /* distance of matched string */
  18720. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  18721. {
  18722. //var out_length, in_length, dcode;
  18723. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  18724. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  18725. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  18726. s.last_lit++;
  18727. if (dist === 0) {
  18728. /* lc is the unmatched char */
  18729. s.dyn_ltree[lc*2]/*.Freq*/++;
  18730. } else {
  18731. s.matches++;
  18732. /* Here, lc is the match length - MIN_MATCH */
  18733. dist--; /* dist = match distance - 1 */
  18734. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  18735. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  18736. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  18737. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  18738. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  18739. }
  18740. // (!) This block is disabled in zlib defailts,
  18741. // don't enable it for binary compatibility
  18742. //#ifdef TRUNCATE_BLOCK
  18743. // /* Try to guess if it is profitable to stop the current block here */
  18744. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  18745. // /* Compute an upper bound for the compressed length */
  18746. // out_length = s.last_lit*8;
  18747. // in_length = s.strstart - s.block_start;
  18748. //
  18749. // for (dcode = 0; dcode < D_CODES; dcode++) {
  18750. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  18751. // }
  18752. // out_length >>>= 3;
  18753. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  18754. // // s->last_lit, in_length, out_length,
  18755. // // 100L - out_length*100L/in_length));
  18756. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  18757. // return true;
  18758. // }
  18759. // }
  18760. //#endif
  18761. return (s.last_lit === s.lit_bufsize-1);
  18762. /* We avoid equality with lit_bufsize because of wraparound at 64K
  18763. * on 16 bit machines and because stored blocks are restricted to
  18764. * 64K-1 bytes.
  18765. */
  18766. }
  18767. exports._tr_init = _tr_init;
  18768. exports._tr_stored_block = _tr_stored_block;
  18769. exports._tr_flush_block = _tr_flush_block;
  18770. exports._tr_tally = _tr_tally;
  18771. exports._tr_align = _tr_align;
  18772. },{"../utils/common":52}],64:[function(require,module,exports){
  18773. 'use strict';
  18774. function ZStream() {
  18775. /* next input byte */
  18776. this.input = null; // JS specific, because we have no pointers
  18777. this.next_in = 0;
  18778. /* number of bytes available at input */
  18779. this.avail_in = 0;
  18780. /* total number of input bytes read so far */
  18781. this.total_in = 0;
  18782. /* next output byte should be put there */
  18783. this.output = null; // JS specific, because we have no pointers
  18784. this.next_out = 0;
  18785. /* remaining free space at output */
  18786. this.avail_out = 0;
  18787. /* total number of bytes output so far */
  18788. this.total_out = 0;
  18789. /* last error message, NULL if no error */
  18790. this.msg = ''/*Z_NULL*/;
  18791. /* not visible by applications */
  18792. this.state = null;
  18793. /* best guess about the data type: binary or text */
  18794. this.data_type = 2/*Z_UNKNOWN*/;
  18795. /* adler32 value of the uncompressed data */
  18796. this.adler = 0;
  18797. }
  18798. module.exports = ZStream;
  18799. },{}],65:[function(require,module,exports){
  18800. /* Copyright @ 2015 Atlassian Pty Ltd
  18801. *
  18802. * Licensed under the Apache License, Version 2.0 (the "License");
  18803. * you may not use this file except in compliance with the License.
  18804. * You may obtain a copy of the License at
  18805. *
  18806. * http://www.apache.org/licenses/LICENSE-2.0
  18807. *
  18808. * Unless required by applicable law or agreed to in writing, software
  18809. * distributed under the License is distributed on an "AS IS" BASIS,
  18810. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18811. * See the License for the specific language governing permissions and
  18812. * limitations under the License.
  18813. */
  18814. module.exports = function arrayEquals(array) {
  18815. // if the other array is a falsy value, return
  18816. if (!array)
  18817. return false;
  18818. // compare lengths - can save a lot of time
  18819. if (this.length != array.length)
  18820. return false;
  18821. for (var i = 0, l = this.length; i < l; i++) {
  18822. // Check if we have nested arrays
  18823. if (this[i] instanceof Array && array[i] instanceof Array) {
  18824. // recurse into the nested arrays
  18825. if (!arrayEquals.apply(this[i], [array[i]]))
  18826. return false;
  18827. } else if (this[i] != array[i]) {
  18828. // Warning - two different object instances will never be equal:
  18829. // {x:20} != {x:20}
  18830. return false;
  18831. }
  18832. }
  18833. return true;
  18834. };
  18835. },{}],66:[function(require,module,exports){
  18836. /* Copyright @ 2015 Atlassian Pty Ltd
  18837. *
  18838. * Licensed under the Apache License, Version 2.0 (the "License");
  18839. * you may not use this file except in compliance with the License.
  18840. * You may obtain a copy of the License at
  18841. *
  18842. * http://www.apache.org/licenses/LICENSE-2.0
  18843. *
  18844. * Unless required by applicable law or agreed to in writing, software
  18845. * distributed under the License is distributed on an "AS IS" BASIS,
  18846. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18847. * See the License for the specific language governing permissions and
  18848. * limitations under the License.
  18849. */
  18850. exports.Interop = require('./interop');
  18851. },{"./interop":67}],67:[function(require,module,exports){
  18852. /* Copyright @ 2015 Atlassian Pty Ltd
  18853. *
  18854. * Licensed under the Apache License, Version 2.0 (the "License");
  18855. * you may not use this file except in compliance with the License.
  18856. * You may obtain a copy of the License at
  18857. *
  18858. * http://www.apache.org/licenses/LICENSE-2.0
  18859. *
  18860. * Unless required by applicable law or agreed to in writing, software
  18861. * distributed under the License is distributed on an "AS IS" BASIS,
  18862. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18863. * See the License for the specific language governing permissions and
  18864. * limitations under the License.
  18865. */
  18866. /* global RTCSessionDescription */
  18867. /* jshint -W097 */
  18868. "use strict";
  18869. var transform = require('./transform');
  18870. var arrayEquals = require('./array-equals');
  18871. function Interop() {
  18872. /**
  18873. * This map holds the most recent Unified Plan offer/answer SDP that was
  18874. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  18875. * the SDP string as values.
  18876. *
  18877. * @type {{}}
  18878. */
  18879. this.cache = {};
  18880. }
  18881. module.exports = Interop;
  18882. /**
  18883. * Returns the index of the first m-line with the given media type and with a
  18884. * direction which allows sending, in the last Unified Plan description with
  18885. * type "answer" converted to Plan B. Returns {null} if there is no saved
  18886. * answer, or if none of its m-lines with the given type allow sending.
  18887. * @param type the media type ("audio" or "video").
  18888. * @returns {*}
  18889. */
  18890. Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {
  18891. if (!this.cache.answer) {
  18892. return null;
  18893. }
  18894. var session = transform.parse(this.cache.answer);
  18895. if (session && session.media && Array.isArray(session.media)){
  18896. for (var i = 0; i < session.media.length; i++) {
  18897. if (session.media[i].type == type &&
  18898. (!session.media[i].direction /* default to sendrecv */ ||
  18899. session.media[i].direction === 'sendrecv' ||
  18900. session.media[i].direction === 'sendonly')){
  18901. return i;
  18902. }
  18903. }
  18904. }
  18905. return null;
  18906. };
  18907. /**
  18908. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  18909. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  18910. * application.
  18911. *
  18912. * @param desc
  18913. * @returns {*}
  18914. */
  18915. Interop.prototype.toPlanB = function(desc) {
  18916. var self = this;
  18917. //#region Preliminary input validation.
  18918. if (typeof desc !== 'object' || desc === null ||
  18919. typeof desc.sdp !== 'string') {
  18920. console.warn('An empty description was passed as an argument.');
  18921. return desc;
  18922. }
  18923. // Objectify the SDP for easier manipulation.
  18924. var session = transform.parse(desc.sdp);
  18925. // If the SDP contains no media, there's nothing to transform.
  18926. if (typeof session.media === 'undefined' ||
  18927. !Array.isArray(session.media) || session.media.length === 0) {
  18928. console.warn('The description has no media.');
  18929. return desc;
  18930. }
  18931. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  18932. // SDP has a video, an audio and a data "channel" at most.
  18933. if (session.media.length <= 3 && session.media.every(function(m) {
  18934. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  18935. })) {
  18936. console.warn('This description does not look like Unified Plan.');
  18937. return desc;
  18938. }
  18939. //#endregion
  18940. // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443
  18941. var sdp = desc.sdp;
  18942. var rewrite = false;
  18943. for (var i = 0; i < session.media.length; i++) {
  18944. var uLine = session.media[i];
  18945. uLine.rtp.forEach(function(rtp) {
  18946. if (rtp.codec === 'NULL')
  18947. {
  18948. rewrite = true;
  18949. var offer = transform.parse(self.cache['offer']);
  18950. rtp.codec = offer.media[i].rtp[0].codec;
  18951. }
  18952. });
  18953. };
  18954. if (rewrite) {
  18955. sdp = transform.write(session);
  18956. }
  18957. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  18958. // -> Unified Plan transformation.
  18959. this.cache[desc.type] = sdp;
  18960. //#region Convert from Unified Plan to Plan B.
  18961. // We rebuild the session.media array.
  18962. var media = session.media;
  18963. session.media = [];
  18964. // Associative array that maps channel types to channel objects for fast
  18965. // access to channel objects by their type, e.g. type2bl['audio']->channel
  18966. // obj.
  18967. var type2bl = {};
  18968. // Used to build the group:BUNDLE value after the channels construction
  18969. // loop.
  18970. var types = [];
  18971. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  18972. media.forEach(function(uLine) {
  18973. // rtcp-mux is required in the Plan B SDP.
  18974. if ((typeof uLine.rtcpMux !== 'string' ||
  18975. uLine.rtcpMux !== 'rtcp-mux') &&
  18976. uLine.direction !== 'inactive') {
  18977. throw new Error('Cannot convert to Plan B because m-lines ' +
  18978. 'without the rtcp-mux attribute were found.');
  18979. }
  18980. if (uLine.type === 'application') {
  18981. session.media.push(uLine);
  18982. types.push(uLine.mid);
  18983. return;
  18984. }
  18985. // If we don't have a channel for this uLine.type, then use this
  18986. // uLine as the channel basis.
  18987. if (typeof type2bl[uLine.type] === 'undefined') {
  18988. type2bl[uLine.type] = uLine;
  18989. }
  18990. // Add sources to the channel and handle a=msid.
  18991. if (typeof uLine.sources === 'object') {
  18992. Object.keys(uLine.sources).forEach(function(ssrc) {
  18993. if (typeof type2bl[uLine.type].sources !== 'object')
  18994. type2bl[uLine.type].sources = {};
  18995. // Assign the sources to the channel.
  18996. type2bl[uLine.type].sources[ssrc] =
  18997. uLine.sources[ssrc];
  18998. if (typeof uLine.msid !== 'undefined') {
  18999. // In Plan B the msid is an SSRC attribute. Also, we don't
  19000. // care about the obsolete label and mslabel attributes.
  19001. //
  19002. // Note that it is not guaranteed that the uLine will
  19003. // have an msid. recvonly channels in particular don't have
  19004. // one.
  19005. type2bl[uLine.type].sources[ssrc].msid =
  19006. uLine.msid;
  19007. }
  19008. // NOTE ssrcs in ssrc groups will share msids, as
  19009. // draft-uberti-rtcweb-plan-00 mandates.
  19010. });
  19011. }
  19012. // Add ssrc groups to the channel.
  19013. if (typeof uLine.ssrcGroups !== 'undefined' &&
  19014. Array.isArray(uLine.ssrcGroups)) {
  19015. // Create the ssrcGroups array, if it's not defined.
  19016. if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||
  19017. !Array.isArray(type2bl[uLine.type].ssrcGroups)) {
  19018. type2bl[uLine.type].ssrcGroups = [];
  19019. }
  19020. type2bl[uLine.type].ssrcGroups =
  19021. type2bl[uLine.type].ssrcGroups.concat(
  19022. uLine.ssrcGroups);
  19023. }
  19024. if (type2bl[uLine.type] === uLine) {
  19025. // Copy ICE related stuff from the principal media line.
  19026. uLine.candidates = media[0].candidates;
  19027. uLine.iceUfrag = media[0].iceUfrag;
  19028. uLine.icePwd = media[0].icePwd;
  19029. uLine.fingerprint = media[0].fingerprint;
  19030. // Plan B mids are in ['audio', 'video', 'data']
  19031. uLine.mid = uLine.type;
  19032. // Plan B doesn't support/need the bundle-only attribute.
  19033. delete uLine.bundleOnly;
  19034. // In Plan B the msid is an SSRC attribute.
  19035. delete uLine.msid;
  19036. // Used to build the group:BUNDLE value after this loop.
  19037. types.push(uLine.type);
  19038. // Add the channel to the new media array.
  19039. session.media.push(uLine);
  19040. }
  19041. });
  19042. // We regenerate the BUNDLE group with the new mids.
  19043. session.groups.some(function(group) {
  19044. if (group.type === 'BUNDLE') {
  19045. group.mids = types.join(' ');
  19046. return true;
  19047. }
  19048. });
  19049. // msid semantic
  19050. session.msidSemantic = {
  19051. semantic: 'WMS',
  19052. token: '*'
  19053. };
  19054. var resStr = transform.write(session);
  19055. return new RTCSessionDescription({
  19056. type: desc.type,
  19057. sdp: resStr
  19058. });
  19059. //#endregion
  19060. };
  19061. /**
  19062. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  19063. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  19064. * to FF.
  19065. *
  19066. * @param desc
  19067. * @returns {*}
  19068. */
  19069. Interop.prototype.toUnifiedPlan = function(desc) {
  19070. var self = this;
  19071. //#region Preliminary input validation.
  19072. if (typeof desc !== 'object' || desc === null ||
  19073. typeof desc.sdp !== 'string') {
  19074. console.warn('An empty description was passed as an argument.');
  19075. return desc;
  19076. }
  19077. var session = transform.parse(desc.sdp);
  19078. // If the SDP contains no media, there's nothing to transform.
  19079. if (typeof session.media === 'undefined' ||
  19080. !Array.isArray(session.media) || session.media.length === 0) {
  19081. console.warn('The description has no media.');
  19082. return desc;
  19083. }
  19084. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  19085. // a video, an audio and a data "channel" at most.
  19086. if (session.media.length > 3 || !session.media.every(function(m) {
  19087. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  19088. })) {
  19089. console.warn('This description does not look like Plan B.');
  19090. return desc;
  19091. }
  19092. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  19093. var mids = [];
  19094. session.media.forEach(function(m) {
  19095. mids.push(m.mid);
  19096. });
  19097. var hasBundle = false;
  19098. if (typeof session.groups !== 'undefined' &&
  19099. Array.isArray(session.groups)) {
  19100. hasBundle = session.groups.every(function(g) {
  19101. return g.type !== 'BUNDLE' ||
  19102. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  19103. });
  19104. }
  19105. if (!hasBundle) {
  19106. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  19107. " are not bundled were found.");
  19108. }
  19109. //#endregion
  19110. //#region Convert from Plan B to Unified Plan.
  19111. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  19112. // rebuild an equivalent Unified Plan offer/answer.
  19113. //
  19114. // For example, if this is a local answer (in Unified Plan style) that we
  19115. // convert to Plan B prior to handing it over to the application (the
  19116. // PeerConnection wrapper called us, for instance, after a successful
  19117. // createAnswer), we want to remember the m-line at which we've seen the
  19118. // (local) SSRC. That's because when the application wants to do call the
  19119. // SLD method, forcing us to do the inverse transformation (from Plan B to
  19120. // Unified Plan), we need to know to which m-line to assign the (local)
  19121. // SSRC. We also need to know all the other m-lines that the original
  19122. // answer had and include them in the transformed answer as well.
  19123. //
  19124. // Another example is if this is a remote offer that we convert to Plan B
  19125. // prior to giving it to the application, we want to remember the mid at
  19126. // which we've seen the (remote) SSRC.
  19127. //
  19128. // In the iteration that follows, we use the cached Unified Plan (if it
  19129. // exists) to assign mids to ssrcs.
  19130. var cached;
  19131. if (typeof this.cache[desc.type] !== 'undefined') {
  19132. cached = transform.parse(this.cache[desc.type]);
  19133. }
  19134. var recvonlySsrcs = {
  19135. audio: {},
  19136. video: {}
  19137. };
  19138. // A helper map that sends mids to m-line objects. We use it later to
  19139. // rebuild the Unified Plan style session.media array.
  19140. var mid2ul = {};
  19141. session.media.forEach(function(bLine) {
  19142. if ((typeof bLine.rtcpMux !== 'string' ||
  19143. bLine.rtcpMux !== 'rtcp-mux') &&
  19144. bLine.direction !== 'inactive') {
  19145. throw new Error("Cannot convert to Unified Plan because m-lines " +
  19146. "without the rtcp-mux attribute were found.");
  19147. }
  19148. if (bLine.type === 'application') {
  19149. mid2ul[bLine.mid] = bLine;
  19150. return;
  19151. }
  19152. // With rtcp-mux and bundle all the channels should have the same ICE
  19153. // stuff.
  19154. var sources = bLine.sources;
  19155. var ssrcGroups = bLine.ssrcGroups;
  19156. var candidates = bLine.candidates;
  19157. var iceUfrag = bLine.iceUfrag;
  19158. var icePwd = bLine.icePwd;
  19159. var fingerprint = bLine.fingerprint;
  19160. var port = bLine.port;
  19161. // We'll use the "bLine" object as a prototype for each new "mLine"
  19162. // that we create, but first we need to clean it up a bit.
  19163. delete bLine.sources;
  19164. delete bLine.ssrcGroups;
  19165. delete bLine.candidates;
  19166. delete bLine.iceUfrag;
  19167. delete bLine.icePwd;
  19168. delete bLine.fingerprint;
  19169. delete bLine.port;
  19170. delete bLine.mid;
  19171. // inverted ssrc group map
  19172. var ssrc2group = {};
  19173. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  19174. ssrcGroups.forEach(function (ssrcGroup) {
  19175. // TODO(gp) find out how to receive simulcast with FF. For the
  19176. // time being, hide it.
  19177. if (ssrcGroup.semantics === 'SIM') {
  19178. return;
  19179. }
  19180. // XXX This might brake if an SSRC is in more than one group
  19181. // for some reason.
  19182. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  19183. Array.isArray(ssrcGroup.ssrcs)) {
  19184. ssrcGroup.ssrcs.forEach(function (ssrc) {
  19185. if (typeof ssrc2group[ssrc] === 'undefined') {
  19186. ssrc2group[ssrc] = [];
  19187. }
  19188. ssrc2group[ssrc].push(ssrcGroup);
  19189. });
  19190. }
  19191. });
  19192. }
  19193. // ssrc to m-line index.
  19194. var ssrc2ml = {};
  19195. if (typeof sources === 'object') {
  19196. // Explode the Plan B channel sources with one m-line per source.
  19197. Object.keys(sources).forEach(function(ssrc) {
  19198. // The (unified) m-line for this SSRC. We either create it from
  19199. // scratch or, if it's a grouped SSRC, we re-use a related
  19200. // mline. In other words, if the source is grouped with another
  19201. // source, put the two together in the same m-line.
  19202. var uLine;
  19203. // We assume here that we are the answerer in the O/A, so any
  19204. // offers which we translate come from the remote side, while
  19205. // answers are local. So the check below is to make that we
  19206. // handle receive-only SSRCs in a special way only if they come
  19207. // from the remote side.
  19208. if (desc.type==='offer') {
  19209. // We want to detect SSRCs which are used by a remote peer
  19210. // in an m-line with direction=recvonly (i.e. they are
  19211. // being used for RTCP only).
  19212. // This information would have gotten lost if the remote
  19213. // peer used Unified Plan and their local description was
  19214. // translated to Plan B. So we use the lack of an MSID
  19215. // attribute to deduce a "receive only" SSRC.
  19216. if (!sources[ssrc].msid) {
  19217. recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];
  19218. // Receive-only SSRCs must not create new m-lines. We
  19219. // will assign them to an existing m-line later.
  19220. return;
  19221. }
  19222. }
  19223. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  19224. Array.isArray(ssrc2group[ssrc])) {
  19225. ssrc2group[ssrc].some(function (ssrcGroup) {
  19226. // ssrcGroup.ssrcs *is* an Array, no need to check
  19227. // again here.
  19228. return ssrcGroup.ssrcs.some(function (related) {
  19229. if (typeof ssrc2ml[related] === 'object') {
  19230. uLine = ssrc2ml[related];
  19231. return true;
  19232. }
  19233. });
  19234. });
  19235. }
  19236. if (typeof uLine === 'object') {
  19237. // the m-line already exists. Just add the source.
  19238. uLine.sources[ssrc] = sources[ssrc];
  19239. delete sources[ssrc].msid;
  19240. } else {
  19241. // Use the "bLine" as a prototype for the "uLine".
  19242. uLine = Object.create(bLine);
  19243. ssrc2ml[ssrc] = uLine;
  19244. if (typeof sources[ssrc].msid !== 'undefined') {
  19245. // Assign the msid of the source to the m-line. Note
  19246. // that it is not guaranteed that the source will have
  19247. // msid. In particular "recvonly" sources don't have an
  19248. // msid. Note that "recvonly" is a term only defined
  19249. // for m-lines.
  19250. uLine.msid = sources[ssrc].msid;
  19251. uLine.direction = 'sendrecv';
  19252. delete sources[ssrc].msid;
  19253. }
  19254. // We assign one SSRC per media line.
  19255. uLine.sources = {};
  19256. uLine.sources[ssrc] = sources[ssrc];
  19257. uLine.ssrcGroups = ssrc2group[ssrc];
  19258. // Use the cached Unified Plan SDP (if it exists) to assign
  19259. // SSRCs to mids.
  19260. if (typeof cached !== 'undefined' &&
  19261. typeof cached.media !== 'undefined' &&
  19262. Array.isArray(cached.media)) {
  19263. cached.media.forEach(function (m) {
  19264. if (typeof m.sources === 'object') {
  19265. Object.keys(m.sources).forEach(function (s) {
  19266. if (s === ssrc) {
  19267. uLine.mid = m.mid;
  19268. }
  19269. });
  19270. }
  19271. });
  19272. }
  19273. if (typeof uLine.mid === 'undefined') {
  19274. // If this is an SSRC that we see for the first time
  19275. // assign it a new mid. This is typically the case when
  19276. // this method is called to transform a remote
  19277. // description for the first time or when there is a
  19278. // new SSRC in the remote description because a new
  19279. // peer has joined the conference. Local SSRCs should
  19280. // have already been added to the map in the toPlanB
  19281. // method.
  19282. //
  19283. // Because FF generates answers in Unified Plan style,
  19284. // we MUST already have a cached answer with all the
  19285. // local SSRCs mapped to some m-line/mid.
  19286. if (desc.type === 'answer') {
  19287. throw new Error("An unmapped SSRC was found.");
  19288. }
  19289. uLine.mid = [bLine.type, '-', ssrc].join('');
  19290. }
  19291. // Include the candidates in the 1st media line.
  19292. uLine.candidates = candidates;
  19293. uLine.iceUfrag = iceUfrag;
  19294. uLine.icePwd = icePwd;
  19295. uLine.fingerprint = fingerprint;
  19296. uLine.port = port;
  19297. mid2ul[uLine.mid] = uLine;
  19298. }
  19299. });
  19300. }
  19301. });
  19302. // Rebuild the media array in the right order and add the missing mLines
  19303. // (missing from the Plan B SDP).
  19304. session.media = [];
  19305. mids = []; // reuse
  19306. if (desc.type === 'answer') {
  19307. // The media lines in the answer must match the media lines in the
  19308. // offer. The order is important too. Here we assume that Firefox is
  19309. // the answerer, so we merely have to use the reconstructed (unified)
  19310. // answer to update the cached (unified) answer accordingly.
  19311. //
  19312. // In the general case, one would have to use the cached (unified)
  19313. // offer to find the m-lines that are missing from the reconstructed
  19314. // answer, potentially grabbing them from the cached (unified) answer.
  19315. // One has to be careful with this approach because inactive m-lines do
  19316. // not always have an mid, making it tricky (impossible?) to find where
  19317. // exactly and which m-lines are missing from the reconstructed answer.
  19318. for (var i = 0; i < cached.media.length; i++) {
  19319. var uLine = cached.media[i];
  19320. if (typeof mid2ul[uLine.mid] === 'undefined') {
  19321. // The mid isn't in the reconstructed (unified) answer.
  19322. // This is either a (unified) m-line containing a remote
  19323. // track only, or a (unified) m-line containing a remote
  19324. // track and a local track that has been removed.
  19325. // In either case, it MUST exist in the cached
  19326. // (unified) answer.
  19327. //
  19328. // In case this is a removed local track, clean-up
  19329. // the (unified) m-line and make sure it's 'recvonly' or
  19330. // 'inactive'.
  19331. delete uLine.msid;
  19332. delete uLine.sources;
  19333. delete uLine.ssrcGroups;
  19334. if (!uLine.direction
  19335. || uLine.direction === 'sendrecv')
  19336. uLine.direction = 'recvonly';
  19337. else if (uLine.direction === 'sendonly')
  19338. uLine.direction = 'inactive';
  19339. } else {
  19340. // This is an (unified) m-line/channel that contains a local
  19341. // track (sendrecv or sendonly channel) or it's a unified
  19342. // recvonly m-line/channel. In either case, since we're
  19343. // going from PlanB -> Unified Plan this m-line MUST
  19344. // exist in the cached answer.
  19345. }
  19346. session.media.push(uLine);
  19347. if (typeof uLine.mid === 'string') {
  19348. // inactive lines don't/may not have an mid.
  19349. mids.push(uLine.mid);
  19350. }
  19351. }
  19352. } else {
  19353. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  19354. // under any circumstances. If we are no longer interested in sending a
  19355. // track, we just remove the msid and ssrc attributes and set it to
  19356. // either a=recvonly (as the reofferer, we must use recvonly if the
  19357. // other side was previously sending on the m-section, but we can also
  19358. // leave the possibility open if it wasn't previously in use), or
  19359. // a=inactive.
  19360. if (typeof cached !== 'undefined' &&
  19361. typeof cached.media !== 'undefined' &&
  19362. Array.isArray(cached.media)) {
  19363. cached.media.forEach(function(uLine) {
  19364. mids.push(uLine.mid);
  19365. if (typeof mid2ul[uLine.mid] !== 'undefined') {
  19366. session.media.push(mid2ul[uLine.mid]);
  19367. } else {
  19368. delete uLine.msid;
  19369. delete uLine.sources;
  19370. delete uLine.ssrcGroups;
  19371. if (!uLine.direction
  19372. || uLine.direction === 'sendrecv')
  19373. uLine.direction = 'recvonly';
  19374. if (!uLine.direction
  19375. || uLine.direction === 'sendonly')
  19376. uLine.direction = 'inactive';
  19377. session.media.push(uLine);
  19378. }
  19379. });
  19380. }
  19381. // Add all the remaining (new) m-lines of the transformed SDP.
  19382. Object.keys(mid2ul).forEach(function(mid) {
  19383. if (mids.indexOf(mid) === -1) {
  19384. mids.push(mid);
  19385. if (mid2ul[mid].direction === 'recvonly') {
  19386. // This is a remote recvonly channel. Add its SSRC to the
  19387. // appropriate sendrecv or sendonly channel.
  19388. // TODO(gp) what if we don't have sendrecv/sendonly
  19389. // channel?
  19390. session.media.some(function (uLine) {
  19391. if ((uLine.direction === 'sendrecv' ||
  19392. uLine.direction === 'sendonly') &&
  19393. uLine.type === mid2ul[mid].type) {
  19394. // mid2ul[mid] shouldn't have any ssrc-groups
  19395. Object.keys(mid2ul[mid].sources).forEach(
  19396. function (ssrc) {
  19397. uLine.sources[ssrc] =
  19398. mid2ul[mid].sources[ssrc];
  19399. });
  19400. return true;
  19401. }
  19402. });
  19403. } else {
  19404. session.media.push(mid2ul[mid]);
  19405. }
  19406. }
  19407. });
  19408. }
  19409. // After we have constructed the Plan Unified m-lines we can figure out
  19410. // where (in which m-line) to place the 'recvonly SSRCs'.
  19411. // Note: we assume here that we are the answerer in the O/A, so any offers
  19412. // which we translate come from the remote side, while answers are local
  19413. // (and so our last local description is cached as an 'answer').
  19414. ["audio", "video"].forEach(function (type) {
  19415. if (!session || !session.media || !Array.isArray(session.media))
  19416. return;
  19417. var idx = null;
  19418. if (Object.keys(recvonlySsrcs[type]).length > 0) {
  19419. idx = self.getFirstSendingIndexFromAnswer(type);
  19420. if (idx === null){
  19421. // If this is the first offer we receive, we don't have a
  19422. // cached answer. Assume that we will be sending media using
  19423. // the first m-line for each media type.
  19424. for (var i = 0; i < session.media.length; i++) {
  19425. if (session.media[i].type === type) {
  19426. idx = i;
  19427. break;
  19428. }
  19429. }
  19430. }
  19431. }
  19432. if (idx && session.media.length > idx) {
  19433. var mLine = session.media[idx];
  19434. Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {
  19435. if (mLine.sources && mLine.sources[ssrc]) {
  19436. console.warn("Replacing an existing SSRC.");
  19437. }
  19438. if (!mLine.sources) {
  19439. mLine.sources = {};
  19440. }
  19441. mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];
  19442. });
  19443. }
  19444. });
  19445. // We regenerate the BUNDLE group (since we regenerated the mids)
  19446. session.groups.some(function(group) {
  19447. if (group.type === 'BUNDLE') {
  19448. group.mids = mids.join(' ');
  19449. return true;
  19450. }
  19451. });
  19452. // msid semantic
  19453. session.msidSemantic = {
  19454. semantic: 'WMS',
  19455. token: '*'
  19456. };
  19457. var resStr = transform.write(session);
  19458. // Cache the transformed SDP (Unified Plan) for later re-use in this
  19459. // function.
  19460. this.cache[desc.type] = resStr;
  19461. return new RTCSessionDescription({
  19462. type: desc.type,
  19463. sdp: resStr
  19464. });
  19465. //#endregion
  19466. };
  19467. },{"./array-equals":65,"./transform":68}],68:[function(require,module,exports){
  19468. /* Copyright @ 2015 Atlassian Pty Ltd
  19469. *
  19470. * Licensed under the Apache License, Version 2.0 (the "License");
  19471. * you may not use this file except in compliance with the License.
  19472. * You may obtain a copy of the License at
  19473. *
  19474. * http://www.apache.org/licenses/LICENSE-2.0
  19475. *
  19476. * Unless required by applicable law or agreed to in writing, software
  19477. * distributed under the License is distributed on an "AS IS" BASIS,
  19478. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19479. * See the License for the specific language governing permissions and
  19480. * limitations under the License.
  19481. */
  19482. var transform = require('sdp-transform');
  19483. exports.write = function(session, opts) {
  19484. if (typeof session !== 'undefined' &&
  19485. typeof session.media !== 'undefined' &&
  19486. Array.isArray(session.media)) {
  19487. session.media.forEach(function (mLine) {
  19488. // expand sources to ssrcs
  19489. if (typeof mLine.sources !== 'undefined' &&
  19490. Object.keys(mLine.sources).length !== 0) {
  19491. mLine.ssrcs = [];
  19492. Object.keys(mLine.sources).forEach(function (ssrc) {
  19493. var source = mLine.sources[ssrc];
  19494. Object.keys(source).forEach(function (attribute) {
  19495. mLine.ssrcs.push({
  19496. id: ssrc,
  19497. attribute: attribute,
  19498. value: source[attribute]
  19499. });
  19500. });
  19501. });
  19502. delete mLine.sources;
  19503. }
  19504. // join ssrcs in ssrc groups
  19505. if (typeof mLine.ssrcGroups !== 'undefined' &&
  19506. Array.isArray(mLine.ssrcGroups)) {
  19507. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  19508. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  19509. Array.isArray(ssrcGroup.ssrcs)) {
  19510. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  19511. }
  19512. });
  19513. }
  19514. });
  19515. }
  19516. // join group mids
  19517. if (typeof session !== 'undefined' &&
  19518. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  19519. session.groups.forEach(function (g) {
  19520. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  19521. g.mids = g.mids.join(' ');
  19522. }
  19523. });
  19524. }
  19525. return transform.write(session, opts);
  19526. };
  19527. exports.parse = function(sdp) {
  19528. var session = transform.parse(sdp);
  19529. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  19530. Array.isArray(session.media)) {
  19531. session.media.forEach(function (mLine) {
  19532. // group sources attributes by ssrc
  19533. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  19534. mLine.sources = {};
  19535. mLine.ssrcs.forEach(function (ssrc) {
  19536. if (!mLine.sources[ssrc.id])
  19537. mLine.sources[ssrc.id] = {};
  19538. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  19539. });
  19540. delete mLine.ssrcs;
  19541. }
  19542. // split ssrcs in ssrc groups
  19543. if (typeof mLine.ssrcGroups !== 'undefined' &&
  19544. Array.isArray(mLine.ssrcGroups)) {
  19545. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  19546. if (typeof ssrcGroup.ssrcs === 'string') {
  19547. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  19548. }
  19549. });
  19550. }
  19551. });
  19552. }
  19553. // split group mids
  19554. if (typeof session !== 'undefined' &&
  19555. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  19556. session.groups.forEach(function (g) {
  19557. if (typeof g.mids === 'string') {
  19558. g.mids = g.mids.split(' ');
  19559. }
  19560. });
  19561. }
  19562. return session;
  19563. };
  19564. },{"sdp-transform":76}],69:[function(require,module,exports){
  19565. /* Copyright @ 2015 Atlassian Pty Ltd
  19566. *
  19567. * Licensed under the Apache License, Version 2.0 (the "License");
  19568. * you may not use this file except in compliance with the License.
  19569. * You may obtain a copy of the License at
  19570. *
  19571. * http://www.apache.org/licenses/LICENSE-2.0
  19572. *
  19573. * Unless required by applicable law or agreed to in writing, software
  19574. * distributed under the License is distributed on an "AS IS" BASIS,
  19575. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19576. * See the License for the specific language governing permissions and
  19577. * limitations under the License.
  19578. */
  19579. var transform = require('sdp-transform');
  19580. var transformUtils = require('./transform-utils');
  19581. var parseSsrcs = transformUtils.parseSsrcs;
  19582. var writeSsrcs = transformUtils.writeSsrcs;
  19583. //region Constants
  19584. var DEFAULT_NUM_OF_LAYERS = 3;
  19585. //endregion
  19586. //region Ctor
  19587. function Simulcast(options) {
  19588. this.options = options ? options : {};
  19589. if (!this.options.numOfLayers) {
  19590. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  19591. }
  19592. this.layers = [];
  19593. }
  19594. //endregion
  19595. //region Stateless private utility functions
  19596. /**
  19597. * Returns a random integer between min (included) and max (excluded)
  19598. * Using Math.round() gives a non-uniform distribution!
  19599. * @returns {number}
  19600. */
  19601. function generateSSRC() {
  19602. var min = 0, max = 0xffffffff;
  19603. return Math.floor(Math.random() * (max - min)) + min;
  19604. };
  19605. function processVideo(session, action) {
  19606. if (session == null || !Array.isArray(session.media)) {
  19607. return;
  19608. }
  19609. session.media.forEach(function (mLine) {
  19610. if (mLine.type === 'video') {
  19611. action(mLine);
  19612. }
  19613. });
  19614. }
  19615. function validateDescription(desc)
  19616. {
  19617. return desc && desc != null
  19618. && desc.type && desc.type != ''
  19619. && desc.sdp && desc.sdp != '';
  19620. }
  19621. function explodeRemoteSimulcast(mLine) {
  19622. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  19623. return;
  19624. }
  19625. var sources = parseSsrcs(mLine);
  19626. var order = [];
  19627. // Find the SIM group and explode its sources.
  19628. var j = mLine.ssrcGroups.length;
  19629. while (j--) {
  19630. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  19631. continue;
  19632. }
  19633. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  19634. for (var i = 0; i < simulcastSsrcs.length; i++) {
  19635. var ssrc = simulcastSsrcs[i];
  19636. order.push(ssrc);
  19637. var parts = sources[ssrc].msid.split(' ');
  19638. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  19639. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  19640. // Remove all the groups that this SSRC participates in.
  19641. mLine.ssrcGroups.forEach(function (relatedGroup) {
  19642. if (relatedGroup.semantics === 'SIM') {
  19643. return;
  19644. }
  19645. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  19646. if (relatedSsrcs.indexOf(ssrc) === -1) {
  19647. return;
  19648. }
  19649. // Nuke all the related SSRCs.
  19650. relatedSsrcs.forEach(function (relatedSSRC) {
  19651. sources[relatedSSRC].msid = sources[ssrc].msid;
  19652. sources[relatedSSRC].cname = sources[ssrc].cname;
  19653. if (relatedSSRC !== ssrc) {
  19654. order.push(relatedSSRC);
  19655. }
  19656. });
  19657. // Schedule the related group for nuking.
  19658. })
  19659. }
  19660. mLine.ssrcs = writeSsrcs(sources, order);
  19661. mLine.ssrcGroups.splice(j, 1);
  19662. };
  19663. }
  19664. function implodeRemoteSimulcast(mLine) {
  19665. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  19666. console.debug('Halt: There are no SSRC groups in the remote ' +
  19667. 'description.');
  19668. return;
  19669. }
  19670. var sources = parseSsrcs(mLine);
  19671. // Find the SIM group and nuke it.
  19672. mLine.ssrcGroups.forEach(function (simulcastGroup) {
  19673. if (simulcastGroup.semantics !== 'SIM') {
  19674. return;
  19675. }
  19676. console.debug("Imploding SIM group: " + simulcastGroup.ssrcs);
  19677. // Schedule the SIM group for nuking.
  19678. simulcastGroup.nuke = true;
  19679. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  19680. // Nuke all the higher layer SSRCs.
  19681. for (var i = 1; i < simulcastSsrcs.length; i++) {
  19682. var ssrc = simulcastSsrcs[i];
  19683. delete sources[ssrc];
  19684. // Remove all the groups that this SSRC participates in.
  19685. mLine.ssrcGroups.forEach(function (relatedGroup) {
  19686. if (relatedGroup.semantics === 'SIM') {
  19687. return;
  19688. }
  19689. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  19690. if (relatedSsrcs.indexOf(ssrc) === -1) {
  19691. return;
  19692. }
  19693. // Nuke all the related SSRCs.
  19694. relatedSsrcs.forEach(function (relatedSSRC) {
  19695. delete sources[relatedSSRC];
  19696. });
  19697. // Schedule the related group for nuking.
  19698. relatedGroup.nuke = true;
  19699. })
  19700. }
  19701. return;
  19702. });
  19703. mLine.ssrcs = writeSsrcs(sources);
  19704. // Nuke all the scheduled groups.
  19705. var i = mLine.ssrcGroups.length;
  19706. while (i--) {
  19707. if (mLine.ssrcGroups[i].nuke) {
  19708. mLine.ssrcGroups.splice(i, 1);
  19709. }
  19710. }
  19711. }
  19712. function removeGoogConference(mLine) {
  19713. if (!mLine || !Array.isArray(mLine.invalid)) {
  19714. return;
  19715. }
  19716. var i = mLine.invalid.length;
  19717. while (i--) {
  19718. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  19719. mLine.invalid.splice(i, 1);
  19720. }
  19721. }
  19722. }
  19723. function assertGoogConference(mLine) {
  19724. if (!mLine) {
  19725. return;
  19726. }
  19727. if (!Array.isArray(mLine.invalid)) {
  19728. mLine.invalid = [];
  19729. }
  19730. if (!mLine.invalid.some(
  19731. function (i) { return i.value === 'x-google-flag:conference' })) {
  19732. mLine.invalid.push({'value': 'x-google-flag:conference'});
  19733. }
  19734. }
  19735. //endregion
  19736. //region "Private" functions
  19737. /**
  19738. *
  19739. * @param mLine
  19740. * @private
  19741. */
  19742. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  19743. if (!mLine || mLine.type !== 'video') {
  19744. return;
  19745. }
  19746. var sources = parseSsrcs(mLine);
  19747. if (Object.keys(sources).length === 0) {
  19748. // no sources, disable simulcast.
  19749. if (this.layers.length !== 0) {
  19750. this.layers = [];
  19751. }
  19752. return;
  19753. }
  19754. // find the base layer (we'll reuse its msid and cname).
  19755. var baseLayerSSRC = Object.keys(sources)[0];
  19756. var baseLayer = sources[baseLayerSSRC];
  19757. // todo(gp) handle screen sharing.
  19758. // check if base CNAME has changed and reinitialise layers.
  19759. if (this.layers.length > 0
  19760. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  19761. this.layers = [];
  19762. }
  19763. // (re)initialise layers
  19764. if (this.layers.length < 1) {
  19765. // first push the base layer.
  19766. this.layers.push({
  19767. ssrc: baseLayerSSRC,
  19768. msid: baseLayer.msid,
  19769. cname: baseLayer.cname
  19770. });
  19771. var rtx = false; // RFC 4588
  19772. if (Array.isArray(mLine.rtp)) {
  19773. rtx = mLine.rtp.some(
  19774. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  19775. }
  19776. if (rtx) {
  19777. this.layers[0].rtx = generateSSRC();
  19778. }
  19779. // now push additional layers.
  19780. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  19781. var layer = { ssrc: generateSSRC() };
  19782. if (rtx) {
  19783. layer.rtx = generateSSRC();
  19784. }
  19785. this.layers.push(layer);
  19786. }
  19787. }
  19788. };
  19789. /**
  19790. *
  19791. * @param mLine
  19792. * @private
  19793. */
  19794. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  19795. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  19796. var sources = {};
  19797. var msid = this.layers[0].msid;
  19798. var cname = this.layers[0].cname;
  19799. var simulcastSsrcs = [];
  19800. var ssrcGroups = [];
  19801. for (var i = 0; i < this.layers.length; i++) {
  19802. var layer = this.layers[i];
  19803. sources[layer.ssrc] = { msid: msid, cname: cname };
  19804. simulcastSsrcs.push(layer.ssrc);
  19805. if (layer.rtx) {
  19806. sources[layer.rtx] = {
  19807. msid: msid,
  19808. cname: cname
  19809. }
  19810. ssrcGroups.push({
  19811. semantics: 'FID',
  19812. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  19813. });
  19814. }
  19815. }
  19816. ssrcGroups.push({
  19817. semantics: 'SIM',
  19818. ssrcs: simulcastSsrcs.join(' ')
  19819. });
  19820. mLine.ssrcGroups = ssrcGroups;
  19821. mLine.ssrcs = writeSsrcs(sources);
  19822. }
  19823. }
  19824. //endregion
  19825. //region "Public" functions
  19826. Simulcast.prototype.isSupported = function () {
  19827. return window.chrome;
  19828. // TODO this needs improvements. For example I doubt that Chrome in Android
  19829. // has simulcast support. Also, only recent versions of Chromium have native
  19830. // simulcast support.
  19831. }
  19832. /**
  19833. *
  19834. * @param desc
  19835. * @returns {RTCSessionDescription}
  19836. */
  19837. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  19838. if (!validateDescription(desc)) {
  19839. return desc;
  19840. }
  19841. var session = transform.parse(desc.sdp);
  19842. var self = this;
  19843. processVideo(session, function (mLine) {
  19844. // Handle simulcast reception.
  19845. if (self.options.explodeRemoteSimulcast) {
  19846. explodeRemoteSimulcast(mLine);
  19847. } else {
  19848. implodeRemoteSimulcast(mLine);
  19849. }
  19850. // If native simulcast is enabled, we must append the x-goog-conference
  19851. // attribute to the SDP.
  19852. if (self.layers.length < 1) {
  19853. removeGoogConference(mLine);
  19854. } else {
  19855. assertGoogConference(mLine);
  19856. }
  19857. });
  19858. return new RTCSessionDescription({
  19859. type: desc.type,
  19860. sdp: transform.write(session)
  19861. });
  19862. };
  19863. /**
  19864. *
  19865. * @param desc
  19866. * @returns {RTCSessionDescription}
  19867. */
  19868. Simulcast.prototype.mungeLocalDescription = function (desc) {
  19869. if (!validateDescription(desc) || !this.isSupported()) {
  19870. return desc;
  19871. }
  19872. var session = transform.parse(desc.sdp);
  19873. var self = this;
  19874. processVideo(session, function (mLine) {
  19875. // Initialize native simulcast layers, if not already done.
  19876. self._maybeInitializeLayers(mLine);
  19877. // Update the SDP with the simulcast layers.
  19878. self._restoreSimulcastView(mLine);
  19879. });
  19880. return new RTCSessionDescription({
  19881. type: desc.type,
  19882. sdp: transform.write(session)
  19883. });
  19884. };
  19885. //endregion
  19886. module.exports = Simulcast;
  19887. },{"./transform-utils":70,"sdp-transform":72}],70:[function(require,module,exports){
  19888. /* Copyright @ 2015 Atlassian Pty Ltd
  19889. *
  19890. * Licensed under the Apache License, Version 2.0 (the "License");
  19891. * you may not use this file except in compliance with the License.
  19892. * You may obtain a copy of the License at
  19893. *
  19894. * http://www.apache.org/licenses/LICENSE-2.0
  19895. *
  19896. * Unless required by applicable law or agreed to in writing, software
  19897. * distributed under the License is distributed on an "AS IS" BASIS,
  19898. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19899. * See the License for the specific language governing permissions and
  19900. * limitations under the License.
  19901. */
  19902. exports.writeSsrcs = function(sources, order) {
  19903. var ssrcs = [];
  19904. // expand sources to ssrcs
  19905. if (typeof sources !== 'undefined' &&
  19906. Object.keys(sources).length !== 0) {
  19907. if (Array.isArray(order)) {
  19908. for (var i = 0; i < order.length; i++) {
  19909. var ssrc = order[i];
  19910. var source = sources[ssrc];
  19911. Object.keys(source).forEach(function (attribute) {
  19912. ssrcs.push({
  19913. id: ssrc,
  19914. attribute: attribute,
  19915. value: source[attribute]
  19916. });
  19917. });
  19918. }
  19919. } else {
  19920. Object.keys(sources).forEach(function (ssrc) {
  19921. var source = sources[ssrc];
  19922. Object.keys(source).forEach(function (attribute) {
  19923. ssrcs.push({
  19924. id: ssrc,
  19925. attribute: attribute,
  19926. value: source[attribute]
  19927. });
  19928. });
  19929. });
  19930. }
  19931. }
  19932. return ssrcs;
  19933. };
  19934. exports.parseSsrcs = function (mLine) {
  19935. var sources = {};
  19936. // group sources attributes by ssrc.
  19937. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  19938. mLine.ssrcs.forEach(function (ssrc) {
  19939. if (!sources[ssrc.id])
  19940. sources[ssrc.id] = {};
  19941. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  19942. });
  19943. }
  19944. return sources;
  19945. };
  19946. },{}],71:[function(require,module,exports){
  19947. var grammar = module.exports = {
  19948. v: [{
  19949. name: 'version',
  19950. reg: /^(\d*)$/
  19951. }],
  19952. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  19953. // NB: sessionId will be a String in most cases because it is huge
  19954. name: 'origin',
  19955. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  19956. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  19957. format: "%s %s %d %s IP%d %s"
  19958. }],
  19959. // default parsing of these only (though some of these feel outdated)
  19960. s: [{ name: 'name' }],
  19961. i: [{ name: 'description' }],
  19962. u: [{ name: 'uri' }],
  19963. e: [{ name: 'email' }],
  19964. p: [{ name: 'phone' }],
  19965. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  19966. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  19967. //k: [{}], // outdated thing ignored
  19968. t: [{ //t=0 0
  19969. name: 'timing',
  19970. reg: /^(\d*) (\d*)/,
  19971. names: ['start', 'stop'],
  19972. format: "%d %d"
  19973. }],
  19974. c: [{ //c=IN IP4 10.47.197.26
  19975. name: 'connection',
  19976. reg: /^IN IP(\d) (\S*)/,
  19977. names: ['version', 'ip'],
  19978. format: "IN IP%d %s"
  19979. }],
  19980. b: [{ //b=AS:4000
  19981. push: 'bandwidth',
  19982. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  19983. names: ['type', 'limit'],
  19984. format: "%s:%s"
  19985. }],
  19986. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  19987. // NB: special - pushes to session
  19988. // TODO: rtp/fmtp should be filtered by the payloads found here?
  19989. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  19990. names: ['type', 'port', 'protocol', 'payloads'],
  19991. format: "%s %d %s %s"
  19992. }],
  19993. a: [
  19994. { //a=rtpmap:110 opus/48000/2
  19995. push: 'rtp',
  19996. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  19997. names: ['payload', 'codec', 'rate', 'encoding'],
  19998. format: function (o) {
  19999. return (o.encoding) ?
  20000. "rtpmap:%d %s/%s/%s":
  20001. "rtpmap:%d %s/%s";
  20002. }
  20003. },
  20004. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  20005. push: 'fmtp',
  20006. reg: /^fmtp:(\d*) (\S*)/,
  20007. names: ['payload', 'config'],
  20008. format: "fmtp:%d %s"
  20009. },
  20010. { //a=control:streamid=0
  20011. name: 'control',
  20012. reg: /^control:(.*)/,
  20013. format: "control:%s"
  20014. },
  20015. { //a=rtcp:65179 IN IP4 193.84.77.194
  20016. name: 'rtcp',
  20017. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  20018. names: ['port', 'netType', 'ipVer', 'address'],
  20019. format: function (o) {
  20020. return (o.address != null) ?
  20021. "rtcp:%d %s IP%d %s":
  20022. "rtcp:%d";
  20023. }
  20024. },
  20025. { //a=rtcp-fb:98 trr-int 100
  20026. push: 'rtcpFbTrrInt',
  20027. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  20028. names: ['payload', 'value'],
  20029. format: "rtcp-fb:%d trr-int %d"
  20030. },
  20031. { //a=rtcp-fb:98 nack rpsi
  20032. push: 'rtcpFb',
  20033. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  20034. names: ['payload', 'type', 'subtype'],
  20035. format: function (o) {
  20036. return (o.subtype != null) ?
  20037. "rtcp-fb:%s %s %s":
  20038. "rtcp-fb:%s %s";
  20039. }
  20040. },
  20041. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  20042. //a=extmap:1/recvonly URI-gps-string
  20043. push: 'ext',
  20044. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  20045. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  20046. format: function (o) {
  20047. return (o.config != null) ?
  20048. "extmap:%s %s %s":
  20049. "extmap:%s %s";
  20050. }
  20051. },
  20052. {
  20053. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  20054. push: 'crypto',
  20055. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  20056. names: ['id', 'suite', 'config', 'sessionConfig'],
  20057. format: function (o) {
  20058. return (o.sessionConfig != null) ?
  20059. "crypto:%d %s %s %s":
  20060. "crypto:%d %s %s";
  20061. }
  20062. },
  20063. { //a=setup:actpass
  20064. name: 'setup',
  20065. reg: /^setup:(\w*)/,
  20066. format: "setup:%s"
  20067. },
  20068. { //a=mid:1
  20069. name: 'mid',
  20070. reg: /^mid:([^\s]*)/,
  20071. format: "mid:%s"
  20072. },
  20073. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  20074. name: 'msid',
  20075. reg: /^msid:(.*)/,
  20076. format: "msid:%s"
  20077. },
  20078. { //a=ptime:20
  20079. name: 'ptime',
  20080. reg: /^ptime:(\d*)/,
  20081. format: "ptime:%d"
  20082. },
  20083. { //a=maxptime:60
  20084. name: 'maxptime',
  20085. reg: /^maxptime:(\d*)/,
  20086. format: "maxptime:%d"
  20087. },
  20088. { //a=sendrecv
  20089. name: 'direction',
  20090. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  20091. },
  20092. { //a=ice-lite
  20093. name: 'icelite',
  20094. reg: /^(ice-lite)/
  20095. },
  20096. { //a=ice-ufrag:F7gI
  20097. name: 'iceUfrag',
  20098. reg: /^ice-ufrag:(\S*)/,
  20099. format: "ice-ufrag:%s"
  20100. },
  20101. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  20102. name: 'icePwd',
  20103. reg: /^ice-pwd:(\S*)/,
  20104. format: "ice-pwd:%s"
  20105. },
  20106. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  20107. name: 'fingerprint',
  20108. reg: /^fingerprint:(\S*) (\S*)/,
  20109. names: ['type', 'hash'],
  20110. format: "fingerprint:%s %s"
  20111. },
  20112. {
  20113. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  20114. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  20115. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  20116. push:'candidates',
  20117. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  20118. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  20119. format: function (o) {
  20120. var str = "candidate:%s %d %s %d %s %d typ %s";
  20121. // NB: candidate has two optional chunks, so %void middle one if it's missing
  20122. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  20123. if (o.generation != null) {
  20124. str += " generation %d";
  20125. }
  20126. return str;
  20127. }
  20128. },
  20129. { //a=end-of-candidates (keep after the candidates line for readability)
  20130. name: 'endOfCandidates',
  20131. reg: /^(end-of-candidates)/
  20132. },
  20133. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  20134. name: 'remoteCandidates',
  20135. reg: /^remote-candidates:(.*)/,
  20136. format: "remote-candidates:%s"
  20137. },
  20138. { //a=ice-options:google-ice
  20139. name: 'iceOptions',
  20140. reg: /^ice-options:(\S*)/,
  20141. format: "ice-options:%s"
  20142. },
  20143. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  20144. push: "ssrcs",
  20145. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  20146. names: ['id', 'attribute', 'value'],
  20147. format: "ssrc:%d %s:%s"
  20148. },
  20149. { //a=ssrc-group:FEC 1 2
  20150. push: "ssrcGroups",
  20151. reg: /^ssrc-group:(\w*) (.*)/,
  20152. names: ['semantics', 'ssrcs'],
  20153. format: "ssrc-group:%s %s"
  20154. },
  20155. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  20156. name: "msidSemantic",
  20157. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  20158. names: ['semantic', 'token'],
  20159. format: "msid-semantic: %s %s" // space after ":" is not accidental
  20160. },
  20161. { //a=group:BUNDLE audio video
  20162. push: 'groups',
  20163. reg: /^group:(\w*) (.*)/,
  20164. names: ['type', 'mids'],
  20165. format: "group:%s %s"
  20166. },
  20167. { //a=rtcp-mux
  20168. name: 'rtcpMux',
  20169. reg: /^(rtcp-mux)/
  20170. },
  20171. { //a=rtcp-rsize
  20172. name: 'rtcpRsize',
  20173. reg: /^(rtcp-rsize)/
  20174. },
  20175. { // any a= that we don't understand is kepts verbatim on media.invalid
  20176. push: 'invalid',
  20177. names: ["value"]
  20178. }
  20179. ]
  20180. };
  20181. // set sensible defaults to avoid polluting the grammar with boring details
  20182. Object.keys(grammar).forEach(function (key) {
  20183. var objs = grammar[key];
  20184. objs.forEach(function (obj) {
  20185. if (!obj.reg) {
  20186. obj.reg = /(.*)/;
  20187. }
  20188. if (!obj.format) {
  20189. obj.format = "%s";
  20190. }
  20191. });
  20192. });
  20193. },{}],72:[function(require,module,exports){
  20194. var parser = require('./parser');
  20195. var writer = require('./writer');
  20196. exports.write = writer;
  20197. exports.parse = parser.parse;
  20198. exports.parseFmtpConfig = parser.parseFmtpConfig;
  20199. exports.parsePayloads = parser.parsePayloads;
  20200. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  20201. },{"./parser":73,"./writer":74}],73:[function(require,module,exports){
  20202. var toIntIfInt = function (v) {
  20203. return String(Number(v)) === v ? Number(v) : v;
  20204. };
  20205. var attachProperties = function (match, location, names, rawName) {
  20206. if (rawName && !names) {
  20207. location[rawName] = toIntIfInt(match[1]);
  20208. }
  20209. else {
  20210. for (var i = 0; i < names.length; i += 1) {
  20211. if (match[i+1] != null) {
  20212. location[names[i]] = toIntIfInt(match[i+1]);
  20213. }
  20214. }
  20215. }
  20216. };
  20217. var parseReg = function (obj, location, content) {
  20218. var needsBlank = obj.name && obj.names;
  20219. if (obj.push && !location[obj.push]) {
  20220. location[obj.push] = [];
  20221. }
  20222. else if (needsBlank && !location[obj.name]) {
  20223. location[obj.name] = {};
  20224. }
  20225. var keyLocation = obj.push ?
  20226. {} : // blank object that will be pushed
  20227. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  20228. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  20229. if (obj.push) {
  20230. location[obj.push].push(keyLocation);
  20231. }
  20232. };
  20233. var grammar = require('./grammar');
  20234. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  20235. exports.parse = function (sdp) {
  20236. var session = {}
  20237. , media = []
  20238. , location = session; // points at where properties go under (one of the above)
  20239. // parse lines we understand
  20240. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  20241. var type = l[0];
  20242. var content = l.slice(2);
  20243. if (type === 'm') {
  20244. media.push({rtp: [], fmtp: []});
  20245. location = media[media.length-1]; // point at latest media line
  20246. }
  20247. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  20248. var obj = grammar[type][j];
  20249. if (obj.reg.test(content)) {
  20250. return parseReg(obj, location, content);
  20251. }
  20252. }
  20253. });
  20254. session.media = media; // link it up
  20255. return session;
  20256. };
  20257. var fmtpReducer = function (acc, expr) {
  20258. var s = expr.split('=');
  20259. if (s.length === 2) {
  20260. acc[s[0]] = toIntIfInt(s[1]);
  20261. }
  20262. return acc;
  20263. };
  20264. exports.parseFmtpConfig = function (str) {
  20265. return str.split(';').reduce(fmtpReducer, {});
  20266. };
  20267. exports.parsePayloads = function (str) {
  20268. return str.split(' ').map(Number);
  20269. };
  20270. exports.parseRemoteCandidates = function (str) {
  20271. var candidates = [];
  20272. var parts = str.split(' ').map(toIntIfInt);
  20273. for (var i = 0; i < parts.length; i += 3) {
  20274. candidates.push({
  20275. component: parts[i],
  20276. ip: parts[i + 1],
  20277. port: parts[i + 2]
  20278. });
  20279. }
  20280. return candidates;
  20281. };
  20282. },{"./grammar":71}],74:[function(require,module,exports){
  20283. var grammar = require('./grammar');
  20284. // customized util.format - discards excess arguments and can void middle ones
  20285. var formatRegExp = /%[sdv%]/g;
  20286. var format = function (formatStr) {
  20287. var i = 1;
  20288. var args = arguments;
  20289. var len = args.length;
  20290. return formatStr.replace(formatRegExp, function (x) {
  20291. if (i >= len) {
  20292. return x; // missing argument
  20293. }
  20294. var arg = args[i];
  20295. i += 1;
  20296. switch (x) {
  20297. case '%%':
  20298. return '%';
  20299. case '%s':
  20300. return String(arg);
  20301. case '%d':
  20302. return Number(arg);
  20303. case '%v':
  20304. return '';
  20305. }
  20306. });
  20307. // NB: we discard excess arguments - they are typically undefined from makeLine
  20308. };
  20309. var makeLine = function (type, obj, location) {
  20310. var str = obj.format instanceof Function ?
  20311. (obj.format(obj.push ? location : location[obj.name])) :
  20312. obj.format;
  20313. var args = [type + '=' + str];
  20314. if (obj.names) {
  20315. for (var i = 0; i < obj.names.length; i += 1) {
  20316. var n = obj.names[i];
  20317. if (obj.name) {
  20318. args.push(location[obj.name][n]);
  20319. }
  20320. else { // for mLine and push attributes
  20321. args.push(location[obj.names[i]]);
  20322. }
  20323. }
  20324. }
  20325. else {
  20326. args.push(location[obj.name]);
  20327. }
  20328. return format.apply(null, args);
  20329. };
  20330. // RFC specified order
  20331. // TODO: extend this with all the rest
  20332. var defaultOuterOrder = [
  20333. 'v', 'o', 's', 'i',
  20334. 'u', 'e', 'p', 'c',
  20335. 'b', 't', 'r', 'z', 'a'
  20336. ];
  20337. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  20338. module.exports = function (session, opts) {
  20339. opts = opts || {};
  20340. // ensure certain properties exist
  20341. if (session.version == null) {
  20342. session.version = 0; // "v=0" must be there (only defined version atm)
  20343. }
  20344. if (session.name == null) {
  20345. session.name = " "; // "s= " must be there if no meaningful name set
  20346. }
  20347. session.media.forEach(function (mLine) {
  20348. if (mLine.payloads == null) {
  20349. mLine.payloads = "";
  20350. }
  20351. });
  20352. var outerOrder = opts.outerOrder || defaultOuterOrder;
  20353. var innerOrder = opts.innerOrder || defaultInnerOrder;
  20354. var sdp = [];
  20355. // loop through outerOrder for matching properties on session
  20356. outerOrder.forEach(function (type) {
  20357. grammar[type].forEach(function (obj) {
  20358. if (obj.name in session && session[obj.name] != null) {
  20359. sdp.push(makeLine(type, obj, session));
  20360. }
  20361. else if (obj.push in session && session[obj.push] != null) {
  20362. session[obj.push].forEach(function (el) {
  20363. sdp.push(makeLine(type, obj, el));
  20364. });
  20365. }
  20366. });
  20367. });
  20368. // then for each media line, follow the innerOrder
  20369. session.media.forEach(function (mLine) {
  20370. sdp.push(makeLine('m', grammar.m[0], mLine));
  20371. innerOrder.forEach(function (type) {
  20372. grammar[type].forEach(function (obj) {
  20373. if (obj.name in mLine && mLine[obj.name] != null) {
  20374. sdp.push(makeLine(type, obj, mLine));
  20375. }
  20376. else if (obj.push in mLine && mLine[obj.push] != null) {
  20377. mLine[obj.push].forEach(function (el) {
  20378. sdp.push(makeLine(type, obj, el));
  20379. });
  20380. }
  20381. });
  20382. });
  20383. });
  20384. return sdp.join('\r\n') + '\r\n';
  20385. };
  20386. },{"./grammar":71}],75:[function(require,module,exports){
  20387. var grammar = module.exports = {
  20388. v: [{
  20389. name: 'version',
  20390. reg: /^(\d*)$/
  20391. }],
  20392. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  20393. // NB: sessionId will be a String in most cases because it is huge
  20394. name: 'origin',
  20395. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  20396. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  20397. format: "%s %s %d %s IP%d %s"
  20398. }],
  20399. // default parsing of these only (though some of these feel outdated)
  20400. s: [{ name: 'name' }],
  20401. i: [{ name: 'description' }],
  20402. u: [{ name: 'uri' }],
  20403. e: [{ name: 'email' }],
  20404. p: [{ name: 'phone' }],
  20405. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  20406. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  20407. //k: [{}], // outdated thing ignored
  20408. t: [{ //t=0 0
  20409. name: 'timing',
  20410. reg: /^(\d*) (\d*)/,
  20411. names: ['start', 'stop'],
  20412. format: "%d %d"
  20413. }],
  20414. c: [{ //c=IN IP4 10.47.197.26
  20415. name: 'connection',
  20416. reg: /^IN IP(\d) (\S*)/,
  20417. names: ['version', 'ip'],
  20418. format: "IN IP%d %s"
  20419. }],
  20420. b: [{ //b=AS:4000
  20421. push: 'bandwidth',
  20422. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  20423. names: ['type', 'limit'],
  20424. format: "%s:%s"
  20425. }],
  20426. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  20427. // NB: special - pushes to session
  20428. // TODO: rtp/fmtp should be filtered by the payloads found here?
  20429. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  20430. names: ['type', 'port', 'protocol', 'payloads'],
  20431. format: "%s %d %s %s"
  20432. }],
  20433. a: [
  20434. { //a=rtpmap:110 opus/48000/2
  20435. push: 'rtp',
  20436. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  20437. names: ['payload', 'codec', 'rate', 'encoding'],
  20438. format: function (o) {
  20439. return (o.encoding) ?
  20440. "rtpmap:%d %s/%s/%s":
  20441. "rtpmap:%d %s/%s";
  20442. }
  20443. },
  20444. {
  20445. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  20446. //a=fmtp:111 minptime=10; useinbandfec=1
  20447. push: 'fmtp',
  20448. reg: /^fmtp:(\d*) ([\S| ]*)/,
  20449. names: ['payload', 'config'],
  20450. format: "fmtp:%d %s"
  20451. },
  20452. { //a=control:streamid=0
  20453. name: 'control',
  20454. reg: /^control:(.*)/,
  20455. format: "control:%s"
  20456. },
  20457. { //a=rtcp:65179 IN IP4 193.84.77.194
  20458. name: 'rtcp',
  20459. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  20460. names: ['port', 'netType', 'ipVer', 'address'],
  20461. format: function (o) {
  20462. return (o.address != null) ?
  20463. "rtcp:%d %s IP%d %s":
  20464. "rtcp:%d";
  20465. }
  20466. },
  20467. { //a=rtcp-fb:98 trr-int 100
  20468. push: 'rtcpFbTrrInt',
  20469. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  20470. names: ['payload', 'value'],
  20471. format: "rtcp-fb:%d trr-int %d"
  20472. },
  20473. { //a=rtcp-fb:98 nack rpsi
  20474. push: 'rtcpFb',
  20475. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  20476. names: ['payload', 'type', 'subtype'],
  20477. format: function (o) {
  20478. return (o.subtype != null) ?
  20479. "rtcp-fb:%s %s %s":
  20480. "rtcp-fb:%s %s";
  20481. }
  20482. },
  20483. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  20484. //a=extmap:1/recvonly URI-gps-string
  20485. push: 'ext',
  20486. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  20487. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  20488. format: function (o) {
  20489. return (o.config != null) ?
  20490. "extmap:%s %s %s":
  20491. "extmap:%s %s";
  20492. }
  20493. },
  20494. {
  20495. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  20496. push: 'crypto',
  20497. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  20498. names: ['id', 'suite', 'config', 'sessionConfig'],
  20499. format: function (o) {
  20500. return (o.sessionConfig != null) ?
  20501. "crypto:%d %s %s %s":
  20502. "crypto:%d %s %s";
  20503. }
  20504. },
  20505. { //a=setup:actpass
  20506. name: 'setup',
  20507. reg: /^setup:(\w*)/,
  20508. format: "setup:%s"
  20509. },
  20510. { //a=mid:1
  20511. name: 'mid',
  20512. reg: /^mid:([^\s]*)/,
  20513. format: "mid:%s"
  20514. },
  20515. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  20516. name: 'msid',
  20517. reg: /^msid:(.*)/,
  20518. format: "msid:%s"
  20519. },
  20520. { //a=ptime:20
  20521. name: 'ptime',
  20522. reg: /^ptime:(\d*)/,
  20523. format: "ptime:%d"
  20524. },
  20525. { //a=maxptime:60
  20526. name: 'maxptime',
  20527. reg: /^maxptime:(\d*)/,
  20528. format: "maxptime:%d"
  20529. },
  20530. { //a=sendrecv
  20531. name: 'direction',
  20532. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  20533. },
  20534. { //a=ice-lite
  20535. name: 'icelite',
  20536. reg: /^(ice-lite)/
  20537. },
  20538. { //a=ice-ufrag:F7gI
  20539. name: 'iceUfrag',
  20540. reg: /^ice-ufrag:(\S*)/,
  20541. format: "ice-ufrag:%s"
  20542. },
  20543. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  20544. name: 'icePwd',
  20545. reg: /^ice-pwd:(\S*)/,
  20546. format: "ice-pwd:%s"
  20547. },
  20548. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  20549. name: 'fingerprint',
  20550. reg: /^fingerprint:(\S*) (\S*)/,
  20551. names: ['type', 'hash'],
  20552. format: "fingerprint:%s %s"
  20553. },
  20554. {
  20555. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  20556. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  20557. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  20558. push:'candidates',
  20559. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  20560. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  20561. format: function (o) {
  20562. var str = "candidate:%s %d %s %d %s %d typ %s";
  20563. // NB: candidate has two optional chunks, so %void middle one if it's missing
  20564. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  20565. if (o.generation != null) {
  20566. str += " generation %d";
  20567. }
  20568. return str;
  20569. }
  20570. },
  20571. { //a=end-of-candidates (keep after the candidates line for readability)
  20572. name: 'endOfCandidates',
  20573. reg: /^(end-of-candidates)/
  20574. },
  20575. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  20576. name: 'remoteCandidates',
  20577. reg: /^remote-candidates:(.*)/,
  20578. format: "remote-candidates:%s"
  20579. },
  20580. { //a=ice-options:google-ice
  20581. name: 'iceOptions',
  20582. reg: /^ice-options:(\S*)/,
  20583. format: "ice-options:%s"
  20584. },
  20585. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  20586. push: "ssrcs",
  20587. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  20588. names: ['id', 'attribute', 'value'],
  20589. format: "ssrc:%d %s:%s"
  20590. },
  20591. { //a=ssrc-group:FEC 1 2
  20592. push: "ssrcGroups",
  20593. reg: /^ssrc-group:(\w*) (.*)/,
  20594. names: ['semantics', 'ssrcs'],
  20595. format: "ssrc-group:%s %s"
  20596. },
  20597. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  20598. name: "msidSemantic",
  20599. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  20600. names: ['semantic', 'token'],
  20601. format: "msid-semantic: %s %s" // space after ":" is not accidental
  20602. },
  20603. { //a=group:BUNDLE audio video
  20604. push: 'groups',
  20605. reg: /^group:(\w*) (.*)/,
  20606. names: ['type', 'mids'],
  20607. format: "group:%s %s"
  20608. },
  20609. { //a=rtcp-mux
  20610. name: 'rtcpMux',
  20611. reg: /^(rtcp-mux)/
  20612. },
  20613. { //a=rtcp-rsize
  20614. name: 'rtcpRsize',
  20615. reg: /^(rtcp-rsize)/
  20616. },
  20617. { // any a= that we don't understand is kepts verbatim on media.invalid
  20618. push: 'invalid',
  20619. names: ["value"]
  20620. }
  20621. ]
  20622. };
  20623. // set sensible defaults to avoid polluting the grammar with boring details
  20624. Object.keys(grammar).forEach(function (key) {
  20625. var objs = grammar[key];
  20626. objs.forEach(function (obj) {
  20627. if (!obj.reg) {
  20628. obj.reg = /(.*)/;
  20629. }
  20630. if (!obj.format) {
  20631. obj.format = "%s";
  20632. }
  20633. });
  20634. });
  20635. },{}],76:[function(require,module,exports){
  20636. arguments[4][72][0].apply(exports,arguments)
  20637. },{"./parser":77,"./writer":78,"dup":72}],77:[function(require,module,exports){
  20638. var toIntIfInt = function (v) {
  20639. return String(Number(v)) === v ? Number(v) : v;
  20640. };
  20641. var attachProperties = function (match, location, names, rawName) {
  20642. if (rawName && !names) {
  20643. location[rawName] = toIntIfInt(match[1]);
  20644. }
  20645. else {
  20646. for (var i = 0; i < names.length; i += 1) {
  20647. if (match[i+1] != null) {
  20648. location[names[i]] = toIntIfInt(match[i+1]);
  20649. }
  20650. }
  20651. }
  20652. };
  20653. var parseReg = function (obj, location, content) {
  20654. var needsBlank = obj.name && obj.names;
  20655. if (obj.push && !location[obj.push]) {
  20656. location[obj.push] = [];
  20657. }
  20658. else if (needsBlank && !location[obj.name]) {
  20659. location[obj.name] = {};
  20660. }
  20661. var keyLocation = obj.push ?
  20662. {} : // blank object that will be pushed
  20663. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  20664. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  20665. if (obj.push) {
  20666. location[obj.push].push(keyLocation);
  20667. }
  20668. };
  20669. var grammar = require('./grammar');
  20670. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  20671. exports.parse = function (sdp) {
  20672. var session = {}
  20673. , media = []
  20674. , location = session; // points at where properties go under (one of the above)
  20675. // parse lines we understand
  20676. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  20677. var type = l[0];
  20678. var content = l.slice(2);
  20679. if (type === 'm') {
  20680. media.push({rtp: [], fmtp: []});
  20681. location = media[media.length-1]; // point at latest media line
  20682. }
  20683. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  20684. var obj = grammar[type][j];
  20685. if (obj.reg.test(content)) {
  20686. return parseReg(obj, location, content);
  20687. }
  20688. }
  20689. });
  20690. session.media = media; // link it up
  20691. return session;
  20692. };
  20693. var fmtpReducer = function (acc, expr) {
  20694. var s = expr.split('=');
  20695. if (s.length === 2) {
  20696. acc[s[0]] = toIntIfInt(s[1]);
  20697. }
  20698. return acc;
  20699. };
  20700. exports.parseFmtpConfig = function (str) {
  20701. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  20702. };
  20703. exports.parsePayloads = function (str) {
  20704. return str.split(' ').map(Number);
  20705. };
  20706. exports.parseRemoteCandidates = function (str) {
  20707. var candidates = [];
  20708. var parts = str.split(' ').map(toIntIfInt);
  20709. for (var i = 0; i < parts.length; i += 3) {
  20710. candidates.push({
  20711. component: parts[i],
  20712. ip: parts[i + 1],
  20713. port: parts[i + 2]
  20714. });
  20715. }
  20716. return candidates;
  20717. };
  20718. },{"./grammar":75}],78:[function(require,module,exports){
  20719. arguments[4][74][0].apply(exports,arguments)
  20720. },{"./grammar":75,"dup":74}],79:[function(require,module,exports){
  20721. var MediaStreamType = {
  20722. VIDEO_TYPE: "Video",
  20723. AUDIO_TYPE: "Audio"
  20724. };
  20725. module.exports = MediaStreamType;
  20726. },{}],80:[function(require,module,exports){
  20727. var RTCEvents = {
  20728. RTC_READY: "rtc.ready",
  20729. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  20730. LASTN_CHANGED: "rtc.lastn_changed",
  20731. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  20732. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  20733. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  20734. };
  20735. module.exports = RTCEvents;
  20736. },{}],81:[function(require,module,exports){
  20737. var Resolutions = {
  20738. "1080": {
  20739. width: 1920,
  20740. height: 1080,
  20741. order: 7
  20742. },
  20743. "fullhd": {
  20744. width: 1920,
  20745. height: 1080,
  20746. order: 7
  20747. },
  20748. "720": {
  20749. width: 1280,
  20750. height: 720,
  20751. order: 6
  20752. },
  20753. "hd": {
  20754. width: 1280,
  20755. height: 720,
  20756. order: 6
  20757. },
  20758. "960": {
  20759. width: 960,
  20760. height: 720,
  20761. order: 5
  20762. },
  20763. "640": {
  20764. width: 640,
  20765. height: 480,
  20766. order: 4
  20767. },
  20768. "vga": {
  20769. width: 640,
  20770. height: 480,
  20771. order: 4
  20772. },
  20773. "360": {
  20774. width: 640,
  20775. height: 360,
  20776. order: 3
  20777. },
  20778. "320": {
  20779. width: 320,
  20780. height: 240,
  20781. order: 2
  20782. },
  20783. "180": {
  20784. width: 320,
  20785. height: 180,
  20786. order: 1
  20787. }
  20788. };
  20789. module.exports = Resolutions;
  20790. },{}],82:[function(require,module,exports){
  20791. var XMPPEvents = {
  20792. // Designates an event indicating that the connection to the XMPP server
  20793. // failed.
  20794. CONNECTION_FAILED: "xmpp.connection.failed",
  20795. // Designates an event indicating that the media (ICE) connection was
  20796. // interrupted. This should go to the RTC module.
  20797. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  20798. // Designates an event indicating that the media (ICE) connection was
  20799. // restored. This should go to the RTC module.
  20800. CONNECTION_RESTORED: "xmpp.connection.restored",
  20801. // Designates an event indicating that an offer (e.g. Jingle
  20802. // session-initiate) was received.
  20803. CALL_INCOMING: "xmpp.callincoming.jingle",
  20804. // Designates an event indicating that we were kicked from the XMPP MUC.
  20805. KICKED: "xmpp.kicked",
  20806. // Designates an event indicating that the userID for a specific JID has
  20807. // changed.
  20808. // Note: currently this event fires every time we receive presence from
  20809. // someone (regardless of whether or not the "userID" changed).
  20810. USER_ID_CHANGED: "xmpp.user_id_changed",
  20811. // Designates an event indicating that we have joined the XMPP MUC.
  20812. MUC_JOINED: "xmpp.muc_joined",
  20813. // Designates an event indicating that a participant joined the XMPP MUC.
  20814. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  20815. // Designates an event indicating that a participant left the XMPP MUC.
  20816. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  20817. // Designates an event indicating that the MUC role of a participant has
  20818. // changed.
  20819. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  20820. // Designates an event indicating that the XMPP MUC was destroyed.
  20821. MUC_DESTROYED: "xmpp.muc_destroyed",
  20822. // Designates an event indicating that the display name of a participant
  20823. // has changed.
  20824. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  20825. // Designates an event indicating that we received statistics from a
  20826. // participant in the MUC.
  20827. REMOTE_STATS: "xmpp.remote_stats",
  20828. // Designates an event indicating that our role in the XMPP MUC has changed.
  20829. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  20830. // Designates an event indicating that the subject of the XMPP MUC has
  20831. // changed.
  20832. SUBJECT_CHANGED: "xmpp.subject_changed",
  20833. // Designates an event indicating that an XMPP message in the MUC was
  20834. // received.
  20835. MESSAGE_RECEIVED: "xmpp.message_received",
  20836. // Designates an event indicating that we sent an XMPP message to the MUC.
  20837. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  20838. // Designates an event indicating that the video type (e.g. 'camera' or
  20839. // 'screen') for a participant has changed.
  20840. // Note: currently this event fires every time we receive presence from
  20841. // someone (regardless of whether or not the "video type" changed).
  20842. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  20843. // Designates an event indicating that a participant in the XMPP MUC has
  20844. // advertised that they have audio muted (or unmuted).
  20845. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  20846. // Designates an event indicating that a participant in the XMPP MUC has
  20847. // advertised that they have video muted (or unmuted).
  20848. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  20849. // Designates an event indicating that the focus has asked us to mute our
  20850. // audio.
  20851. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  20852. // Designates an event indicating that a moderator in the room changed the
  20853. // "start muted" settings for the conference.
  20854. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  20855. // Designates an event indicating that we should join the conference with
  20856. // audio and/or video muted.
  20857. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  20858. // Designates an event indicating that a remote participant's available
  20859. // devices (whether he supports a audio and/or video) changed.
  20860. // Note: currently this event fires every time we receive presence from
  20861. // someone (regardless of whether or not the devices changed).
  20862. DEVICE_AVAILABLE: "xmpp.device_available",
  20863. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  20864. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  20865. PASSWORD_REQUIRED: "xmpp.password_required",
  20866. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  20867. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  20868. ETHERPAD: "xmpp.etherpad",
  20869. BRIDGE_DOWN: "xmpp.bridge_down",
  20870. PRESENCE_STATUS: "xmpp.presence_status",
  20871. RESERVATION_ERROR: "xmpp.room_reservation_error",
  20872. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  20873. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  20874. // TODO: only used in a hack, should probably be removed.
  20875. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  20876. // TODO: only used in a hack, should probably be removed.
  20877. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  20878. // TODO: only used in a hack, should probably be removed.
  20879. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  20880. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  20881. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  20882. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  20883. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  20884. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  20885. // xmpp is connected and obtained user media
  20886. READY_TO_JOIN: 'xmpp.ready_to_join',
  20887. FOCUS_LEFT: "xmpp.focus_left",
  20888. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received",
  20889. /**
  20890. * Indicates that recording state changed.
  20891. */
  20892. RECORDING_STATE_CHANGED: "xmpp.recordingStateChanged",
  20893. /**
  20894. * Indicates that phone number changed.
  20895. */
  20896. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged"
  20897. };
  20898. module.exports = XMPPEvents;
  20899. },{}],83:[function(require,module,exports){
  20900. var AuthenticationEvents = {
  20901. /**
  20902. * Event callback arguments:
  20903. * function(authenticationEnabled, userIdentity)
  20904. * authenticationEnabled - indicates whether authentication has been enabled
  20905. * in this session
  20906. * userIdentity - if user has been logged in then it contains user name. If
  20907. * contains 'null' or 'undefined' then user is not logged in.
  20908. */
  20909. IDENTITY_UPDATED: "authentication.identity_updated"
  20910. };
  20911. module.exports = AuthenticationEvents;
  20912. },{}],84:[function(require,module,exports){
  20913. var DesktopSharingEventTypes = {
  20914. INIT: "ds.init",
  20915. SWITCHING_DONE: "ds.switching_done",
  20916. NEW_STREAM_CREATED: "ds.new_stream_created",
  20917. /**
  20918. * An event which indicates that the jidesha extension for Firefox is
  20919. * needed to proceed with screen sharing, and that it is not installed.
  20920. */
  20921. FIREFOX_EXTENSION_NEEDED: "ds.firefox_extension_needed"
  20922. };
  20923. module.exports = DesktopSharingEventTypes;
  20924. },{}],85:[function(require,module,exports){
  20925. module.exports = {
  20926. /**
  20927. * An event carrying connection statistics.
  20928. */
  20929. CONNECTION_STATS: "statistics.connectionstats",
  20930. /**
  20931. * FIXME: needs documentation.
  20932. */
  20933. AUDIO_LEVEL: "statistics.audioLevel",
  20934. /**
  20935. * FIXME: needs documentation.
  20936. */
  20937. STOP: "statistics.stop"
  20938. };
  20939. },{}],86:[function(require,module,exports){
  20940. var Constants = {
  20941. LOCAL_JID: 'local'
  20942. };
  20943. module.exports = Constants;
  20944. },{}],87:[function(require,module,exports){
  20945. arguments[4][82][0].apply(exports,arguments)
  20946. },{"dup":82}]},{},[7])(7)
  20947. });