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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564
  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.lastDominantSpeaker = null;
  44. this.dtmfManager = null;
  45. this.somebodySupportsDTMF = false;
  46. this.authEnabled = false;
  47. this.authIdentity;
  48. this.startAudioMuted = false;
  49. this.startVideoMuted = false;
  50. this.startMutedPolicy = {audio: false, video: false};
  51. }
  52. /**
  53. * Joins the conference.
  54. * @param password {string} the password
  55. */
  56. JitsiConference.prototype.join = function (password) {
  57. if(this.room)
  58. this.room.join(password);
  59. };
  60. /**
  61. * Check if joined to the conference.
  62. */
  63. JitsiConference.prototype.isJoined = function () {
  64. return this.room && this.room.joined;
  65. };
  66. /**
  67. * Leaves the conference.
  68. */
  69. JitsiConference.prototype.leave = function () {
  70. if(this.xmpp && this.room)
  71. this.xmpp.leaveRoom(this.room.roomjid);
  72. this.room = null;
  73. };
  74. /**
  75. * Returns name of this conference.
  76. */
  77. JitsiConference.prototype.getName = function () {
  78. return this.options.name;
  79. };
  80. /**
  81. * Check if authentication is enabled for this conference.
  82. */
  83. JitsiConference.prototype.isAuthEnabled = function () {
  84. return this.authEnabled;
  85. };
  86. /**
  87. * Check if user is logged in.
  88. */
  89. JitsiConference.prototype.isLoggedIn = function () {
  90. return !!this.authIdentity;
  91. };
  92. /**
  93. * Get authorized login.
  94. */
  95. JitsiConference.prototype.getAuthLogin = function () {
  96. return this.authIdentity;
  97. };
  98. /**
  99. * Check if external authentication is enabled for this conference.
  100. */
  101. JitsiConference.prototype.isExternalAuthEnabled = function () {
  102. return this.room && this.room.moderator.isExternalAuthEnabled();
  103. };
  104. /**
  105. * Get url for external authentication.
  106. * @param {boolean} [urlForPopup] if true then return url for login popup,
  107. * else url of login page.
  108. * @returns {Promise}
  109. */
  110. JitsiConference.prototype.getExternalAuthUrl = function (urlForPopup) {
  111. return new Promise(function (resolve, reject) {
  112. if (!this.isExternalAuthEnabled()) {
  113. reject();
  114. return;
  115. }
  116. if (urlForPopup) {
  117. this.room.moderator.getPopupLoginUrl(resolve, reject);
  118. } else {
  119. this.room.moderator.getLoginUrl(resolve, reject);
  120. }
  121. }.bind(this));
  122. };
  123. /**
  124. * Returns the local tracks.
  125. */
  126. JitsiConference.prototype.getLocalTracks = function () {
  127. if (this.rtc) {
  128. return this.rtc.localStreams;
  129. } else {
  130. return [];
  131. }
  132. };
  133. /**
  134. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  135. * in JitsiConferenceEvents.
  136. * @param eventId the event ID.
  137. * @param handler handler for the event.
  138. *
  139. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  140. */
  141. JitsiConference.prototype.on = function (eventId, handler) {
  142. if(this.eventEmitter)
  143. this.eventEmitter.on(eventId, handler);
  144. };
  145. /**
  146. * Removes event listener
  147. * @param eventId the event ID.
  148. * @param [handler] optional, the specific handler to unbind
  149. *
  150. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  151. */
  152. JitsiConference.prototype.off = function (eventId, handler) {
  153. if(this.eventEmitter)
  154. this.eventEmitter.removeListener(eventId, handler);
  155. };
  156. // Common aliases for event emitter
  157. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  158. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  159. /**
  160. * Receives notifications from another participants for commands / custom events
  161. * (send by sendPresenceCommand method).
  162. * @param command {String} the name of the command
  163. * @param handler {Function} handler for the command
  164. */
  165. JitsiConference.prototype.addCommandListener = function (command, handler) {
  166. if(this.room)
  167. this.room.addPresenceListener(command, handler);
  168. };
  169. /**
  170. * Removes command listener
  171. * @param command {String} the name of the command
  172. */
  173. JitsiConference.prototype.removeCommandListener = function (command) {
  174. if(this.room)
  175. this.room.removePresenceListener(command);
  176. };
  177. /**
  178. * Sends text message to the other participants in the conference
  179. * @param message the text message.
  180. */
  181. JitsiConference.prototype.sendTextMessage = function (message) {
  182. if(this.room)
  183. this.room.sendMessage(message);
  184. };
  185. /**
  186. * Send presence command.
  187. * @param name the name of the command.
  188. * @param values Object with keys and values that will be send.
  189. **/
  190. JitsiConference.prototype.sendCommand = function (name, values) {
  191. if(this.room) {
  192. this.room.addToPresence(name, values);
  193. this.room.sendPresence();
  194. }
  195. };
  196. /**
  197. * Send presence command one time.
  198. * @param name the name of the command.
  199. * @param values Object with keys and values that will be send.
  200. **/
  201. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  202. this.sendCommand(name, values);
  203. this.removeCommand(name);
  204. };
  205. /**
  206. * Send presence command.
  207. * @param name the name of the command.
  208. * @param values Object with keys and values that will be send.
  209. * @param persistent if false the command will be sent only one time
  210. **/
  211. JitsiConference.prototype.removeCommand = function (name) {
  212. if(this.room)
  213. this.room.removeFromPresence(name);
  214. };
  215. /**
  216. * Sets the display name for this conference.
  217. * @param name the display name to set
  218. */
  219. JitsiConference.prototype.setDisplayName = function(name) {
  220. if(this.room){
  221. // remove previously set nickname
  222. this.room.removeFromPresence("nick");
  223. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  224. this.room.sendPresence();
  225. }
  226. };
  227. /**
  228. * Adds JitsiLocalTrack object to the conference.
  229. * @param track the JitsiLocalTrack object.
  230. */
  231. JitsiConference.prototype.addTrack = function (track) {
  232. this.room.addStream(track.getOriginalStream(), function () {
  233. this.rtc.addLocalStream(track);
  234. if (track.startMuted) {
  235. track.mute();
  236. }
  237. track.muteHandler = this._fireMuteChangeEvent.bind(this, track);
  238. track.stopHandler = this.removeTrack.bind(this, track);
  239. track.audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  240. track.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, track.muteHandler);
  241. track.addEventListener(JitsiTrackEvents.TRACK_STOPPED, track.stopHandler);
  242. track.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, track.audioLevelHandler);
  243. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  244. }.bind(this));
  245. };
  246. /**
  247. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event.
  248. * @param audioLevel the audio level
  249. */
  250. JitsiConference.prototype._fireAudioLevelChangeEvent = function (audioLevel) {
  251. this.eventEmitter.emit(
  252. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  253. this.myUserId(), audioLevel);
  254. };
  255. /**
  256. * Fires TRACK_MUTE_CHANGED change conference event.
  257. * @param track the JitsiTrack object related to the event.
  258. */
  259. JitsiConference.prototype._fireMuteChangeEvent = function (track) {
  260. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  261. };
  262. /**
  263. * Removes JitsiLocalTrack object to the conference.
  264. * @param track the JitsiLocalTrack object.
  265. */
  266. JitsiConference.prototype.removeTrack = function (track) {
  267. if(!this.room){
  268. if(this.rtc)
  269. this.rtc.removeLocalStream(track);
  270. return;
  271. }
  272. this.room.removeStream(track.getOriginalStream(), function(){
  273. this.rtc.removeLocalStream(track);
  274. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, track.muteHandler);
  275. track.removeEventListener(JitsiTrackEvents.TRACK_STOPPED, track.stopHandler);
  276. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, track.audioLevelHandler);
  277. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  278. }.bind(this));
  279. };
  280. /**
  281. * Get role of the local user.
  282. * @returns {string} user role: 'moderator' or 'none'
  283. */
  284. JitsiConference.prototype.getRole = function () {
  285. return this.room.role;
  286. };
  287. /**
  288. * Check if local user is moderator.
  289. * @returns {boolean} true if local user is moderator, false otherwise.
  290. */
  291. JitsiConference.prototype.isModerator = function () {
  292. return this.room.isModerator();
  293. };
  294. /**
  295. * Set password for the room.
  296. * @param {string} password new password for the room.
  297. * @returns {Promise}
  298. */
  299. JitsiConference.prototype.lock = function (password) {
  300. if (!this.isModerator()) {
  301. return Promise.reject();
  302. }
  303. var conference = this;
  304. return new Promise(function (resolve, reject) {
  305. conference.room.lockRoom(password || "", function () {
  306. resolve();
  307. }, function (err) {
  308. reject(err);
  309. }, function () {
  310. reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED);
  311. });
  312. });
  313. };
  314. /**
  315. * Remove password from the room.
  316. * @returns {Promise}
  317. */
  318. JitsiConference.prototype.unlock = function () {
  319. return this.lock();
  320. };
  321. /**
  322. * Elects the participant with the given id to be the selected participant or the speaker.
  323. * @param id the identifier of the participant
  324. */
  325. JitsiConference.prototype.selectParticipant = function(participantId) {
  326. if (this.rtc) {
  327. this.rtc.selectedEndpoint(participantId);
  328. }
  329. };
  330. /**
  331. *
  332. * @param id the identifier of the participant
  333. */
  334. JitsiConference.prototype.pinParticipant = function(participantId) {
  335. if (this.rtc) {
  336. this.rtc.pinEndpoint(participantId);
  337. }
  338. };
  339. /**
  340. * Returns the list of participants for this conference.
  341. * @return Array<JitsiParticipant> a list of participant identifiers containing all conference participants.
  342. */
  343. JitsiConference.prototype.getParticipants = function() {
  344. return Object.keys(this.participants).map(function (key) {
  345. return this.participants[key];
  346. }, this);
  347. };
  348. /**
  349. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  350. * undefined if there isn't one).
  351. * @param id the id of the participant.
  352. */
  353. JitsiConference.prototype.getParticipantById = function(id) {
  354. return this.participants[id];
  355. };
  356. /**
  357. * Kick participant from this conference.
  358. * @param {string} id id of the participant to kick
  359. */
  360. JitsiConference.prototype.kickParticipant = function (id) {
  361. var participant = this.getParticipantById(id);
  362. if (!participant) {
  363. return;
  364. }
  365. this.room.kick(participant.getJid());
  366. };
  367. /**
  368. * Kick participant from this conference.
  369. * @param {string} id id of the participant to kick
  370. */
  371. JitsiConference.prototype.muteParticipant = function (id) {
  372. var participant = this.getParticipantById(id);
  373. if (!participant) {
  374. return;
  375. }
  376. this.room.muteParticipant(participant.getJid(), true);
  377. };
  378. JitsiConference.prototype.onMemberJoined = function (jid, nick, role) {
  379. var id = Strophe.getResourceFromJid(jid);
  380. if (id === 'focus' || this.myUserId() === id) {
  381. return;
  382. }
  383. var participant = new JitsiParticipant(jid, this, nick);
  384. participant._role = role;
  385. this.participants[id] = participant;
  386. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, id, participant);
  387. this.xmpp.connection.disco.info(
  388. jid, "node", function(iq) {
  389. participant._supportsDTMF = $(iq).find(
  390. '>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  391. this.updateDTMFSupport();
  392. }.bind(this)
  393. );
  394. };
  395. JitsiConference.prototype.onMemberLeft = function (jid) {
  396. var id = Strophe.getResourceFromJid(jid);
  397. if (id === 'focus' || this.myUserId() === id) {
  398. return;
  399. }
  400. var participant = this.participants[id];
  401. delete this.participants[id];
  402. this.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, id, participant);
  403. };
  404. JitsiConference.prototype.onUserRoleChanged = function (jid, role) {
  405. var id = Strophe.getResourceFromJid(jid);
  406. var participant = this.getParticipantById(id);
  407. if (!participant) {
  408. return;
  409. }
  410. participant._role = role;
  411. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  412. };
  413. JitsiConference.prototype.onDisplayNameChanged = function (jid, displayName) {
  414. var id = Strophe.getResourceFromJid(jid);
  415. var participant = this.getParticipantById(id);
  416. if (!participant) {
  417. return;
  418. }
  419. participant._displayName = displayName;
  420. this.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED, id, displayName);
  421. };
  422. JitsiConference.prototype.onTrackAdded = function (track) {
  423. var id = track.getParticipantId();
  424. var participant = this.getParticipantById(id);
  425. if (!participant) {
  426. return;
  427. }
  428. // add track to JitsiParticipant
  429. participant._tracks.push(track);
  430. var emitter = this.eventEmitter;
  431. track.addEventListener(
  432. JitsiTrackEvents.TRACK_STOPPED,
  433. function () {
  434. // remove track from JitsiParticipant
  435. var pos = participant._tracks.indexOf(track);
  436. if (pos > -1) {
  437. participant._tracks.splice(pos, 1);
  438. }
  439. emitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  440. }
  441. );
  442. track.addEventListener(
  443. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  444. function () {
  445. emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  446. }
  447. );
  448. track.addEventListener(
  449. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  450. function (audioLevel) {
  451. emitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, id, audioLevel);
  452. }
  453. );
  454. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  455. };
  456. JitsiConference.prototype.updateDTMFSupport = function () {
  457. var somebodySupportsDTMF = false;
  458. var participants = this.getParticipants();
  459. // check if at least 1 participant supports DTMF
  460. for (var i = 0; i < participants.length; i += 1) {
  461. if (participants[i].supportsDTMF()) {
  462. somebodySupportsDTMF = true;
  463. break;
  464. }
  465. }
  466. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  467. this.somebodySupportsDTMF = somebodySupportsDTMF;
  468. this.eventEmitter.emit(JitsiConferenceEvents.DTMF_SUPPORT_CHANGED, somebodySupportsDTMF);
  469. }
  470. };
  471. /**
  472. * Allows to check if there is at least one user in the conference
  473. * that supports DTMF.
  474. * @returns {boolean} true if somebody supports DTMF, false otherwise
  475. */
  476. JitsiConference.prototype.isDTMFSupported = function () {
  477. return this.somebodySupportsDTMF;
  478. };
  479. /**
  480. * Returns the local user's ID
  481. * @return {string} local user's ID
  482. */
  483. JitsiConference.prototype.myUserId = function () {
  484. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  485. };
  486. JitsiConference.prototype.sendTones = function (tones, duration, pause) {
  487. if (!this.dtmfManager) {
  488. var connection = this.xmpp.connection.jingle.activecall.peerconnection;
  489. if (!connection) {
  490. logger.warn("cannot sendTones: no conneciton");
  491. return;
  492. }
  493. var tracks = this.getLocalTracks().filter(function (track) {
  494. return track.isAudioTrack();
  495. });
  496. if (!tracks.length) {
  497. logger.warn("cannot sendTones: no local audio stream");
  498. return;
  499. }
  500. this.dtmfManager = new JitsiDTMFManager(tracks[0], connection);
  501. }
  502. this.dtmfManager.sendTones(tones, duration, pause);
  503. };
  504. /**
  505. * Returns true if the recording is supproted and false if not.
  506. */
  507. JitsiConference.prototype.isRecordingSupported = function () {
  508. if(this.room)
  509. return this.room.isRecordingSupported();
  510. return false;
  511. };
  512. /**
  513. * Returns null if the recording is not supported, "on" if the recording started
  514. * and "off" if the recording is not started.
  515. */
  516. JitsiConference.prototype.getRecordingState = function () {
  517. if(this.room)
  518. return this.room.getRecordingState();
  519. return "off";
  520. }
  521. /**
  522. * Returns the url of the recorded video.
  523. */
  524. JitsiConference.prototype.getRecordingURL = function () {
  525. if(this.room)
  526. return this.room.getRecordingURL();
  527. return null;
  528. }
  529. /**
  530. * Starts/stops the recording
  531. */
  532. JitsiConference.prototype.toggleRecording = function (options) {
  533. if(this.room)
  534. return this.room.toggleRecording(options, function (status, error) {
  535. this.eventEmitter.emit(
  536. JitsiConferenceEvents.RECORDING_STATE_CHANGED, status, error);
  537. }.bind(this));
  538. this.eventEmitter.emit(
  539. JitsiConferenceEvents.RECORDING_STATE_CHANGED, "error",
  540. new Error("The conference is not created yet!"));
  541. }
  542. /**
  543. * Returns true if the SIP calls are supported and false otherwise
  544. */
  545. JitsiConference.prototype.isSIPCallingSupported = function () {
  546. if(this.room)
  547. return this.room.isSIPCallingSupported();
  548. return false;
  549. }
  550. /**
  551. * Dials a number.
  552. * @param number the number
  553. */
  554. JitsiConference.prototype.dial = function (number) {
  555. if(this.room)
  556. return this.room.dial(number);
  557. return new Promise(function(resolve, reject){
  558. reject(new Error("The conference is not created yet!"))});
  559. }
  560. /**
  561. * Hangup an existing call
  562. */
  563. JitsiConference.prototype.hangup = function () {
  564. if(this.room)
  565. return this.room.hangup();
  566. return new Promise(function(resolve, reject){
  567. reject(new Error("The conference is not created yet!"))});
  568. }
  569. /**
  570. * Returns the phone number for joining the conference.
  571. */
  572. JitsiConference.prototype.getPhoneNumber = function () {
  573. if(this.room)
  574. return this.room.getPhoneNumber();
  575. return null;
  576. }
  577. /**
  578. * Returns the pin for joining the conference with phone.
  579. */
  580. JitsiConference.prototype.getPhonePin = function () {
  581. if(this.room)
  582. return this.room.getPhonePin();
  583. return null;
  584. }
  585. /**
  586. * Returns the connection state for the current room. Its ice connection state
  587. * for its session.
  588. */
  589. JitsiConference.prototype.getConnectionState = function () {
  590. if(this.room)
  591. return this.room.getConnectionState();
  592. return null;
  593. }
  594. /**
  595. * Make all new participants mute their audio/video on join.
  596. * @param policy {Object} object with 2 boolean properties for video and audio:
  597. * @param {boolean} audio if audio should be muted.
  598. * @param {boolean} video if video should be muted.
  599. */
  600. JitsiConference.prototype.setStartMutedPolicy = function (policy) {
  601. if (!this.isModerator()) {
  602. return;
  603. }
  604. this.startMutedPolicy = policy;
  605. this.room.removeFromPresence("startmuted");
  606. this.room.addToPresence("startmuted", {
  607. attributes: {
  608. audio: policy.audio,
  609. video: policy.video,
  610. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  611. }
  612. });
  613. this.room.sendPresence();
  614. };
  615. /**
  616. * Returns current start muted policy
  617. * @returns {Object} with 2 proprties - audio and video.
  618. */
  619. JitsiConference.prototype.getStartMutedPolicy = function () {
  620. return this.startMutedPolicy;
  621. };
  622. /**
  623. * Check if audio is muted on join.
  624. */
  625. JitsiConference.prototype.isStartAudioMuted = function () {
  626. return this.startAudioMuted;
  627. };
  628. /**
  629. * Check if video is muted on join.
  630. */
  631. JitsiConference.prototype.isStartVideoMuted = function () {
  632. return this.startVideoMuted;
  633. };
  634. /**
  635. * Get object with internal logs.
  636. */
  637. JitsiConference.prototype.getLogs = function () {
  638. var data = this.xmpp.getJingleLog();
  639. var metadata = {};
  640. metadata.time = new Date();
  641. metadata.url = window.location.href;
  642. metadata.ua = navigator.userAgent;
  643. var log = this.xmpp.getXmppLog();
  644. if (log) {
  645. metadata.xmpp = log;
  646. }
  647. data.metadata = metadata;
  648. return data;
  649. };
  650. /**
  651. * Setups the listeners needed for the conference.
  652. * @param conference the conference
  653. */
  654. function setupListeners(conference) {
  655. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  656. conference.rtc.onIncommingCall(event);
  657. if(conference.statistics)
  658. conference.statistics.startRemoteStats(event.peerconnection);
  659. });
  660. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  661. function (data, sid, thessrc) {
  662. var track = conference.rtc.createRemoteStream(data, sid, thessrc);
  663. if (track) {
  664. conference.onTrackAdded(track);
  665. }
  666. }
  667. );
  668. conference.room.addListener(XMPPEvents.AUDIO_MUTED_BY_FOCUS,
  669. function (value) {
  670. conference.rtc.setAudioMute(value);
  671. }
  672. );
  673. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  674. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  675. });
  676. conference.room.addListener(XMPPEvents.ROOM_JOIN_ERROR, function (pres) {
  677. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  678. });
  679. conference.room.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function (pres) {
  680. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  681. });
  682. conference.room.addListener(XMPPEvents.PASSWORD_REQUIRED, function (pres) {
  683. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.PASSWORD_REQUIRED, pres);
  684. });
  685. conference.room.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, function () {
  686. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.AUTHENTICATION_REQUIRED);
  687. });
  688. conference.room.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  689. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE);
  690. });
  691. // FIXME
  692. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  693. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  694. // });
  695. conference.room.addListener(XMPPEvents.KICKED, function () {
  696. conference.eventEmitter.emit(JitsiConferenceEvents.KICKED);
  697. });
  698. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  699. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT, conference.onMemberLeft.bind(conference));
  700. conference.room.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, conference.onDisplayNameChanged.bind(conference));
  701. conference.room.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, function (role) {
  702. conference.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, conference.myUserId(), role);
  703. });
  704. conference.room.addListener(XMPPEvents.MUC_ROLE_CHANGED, conference.onUserRoleChanged.bind(conference));
  705. conference.room.addListener(XMPPEvents.CONNECTION_INTERRUPTED, function () {
  706. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  707. });
  708. conference.room.addListener(XMPPEvents.RECORDING_STATE_CHANGED,
  709. function () {
  710. conference.eventEmitter.emit(
  711. JitsiConferenceEvents.RECORDING_STATE_CHANGED);
  712. });
  713. conference.room.addListener(XMPPEvents.PHONE_NUMBER_CHANGED, function () {
  714. conference.eventEmitter.emit(
  715. JitsiConferenceEvents.PHONE_NUMBER_CHANGED);
  716. });
  717. conference.room.addListener(XMPPEvents.CONNECTION_RESTORED, function () {
  718. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  719. });
  720. conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  721. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.SETUP_FAILED);
  722. });
  723. conference.room.addListener(AuthenticationEvents.IDENTITY_UPDATED, function (authEnabled, authIdentity) {
  724. conference.authEnabled = authEnabled;
  725. conference.authIdentity = authIdentity;
  726. });
  727. conference.room.addListener(XMPPEvents.MESSAGE_RECEIVED, function (jid, displayName, txt, myJid, ts) {
  728. var id = Strophe.getResourceFromJid(jid);
  729. conference.eventEmitter.emit(JitsiConferenceEvents.MESSAGE_RECEIVED, id, txt, ts);
  730. });
  731. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  732. if(conference.lastDominantSpeaker !== id && conference.room) {
  733. conference.lastDominantSpeaker = id;
  734. conference.eventEmitter.emit(JitsiConferenceEvents.DOMINANT_SPEAKER_CHANGED, id);
  735. }
  736. });
  737. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  738. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  739. });
  740. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  741. function (lastNEndpoints, endpointsEnteringLastN) {
  742. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  743. lastNEndpoints, endpointsEnteringLastN);
  744. });
  745. conference.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, function () {
  746. conference.eventEmitter.emit(JitsiConferenceErrors.PASSWORD_REQUIRED);
  747. });
  748. conference.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS,
  749. function (audioMuted, videoMuted) {
  750. conference.startAudioMuted = audioMuted;
  751. conference.startVideoMuted = videoMuted;
  752. // mute existing local tracks because this is initial mute from
  753. // Jicofo
  754. conference.getLocalTracks().forEach(function (track) {
  755. if (conference.startAudioMuted && track.isAudioTrack()) {
  756. track.mute();
  757. }
  758. if (conference.startVideoMuted && track.isVideoTrack()) {
  759. track.mute();
  760. }
  761. });
  762. conference.eventEmitter.emit(JitsiConferenceEvents.STARTED_MUTED);
  763. });
  764. conference.room.addPresenceListener("startmuted", function (data, from) {
  765. var isModerator = false;
  766. if (conference.myUserId() === from && conference.isModerator()) {
  767. isModerator = true;
  768. } else {
  769. var participant = conference.getParticipantById(from);
  770. if (participant && participant.isModerator()) {
  771. isModerator = true;
  772. }
  773. }
  774. if (!isModerator) {
  775. return;
  776. }
  777. var startAudioMuted = data.attributes.audio === 'true';
  778. var startVideoMuted = data.attributes.video === 'true';
  779. var updated = false;
  780. if (startAudioMuted !== conference.startMutedPolicy.audio) {
  781. conference.startMutedPolicy.audio = startAudioMuted;
  782. updated = true;
  783. }
  784. if (startVideoMuted !== conference.startMutedPolicy.video) {
  785. conference.startMutedPolicy.video = startVideoMuted;
  786. updated = true;
  787. }
  788. if (updated) {
  789. conference.eventEmitter.emit(
  790. JitsiConferenceEvents.START_MUTED_POLICY_CHANGED,
  791. conference.startMutedPolicy
  792. );
  793. }
  794. });
  795. if(conference.statistics) {
  796. //FIXME: Maybe remove event should not be associated with the conference.
  797. conference.statistics.addAudioLevelListener(function (ssrc, level) {
  798. var userId = null;
  799. var jid = conference.room.getJidBySSRC(ssrc);
  800. if (!jid)
  801. return;
  802. conference.rtc.setAudioLevel(jid, level);
  803. });
  804. conference.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE,
  805. function () {
  806. conference.statistics.dispose();
  807. });
  808. // FIXME: Maybe we should move this.
  809. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  810. // conference.room.updateDeviceAvailability(devices);
  811. // });
  812. }
  813. }
  814. module.exports = JitsiConference;
  815. }).call(this,"/JitsiConference.js")
  816. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./JitsiTrackEvents":10,"./modules/DTMF/JitsiDTMFManager":11,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"./service/RTC/RTCEvents":79,"./service/authentication/AuthenticationEvents":81,"./service/xmpp/XMPPEvents":85,"events":43,"jitsi-meet-logger":47}],2:[function(require,module,exports){
  817. /**
  818. * Enumeration with the errors for the conference.
  819. * @type {{string: string}}
  820. */
  821. var JitsiConferenceErrors = {
  822. /**
  823. * Indicates that a password is required in order to join the conference.
  824. */
  825. PASSWORD_REQUIRED: "conference.passwordRequired",
  826. /**
  827. * Indicates that client must be authenticated to create the conference.
  828. */
  829. AUTHENTICATION_REQUIRED: "conference.authenticationRequired",
  830. /**
  831. * Indicates that password cannot be set for this conference.
  832. */
  833. PASSWORD_NOT_SUPPORTED: "conference.passwordNotSupported",
  834. /**
  835. * Indicates that a connection error occurred when trying to join a
  836. * conference.
  837. */
  838. CONNECTION_ERROR: "conference.connectionError",
  839. /**
  840. * Indicates that the conference setup failed.
  841. */
  842. SETUP_FAILED: "conference.setup_failed",
  843. /**
  844. * Indicates that there is no available videobridge.
  845. */
  846. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  847. /**
  848. * Many more errors TBD here.
  849. */
  850. };
  851. module.exports = JitsiConferenceErrors;
  852. },{}],3:[function(require,module,exports){
  853. /**
  854. * Enumeration with the events for the conference.
  855. * @type {{string: string}}
  856. */
  857. var JitsiConferenceEvents = {
  858. /**
  859. * A new media track was added to the conference.
  860. */
  861. TRACK_ADDED: "conference.trackAdded",
  862. /**
  863. * The media track was removed from the conference.
  864. */
  865. TRACK_REMOVED: "conference.trackRemoved",
  866. /**
  867. * The dominant speaker was changed.
  868. */
  869. DOMINANT_SPEAKER_CHANGED: "conference.dominantSpeaker",
  870. /**
  871. * A new user joinned the conference.
  872. */
  873. USER_JOINED: "conference.userJoined",
  874. /**
  875. * A user has left the conference.
  876. */
  877. USER_LEFT: "conference.userLeft",
  878. /**
  879. * User role changed.
  880. */
  881. USER_ROLE_CHANGED: "conference.roleChanged",
  882. /**
  883. * New text message was received.
  884. */
  885. MESSAGE_RECEIVED: "conference.messageReceived",
  886. /**
  887. * A user has changed it display name
  888. */
  889. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  890. /**
  891. * A participant avatar has changed.
  892. */
  893. AVATAR_CHANGED: "conference.avatarChanged",
  894. /**
  895. * New connection statistics are received.
  896. */
  897. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  898. /**
  899. * The Last N set is changed.
  900. */
  901. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  902. /**
  903. * You are included / excluded in somebody's last N set
  904. */
  905. IN_LAST_N_CHANGED: "conference.lastNEndpointsChanged",
  906. /**
  907. * A media track ( attached to the conference) mute status was changed.
  908. */
  909. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  910. /**
  911. * Audio levels of a media track ( attached to the conference) was changed.
  912. */
  913. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  914. /**
  915. * Indicates that the connection to the conference has been interrupted
  916. * for some reason.
  917. */
  918. CONNECTION_INTERRUPTED: "conference.connectionInterrupted",
  919. /**
  920. * Indicates that the connection to the conference has been restored.
  921. */
  922. CONNECTION_RESTORED: "conference.connectionRestored",
  923. /**
  924. * Indicates that conference failed.
  925. */
  926. CONFERENCE_FAILED: "conference.failed",
  927. /**
  928. * Indicates that conference has been joined.
  929. */
  930. CONFERENCE_JOINED: "conference.joined",
  931. /**
  932. * Indicates that conference has been left.
  933. */
  934. CONFERENCE_LEFT: "conference.left",
  935. /**
  936. * You are kicked from the conference.
  937. */
  938. KICKED: "conferenece.kicked",
  939. /**
  940. * Indicates that start muted settings changed.
  941. */
  942. START_MUTED_POLICY_CHANGED: "conference.start_muted_policy_changed",
  943. /**
  944. * Indicates that the local user has started muted.
  945. */
  946. STARTED_MUTED: "conference.started_muted",
  947. /**
  948. * Indicates that DTMF support changed.
  949. */
  950. DTMF_SUPPORT_CHANGED: "conference.dtmfSupportChanged",
  951. /**
  952. * Indicates that recording state changed.
  953. */
  954. RECORDING_STATE_CHANGED: "conference.recordingStateChanged",
  955. /**
  956. * Indicates that phone number changed.
  957. */
  958. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged"
  959. };
  960. module.exports = JitsiConferenceEvents;
  961. },{}],4:[function(require,module,exports){
  962. var JitsiConference = require("./JitsiConference");
  963. var XMPP = require("./modules/xmpp/xmpp");
  964. /**
  965. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  966. * JitsiConference interface.
  967. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  968. * @param token the JWT token used to authenticate with the server(optional)
  969. * @param options Object with properties / settings related to connection with the server.
  970. * @constructor
  971. */
  972. function JitsiConnection(appID, token, options) {
  973. this.appID = appID;
  974. this.token = token;
  975. this.options = options;
  976. this.xmpp = new XMPP(options);
  977. this.conferences = {};
  978. }
  979. /**
  980. * Connect the client with the server.
  981. * @param options {object} connecting options (for example authentications parameters).
  982. */
  983. JitsiConnection.prototype.connect = function (options) {
  984. if(!options)
  985. options = {};
  986. this.xmpp.connect(options.id, options.password);
  987. }
  988. /**
  989. * Disconnect the client from the server.
  990. */
  991. JitsiConnection.prototype.disconnect = function () {
  992. this.xmpp.disconnect();
  993. }
  994. /**
  995. * This method allows renewal of the tokens if they are expiring.
  996. * @param token the new token.
  997. */
  998. JitsiConnection.prototype.setToken = function (token) {
  999. this.token = token;
  1000. }
  1001. /**
  1002. * Creates and joins new conference.
  1003. * @param name the name of the conference; if null - a generated name will be
  1004. * provided from the api
  1005. * @param options Object with properties / settings related to the conference
  1006. * that will be created.
  1007. * @returns {JitsiConference} returns the new conference object.
  1008. */
  1009. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  1010. this.conferences[name] = new JitsiConference({name: name, config: options,
  1011. connection: this});
  1012. return this.conferences[name];
  1013. }
  1014. /**
  1015. * Subscribes the passed listener to the event.
  1016. * @param event {JitsiConnectionEvents} the connection event.
  1017. * @param listener {Function} the function that will receive the event
  1018. */
  1019. JitsiConnection.prototype.addEventListener = function (event, listener) {
  1020. this.xmpp.addListener(event, listener);
  1021. }
  1022. /**
  1023. * Unsubscribes the passed handler.
  1024. * @param event {JitsiConnectionEvents} the connection event.
  1025. * @param listener {Function} the function that will receive the event
  1026. */
  1027. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  1028. this.xmpp.removeListener(event, listener);
  1029. }
  1030. module.exports = JitsiConnection;
  1031. },{"./JitsiConference":1,"./modules/xmpp/xmpp":41}],5:[function(require,module,exports){
  1032. /**
  1033. * Enumeration with the errors for the connection.
  1034. * @type {{string: string}}
  1035. */
  1036. var JitsiConnectionErrors = {
  1037. /**
  1038. * Indicates that a password is required in order to join the conference.
  1039. */
  1040. PASSWORD_REQUIRED: "connection.passwordRequired",
  1041. /**
  1042. * Indicates that a connection error occurred when trying to join a
  1043. * conference.
  1044. */
  1045. CONNECTION_ERROR: "connection.connectionError",
  1046. /**
  1047. * Not specified errors.
  1048. */
  1049. OTHER_ERROR: "connection.otherError"
  1050. };
  1051. module.exports = JitsiConnectionErrors;
  1052. },{}],6:[function(require,module,exports){
  1053. /**
  1054. * Enumeration with the events for the connection.
  1055. * @type {{string: string}}
  1056. */
  1057. var JitsiConnnectionEvents = {
  1058. /**
  1059. * Indicates that the connection has been failed for some reason.
  1060. */
  1061. CONNECTION_FAILED: "connection.connectionFailed",
  1062. /**
  1063. * Indicates that the connection has been established.
  1064. */
  1065. CONNECTION_ESTABLISHED: "connection.connectionEstablished",
  1066. /**
  1067. * Indicates that the connection has been disconnected.
  1068. */
  1069. CONNECTION_DISCONNECTED: "connection.connectionDisconnected",
  1070. /**
  1071. * Indicates that the perfomed action cannot be executed because the
  1072. * connection is not in the correct state(connected, disconnected, etc.)
  1073. */
  1074. WRONG_STATE: "connection.wrongState"
  1075. };
  1076. module.exports = JitsiConnnectionEvents;
  1077. },{}],7:[function(require,module,exports){
  1078. var JitsiConnection = require("./JitsiConnection");
  1079. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  1080. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  1081. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  1082. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  1083. var JitsiTrackEvents = require("./JitsiTrackEvents");
  1084. var JitsiTrackErrors = require("./JitsiTrackErrors");
  1085. var Logger = require("jitsi-meet-logger");
  1086. var RTC = require("./modules/RTC/RTC");
  1087. var Statistics = require("./modules/statistics/statistics");
  1088. var Resolutions = require("./service/RTC/Resolutions");
  1089. function getLowerResolution(resolution) {
  1090. if(!Resolutions[resolution])
  1091. return null;
  1092. var order = Resolutions[resolution].order;
  1093. var res = null;
  1094. var resName = null;
  1095. for(var i in Resolutions) {
  1096. var tmp = Resolutions[i];
  1097. if (!res || (res.order < tmp.order && tmp.order < order)) {
  1098. resName = i;
  1099. res = tmp;
  1100. }
  1101. }
  1102. return resName;
  1103. }
  1104. /**
  1105. * Namespace for the interface of Jitsi Meet Library.
  1106. */
  1107. var LibJitsiMeet = {
  1108. JitsiConnection: JitsiConnection,
  1109. events: {
  1110. conference: JitsiConferenceEvents,
  1111. connection: JitsiConnectionEvents,
  1112. track: JitsiTrackEvents
  1113. },
  1114. errors: {
  1115. conference: JitsiConferenceErrors,
  1116. connection: JitsiConnectionErrors,
  1117. track: JitsiTrackErrors
  1118. },
  1119. logLevels: Logger.levels,
  1120. init: function (options) {
  1121. return RTC.init(options || {});
  1122. },
  1123. /**
  1124. * Returns whether the desktop sharing is enabled or not.
  1125. * @returns {boolean}
  1126. */
  1127. isDesktopSharingEnabled: function () {
  1128. return RTC.isDesktopSharingEnabled();
  1129. },
  1130. setLogLevel: function (level) {
  1131. Logger.setLogLevel(level);
  1132. },
  1133. /**
  1134. * Creates the media tracks and returns them trough the callback.
  1135. * @param options Object with properties / settings specifying the tracks which should be created.
  1136. * should be created or some additional configurations about resolution for example.
  1137. * @param {Array} options.devices the devices that will be requested
  1138. * @param {string} options.resolution resolution constraints
  1139. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1140. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1141. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1142. * @param {string} options.cameraDeviceId
  1143. * @param {string} options.micDeviceId
  1144. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>}
  1145. * A promise that returns an array of created JitsiTracks if resolved,
  1146. * or a JitsiConferenceError if rejected.
  1147. */
  1148. createLocalTracks: function (options) {
  1149. return RTC.obtainAudioAndVideoPermissions(options || {}).then(
  1150. function(tracks) {
  1151. if(!RTC.options.disableAudioLevels)
  1152. for(var i = 0; i < tracks.length; i++) {
  1153. var track = tracks[i];
  1154. var mStream = track.getOriginalStream();
  1155. if(track.getType() === "audio"){
  1156. Statistics.startLocalStats(mStream,
  1157. track.setAudioLevel.bind(track));
  1158. track.addEventListener(
  1159. JitsiTrackEvents.TRACK_STOPPED,
  1160. function(){
  1161. Statistics.stopLocalStats(mStream);
  1162. });
  1163. }
  1164. }
  1165. return tracks;
  1166. }).catch(function (error) {
  1167. if(error === JitsiTrackErrors.UNSUPPORTED_RESOLUTION) {
  1168. var oldResolution = options.resolution || '360';
  1169. var newResolution = getLowerResolution(oldResolution);
  1170. if(newResolution === null)
  1171. return Promise.reject(error);
  1172. options.resolution = newResolution;
  1173. return LibJitsiMeet.createLocalTracks(options);
  1174. }
  1175. return Promise.reject(error);
  1176. });
  1177. },
  1178. /**
  1179. * Checks if its possible to enumerate available cameras/micropones.
  1180. * @returns {boolean} true if available, false otherwise.
  1181. */
  1182. isDeviceListAvailable: function () {
  1183. return RTC.isDeviceListAvailable();
  1184. },
  1185. /**
  1186. * Returns true if changing the camera / microphone device is supported and
  1187. * false if not.
  1188. * @returns {boolean} true if available, false otherwise.
  1189. */
  1190. isDeviceChangeAvailable: function () {
  1191. return RTC.isDeviceChangeAvailable();
  1192. },
  1193. enumerateDevices: function (callback) {
  1194. RTC.enumerateDevices(callback);
  1195. }
  1196. };
  1197. //Setups the promise object.
  1198. window.Promise = window.Promise || require("es6-promise").Promise;
  1199. module.exports = LibJitsiMeet;
  1200. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./JitsiTrackErrors":9,"./JitsiTrackEvents":10,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"./service/RTC/Resolutions":80,"es6-promise":45,"jitsi-meet-logger":47}],8:[function(require,module,exports){
  1201. /* global Strophe */
  1202. /**
  1203. * Represents a participant in (a member of) a conference.
  1204. */
  1205. function JitsiParticipant(jid, conference, displayName){
  1206. this._jid = jid;
  1207. this._id = Strophe.getResourceFromJid(jid);
  1208. this._conference = conference;
  1209. this._displayName = displayName;
  1210. this._supportsDTMF = false;
  1211. this._tracks = [];
  1212. this._role = 'none';
  1213. }
  1214. /**
  1215. * @returns {JitsiConference} The conference that this participant belongs to.
  1216. */
  1217. JitsiParticipant.prototype.getConference = function() {
  1218. return this._conference;
  1219. };
  1220. /**
  1221. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  1222. */
  1223. JitsiParticipant.prototype.getTracks = function() {
  1224. return this._tracks;
  1225. };
  1226. /**
  1227. * @returns {String} The ID of this participant.
  1228. */
  1229. JitsiParticipant.prototype.getId = function() {
  1230. return this._id;
  1231. };
  1232. /**
  1233. * @returns {String} The JID of this participant.
  1234. */
  1235. JitsiParticipant.prototype.getJid = function() {
  1236. return this._jid;
  1237. };
  1238. /**
  1239. * @returns {String} The human-readable display name of this participant.
  1240. */
  1241. JitsiParticipant.prototype.getDisplayName = function() {
  1242. return this._displayName;
  1243. };
  1244. /**
  1245. * @returns {Boolean} Whether this participant is a moderator or not.
  1246. */
  1247. JitsiParticipant.prototype.isModerator = function() {
  1248. return this._role === 'moderator';
  1249. };
  1250. // Gets a link to an etherpad instance advertised by the participant?
  1251. //JitsiParticipant.prototype.getEtherpad = function() {
  1252. //
  1253. //}
  1254. /*
  1255. * @returns {Boolean} Whether this participant has muted their audio.
  1256. */
  1257. JitsiParticipant.prototype.isAudioMuted = function() {
  1258. return this.getTracks().reduce(function (track, isAudioMuted) {
  1259. return isAudioMuted && (track.isVideoTrack() || track.isMuted());
  1260. }, true);
  1261. };
  1262. /*
  1263. * @returns {Boolean} Whether this participant has muted their video.
  1264. */
  1265. JitsiParticipant.prototype.isVideoMuted = function() {
  1266. return this.getTracks().reduce(function (track, isVideoMuted) {
  1267. return isVideoMuted && (track.isAudioTrack() || track.isMuted());
  1268. }, true);
  1269. };
  1270. /*
  1271. * @returns {???} The latest statistics reported by this participant
  1272. * (i.e. info used to populate the GSM bars)
  1273. * TODO: do we expose this or handle it internally?
  1274. */
  1275. JitsiParticipant.prototype.getLatestStats = function() {
  1276. };
  1277. /**
  1278. * @returns {String} The role of this participant.
  1279. */
  1280. JitsiParticipant.prototype.getRole = function() {
  1281. return this._role;
  1282. };
  1283. /*
  1284. * @returns {Boolean} Whether this participant is
  1285. * the conference focus (i.e. jicofo).
  1286. */
  1287. JitsiParticipant.prototype.isFocus = function() {
  1288. };
  1289. /*
  1290. * @returns {Boolean} Whether this participant is
  1291. * a conference recorder (i.e. jirecon).
  1292. */
  1293. JitsiParticipant.prototype.isRecorder = function() {
  1294. };
  1295. /*
  1296. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  1297. */
  1298. JitsiParticipant.prototype.isSipGateway = function() {
  1299. };
  1300. /**
  1301. * @returns {Boolean} Whether this participant
  1302. * is currently sharing their screen.
  1303. */
  1304. JitsiParticipant.prototype.isScreenSharing = function() {
  1305. };
  1306. /**
  1307. * @returns {String} The user agent of this participant
  1308. * (i.e. browser userAgent string).
  1309. */
  1310. JitsiParticipant.prototype.getUserAgent = function() {
  1311. };
  1312. /**
  1313. * Kicks the participant from the conference (requires certain privileges).
  1314. */
  1315. JitsiParticipant.prototype.kick = function() {
  1316. };
  1317. /**
  1318. * Asks this participant to mute themselves.
  1319. */
  1320. JitsiParticipant.prototype.askToMute = function() {
  1321. };
  1322. JitsiParticipant.prototype.supportsDTMF = function () {
  1323. return this._supportsDTMF;
  1324. };
  1325. module.exports = JitsiParticipant;
  1326. },{}],9:[function(require,module,exports){
  1327. module.exports = {
  1328. /**
  1329. * Returns JitsiTrackErrors based on the error object passed by GUM
  1330. * @param error the error
  1331. * @param {Array} devices Array with the requested devices
  1332. */
  1333. parseError: function (error, devices) {
  1334. devices = devices || [];
  1335. if (typeof error == "object" && error.constraintName && error.name
  1336. && (error.name == "ConstraintNotSatisfiedError" ||
  1337. error.name == "OverconstrainedError") &&
  1338. (error.constraintName == "minWidth" ||
  1339. error.constraintName == "maxWidth" ||
  1340. error.constraintName == "minHeight" ||
  1341. error.constraintName == "maxHeight") &&
  1342. devices.indexOf("video") !== -1) {
  1343. return this.UNSUPPORTED_RESOLUTION;
  1344. } else if(typeof error === "object" && error.type === "jitsiError") {
  1345. return error.errorObject;
  1346. } else {
  1347. return this.GENERAL;
  1348. }
  1349. },
  1350. UNSUPPORTED_RESOLUTION: "gum.unsupported_resolution",
  1351. FIREFOX_EXTENSION_NEEDED: "gum.firefox_extension_needed",
  1352. GENERAL: "gum.general"
  1353. };
  1354. },{}],10:[function(require,module,exports){
  1355. var JitsiTrackEvents = {
  1356. /**
  1357. * A media track mute status was changed.
  1358. */
  1359. TRACK_MUTE_CHANGED: "track.trackMuteChanged",
  1360. /**
  1361. * Audio levels of a this track was changed.
  1362. */
  1363. TRACK_AUDIO_LEVEL_CHANGED: "track.audioLevelsChanged",
  1364. /**
  1365. * The media track was removed to the conference.
  1366. */
  1367. TRACK_STOPPED: "track.stopped"
  1368. };
  1369. module.exports = JitsiTrackEvents;
  1370. },{}],11:[function(require,module,exports){
  1371. (function (__filename){
  1372. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1373. function JitsiDTMFManager (localAudio, peerConnection) {
  1374. var tracks = localAudio._getTracks();
  1375. if (!tracks.length) {
  1376. throw new Error("Failed to initialize DTMFSender: no audio track.");
  1377. }
  1378. this.dtmfSender = peerConnection.peerconnection.createDTMFSender(tracks[0]);
  1379. logger.debug("Initialized DTMFSender");
  1380. }
  1381. JitsiDTMFManager.prototype.sendTones = function (tones, duration, pause) {
  1382. this.dtmfSender.insertDTMF(tones, (duration || 200), (pause || 200));
  1383. };
  1384. }).call(this,"/modules/DTMF/JitsiDTMFManager.js")
  1385. },{"jitsi-meet-logger":47}],12:[function(require,module,exports){
  1386. (function (__filename){
  1387. /* global config, APP, Strophe */
  1388. // cache datachannels to avoid garbage collection
  1389. // https://code.google.com/p/chromium/issues/detail?id=405545
  1390. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1391. var RTCEvents = require("../../service/RTC/RTCEvents");
  1392. /**
  1393. * Binds "ondatachannel" event listener to given PeerConnection instance.
  1394. * @param peerConnection WebRTC peer connection instance.
  1395. */
  1396. function DataChannels(peerConnection, emitter) {
  1397. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  1398. this.eventEmitter = emitter;
  1399. this._dataChannels = [];
  1400. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  1401. // Although it's not a requirement to open separate channels from both bridge
  1402. // and peer as single channel can be used for sending and receiving data.
  1403. // So either channel opened by the bridge or the one opened here is enough
  1404. // for communication with the bridge.
  1405. /*var dataChannelOptions =
  1406. {
  1407. reliable: true
  1408. };
  1409. var dataChannel
  1410. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  1411. // Can be used only when is in open state
  1412. dataChannel.onopen = function ()
  1413. {
  1414. dataChannel.send("My channel !!!");
  1415. };
  1416. dataChannel.onmessage = function (event)
  1417. {
  1418. var msgData = event.data;
  1419. logger.info("Got My Data Channel Message:", msgData, dataChannel);
  1420. };*/
  1421. };
  1422. /**
  1423. * Callback triggered by PeerConnection when new data channel is opened
  1424. * on the bridge.
  1425. * @param event the event info object.
  1426. */
  1427. DataChannels.prototype.onDataChannel = function (event) {
  1428. var dataChannel = event.channel;
  1429. var self = this;
  1430. var lastSelectedEndpoint = null;
  1431. dataChannel.onopen = function () {
  1432. logger.info("Data channel opened by the Videobridge!", dataChannel);
  1433. // Code sample for sending string and/or binary data
  1434. // Sends String message to the bridge
  1435. //dataChannel.send("Hello bridge!");
  1436. // Sends 12 bytes binary message to the bridge
  1437. //dataChannel.send(new ArrayBuffer(12));
  1438. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  1439. // when the data channel becomes available, tell the bridge about video
  1440. // selections so that it can do adaptive simulcast,
  1441. // we want the notification to trigger even if userJid is undefined,
  1442. // or null.
  1443. self.handleSelectedEndpointEvent(self.lastSelectedEndpoint);
  1444. };
  1445. dataChannel.onerror = function (error) {
  1446. logger.error("Data Channel Error:", error, dataChannel);
  1447. };
  1448. dataChannel.onmessage = function (event) {
  1449. var data = event.data;
  1450. // JSON
  1451. var obj;
  1452. try {
  1453. obj = JSON.parse(data);
  1454. }
  1455. catch (e) {
  1456. logger.error(
  1457. "Failed to parse data channel message as JSON: ",
  1458. data,
  1459. dataChannel);
  1460. }
  1461. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  1462. var colibriClass = obj.colibriClass;
  1463. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  1464. // Endpoint ID from the Videobridge.
  1465. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  1466. logger.info(
  1467. "Data channel new dominant speaker event: ",
  1468. dominantSpeakerEndpoint);
  1469. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  1470. }
  1471. else if ("InLastNChangeEvent" === colibriClass) {
  1472. var oldValue = obj.oldValue;
  1473. var newValue = obj.newValue;
  1474. // Make sure that oldValue and newValue are of type boolean.
  1475. var type;
  1476. if ((type = typeof oldValue) !== 'boolean') {
  1477. if (type === 'string') {
  1478. oldValue = (oldValue == "true");
  1479. } else {
  1480. oldValue = new Boolean(oldValue).valueOf();
  1481. }
  1482. }
  1483. if ((type = typeof newValue) !== 'boolean') {
  1484. if (type === 'string') {
  1485. newValue = (newValue == "true");
  1486. } else {
  1487. newValue = new Boolean(newValue).valueOf();
  1488. }
  1489. }
  1490. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  1491. }
  1492. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  1493. // The new/latest list of last-n endpoint IDs.
  1494. var lastNEndpoints = obj.lastNEndpoints;
  1495. // The list of endpoint IDs which are entering the list of
  1496. // last-n at this time i.e. were not in the old list of last-n
  1497. // endpoint IDs.
  1498. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  1499. logger.info(
  1500. "Data channel new last-n event: ",
  1501. lastNEndpoints, endpointsEnteringLastN, obj);
  1502. self.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1503. lastNEndpoints, endpointsEnteringLastN, obj);
  1504. }
  1505. else {
  1506. logger.debug("Data channel JSON-formatted message: ", obj);
  1507. // The received message appears to be appropriately formatted
  1508. // (i.e. is a JSON object which assigns a value to the mandatory
  1509. // property colibriClass) so don't just swallow it, expose it to
  1510. // public consumption.
  1511. self.eventEmitter.emit("rtc.datachannel." + colibriClass, obj);
  1512. }
  1513. }
  1514. };
  1515. dataChannel.onclose = function () {
  1516. logger.info("The Data Channel closed", dataChannel);
  1517. var idx = self._dataChannels.indexOf(dataChannel);
  1518. if (idx > -1)
  1519. self._dataChannels = self._dataChannels.splice(idx, 1);
  1520. };
  1521. this._dataChannels.push(dataChannel);
  1522. };
  1523. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  1524. this.lastSelectedEndpoint = userResource;
  1525. this._onXXXEndpointChanged("selected", userResource);
  1526. }
  1527. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  1528. this._onXXXEndpointChanged("pinnned", userResource);
  1529. }
  1530. /**
  1531. * Notifies Videobridge about a change in the value of a specific
  1532. * endpoint-related property such as selected endpoint and pinnned endpoint.
  1533. *
  1534. * @param xxx the name of the endpoint-related property whose value changed
  1535. * @param userResource the new value of the endpoint-related property after the
  1536. * change
  1537. */
  1538. DataChannels.prototype._onXXXEndpointChanged = function (xxx, userResource) {
  1539. // Derive the correct words from xxx such as selected and Selected, pinned
  1540. // and Pinned.
  1541. var head = xxx.charAt(0);
  1542. var tail = xxx.substring(1);
  1543. var lower = head.toLowerCase() + tail;
  1544. var upper = head.toUpperCase() + tail;
  1545. // Notify Videobridge about the specified endpoint change.
  1546. console.log(lower + ' endpoint changed: ', userResource);
  1547. this._some(function (dataChannel) {
  1548. if (dataChannel.readyState == 'open') {
  1549. console.log(
  1550. 'sending ' + lower
  1551. + ' endpoint changed notification to the bridge: ',
  1552. userResource);
  1553. var jsonObject = {};
  1554. jsonObject.colibriClass = (upper + 'EndpointChangedEvent');
  1555. jsonObject[lower + "Endpoint"]
  1556. = (userResource ? userResource : null);
  1557. dataChannel.send(JSON.stringify(jsonObject));
  1558. return true;
  1559. }
  1560. });
  1561. }
  1562. DataChannels.prototype._some = function (callback, thisArg) {
  1563. var dataChannels = this._dataChannels;
  1564. if (dataChannels && dataChannels.length !== 0) {
  1565. if (thisArg)
  1566. return dataChannels.some(callback, thisArg);
  1567. else
  1568. return dataChannels.some(callback);
  1569. } else {
  1570. return false;
  1571. }
  1572. }
  1573. module.exports = DataChannels;
  1574. }).call(this,"/modules/RTC/DataChannels.js")
  1575. },{"../../service/RTC/RTCEvents":79,"jitsi-meet-logger":47}],13:[function(require,module,exports){
  1576. var JitsiTrack = require("./JitsiTrack");
  1577. var RTCBrowserType = require("./RTCBrowserType");
  1578. var JitsiTrackEvents = require('../../JitsiTrackEvents');
  1579. var RTCUtils = require("./RTCUtils");
  1580. /**
  1581. * Represents a single media track (either audio or video).
  1582. * @constructor
  1583. */
  1584. function JitsiLocalTrack(stream, videoType,
  1585. resolution)
  1586. {
  1587. this.videoType = videoType;
  1588. this.dontFireRemoveEvent = false;
  1589. this.resolution = resolution;
  1590. this.startMuted = false;
  1591. var self = this;
  1592. JitsiTrack.call(this, null, stream,
  1593. function () {
  1594. if(!this.dontFireRemoveEvent)
  1595. this.eventEmitter.emit(
  1596. JitsiTrackEvents.TRACK_STOPPED);
  1597. this.dontFireRemoveEvent = false;
  1598. }.bind(this));
  1599. }
  1600. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  1601. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  1602. /**
  1603. * Mutes / unmutes the track.
  1604. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  1605. */
  1606. JitsiLocalTrack.prototype._setMute = function (mute) {
  1607. if (this.isMuted() === mute) {
  1608. return;
  1609. }
  1610. if(!this.rtc) {
  1611. this.startMuted = mute;
  1612. return;
  1613. }
  1614. var isAudio = this.type === JitsiTrack.AUDIO;
  1615. this.dontFireRemoveEvent = false;
  1616. if ((window.location.protocol != "https:") ||
  1617. (isAudio) || this.videoType === "desktop" ||
  1618. // FIXME FF does not support 'removeStream' method used to mute
  1619. RTCBrowserType.isFirefox()) {
  1620. var tracks = this._getTracks();
  1621. for (var idx = 0; idx < tracks.length; idx++) {
  1622. tracks[idx].enabled = !mute;
  1623. }
  1624. if(isAudio)
  1625. this.rtc.room.setAudioMute(mute);
  1626. else
  1627. this.rtc.room.setVideoMute(mute);
  1628. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1629. } else {
  1630. if (mute) {
  1631. this.dontFireRemoveEvent = true;
  1632. this.rtc.room.removeStream(this.stream, function () {});
  1633. RTCUtils.stopMediaStream(this.stream);
  1634. if(isAudio)
  1635. this.rtc.room.setAudioMute(mute);
  1636. else
  1637. this.rtc.room.setVideoMute(mute);
  1638. this.stream = null;
  1639. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1640. //FIXME: Maybe here we should set the SRC for the containers to something
  1641. } else {
  1642. var self = this;
  1643. RTCUtils.obtainAudioAndVideoPermissions({
  1644. devices: (isAudio ? ["audio"] : ["video"]),
  1645. resolution: self.resolution})
  1646. .then(function (streams) {
  1647. var stream = null;
  1648. for(var i = 0; i < streams.length; i++) {
  1649. stream = streams[i];
  1650. if(stream.type === self.type) {
  1651. self.stream = stream.stream;
  1652. self.videoType = stream.videoType;
  1653. break;
  1654. }
  1655. }
  1656. if(!stream)
  1657. return;
  1658. for(var i = 0; i < self.containers.length; i++)
  1659. {
  1660. RTCUtils.attachMediaStream(
  1661. self.containers[i], self.stream);
  1662. }
  1663. self.rtc.room.addStream(stream.stream,
  1664. function () {
  1665. if(isAudio)
  1666. self.rtc.room.setAudioMute(mute);
  1667. else
  1668. self.rtc.room.setVideoMute(mute);
  1669. self.eventEmitter.emit(
  1670. JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1671. });
  1672. });
  1673. }
  1674. }
  1675. }
  1676. /**
  1677. * Stops sending the media track. And removes it from the HTML.
  1678. * NOTE: Works for local tracks only.
  1679. */
  1680. JitsiLocalTrack.prototype.stop = function () {
  1681. if(!this.stream)
  1682. return;
  1683. if(this.rtc)
  1684. this.rtc.room.removeStream(this.stream, function () {});
  1685. RTCUtils.stopMediaStream(this.stream);
  1686. this.detach();
  1687. }
  1688. /**
  1689. * Returns <tt>true</tt> - if the stream is muted
  1690. * and <tt>false</tt> otherwise.
  1691. * @returns {boolean} <tt>true</tt> - if the stream is muted
  1692. * and <tt>false</tt> otherwise.
  1693. */
  1694. JitsiLocalTrack.prototype.isMuted = function () {
  1695. if (!this.stream)
  1696. return true;
  1697. var tracks = [];
  1698. var isAudio = this.type === JitsiTrack.AUDIO;
  1699. if (isAudio) {
  1700. tracks = this.stream.getAudioTracks();
  1701. } else {
  1702. if (!this.isActive())
  1703. return true;
  1704. tracks = this.stream.getVideoTracks();
  1705. }
  1706. for (var idx = 0; idx < tracks.length; idx++) {
  1707. if(tracks[idx].enabled)
  1708. return false;
  1709. }
  1710. return true;
  1711. };
  1712. /**
  1713. * Private method. Updates rtc property of the track.
  1714. * @param rtc the rtc instance.
  1715. */
  1716. JitsiLocalTrack.prototype._setRTC = function (rtc) {
  1717. this.rtc = rtc;
  1718. };
  1719. /**
  1720. * Return true;
  1721. */
  1722. JitsiLocalTrack.prototype.isLocal = function () {
  1723. return true;
  1724. }
  1725. module.exports = JitsiLocalTrack;
  1726. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils":18}],14:[function(require,module,exports){
  1727. var JitsiTrack = require("./JitsiTrack");
  1728. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1729. /**
  1730. * Represents a single media track (either audio or video).
  1731. * @param RTC the rtc instance.
  1732. * @param data object with the stream and some details about it(participant id, video type, etc.)
  1733. * @param sid sid for the Media Stream
  1734. * @param ssrc ssrc for the Media Stream
  1735. * @param eventEmitter the event emitter
  1736. * @constructor
  1737. */
  1738. function JitsiRemoteTrack(RTC, data, sid, ssrc) {
  1739. JitsiTrack.call(this, RTC, data.stream,
  1740. function () {
  1741. this.eventEmitter.emit(JitsiTrackEvents.TRACK_STOPPED);
  1742. }.bind(this));
  1743. this.rtc = RTC;
  1744. this.sid = sid;
  1745. this.stream = data.stream;
  1746. this.peerjid = data.peerjid;
  1747. this.videoType = data.videoType;
  1748. this.ssrc = ssrc;
  1749. this.muted = false;
  1750. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  1751. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  1752. this.muted = true;
  1753. }
  1754. }
  1755. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  1756. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  1757. /**
  1758. * Sets current muted status and fires an events for the change.
  1759. * @param value the muted status.
  1760. */
  1761. JitsiRemoteTrack.prototype.setMute = function (value) {
  1762. if(this.muted === value)
  1763. return;
  1764. this.stream.muted = value;
  1765. this.muted = value;
  1766. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1767. };
  1768. /**
  1769. * Returns the current muted status of the track.
  1770. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  1771. */
  1772. JitsiRemoteTrack.prototype.isMuted = function () {
  1773. return this.muted;
  1774. };
  1775. /**
  1776. * Returns the participant id which owns the track.
  1777. * @returns {string} the id of the participants.
  1778. */
  1779. JitsiRemoteTrack.prototype.getParticipantId = function() {
  1780. return Strophe.getResourceFromJid(this.peerjid);
  1781. };
  1782. /**
  1783. * Return false;
  1784. */
  1785. JitsiRemoteTrack.prototype.isLocal = function () {
  1786. return false;
  1787. };
  1788. delete JitsiRemoteTrack.prototype.stop;
  1789. delete JitsiRemoteTrack.prototype.start;
  1790. module.exports = JitsiRemoteTrack;
  1791. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15}],15:[function(require,module,exports){
  1792. var RTCBrowserType = require("./RTCBrowserType");
  1793. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1794. var EventEmitter = require("events");
  1795. var RTC = require("./RTCUtils");
  1796. /**
  1797. * This implements 'onended' callback normally fired by WebRTC after the stream
  1798. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  1799. * @param jitsiTrack our track object holding the original WebRTC stream object
  1800. * to which 'onended' handling will be added.
  1801. */
  1802. function implementOnEndedHandling(jitsiTrack) {
  1803. var stream = jitsiTrack.getOriginalStream();
  1804. var originalStop = stream.stop;
  1805. stream.stop = function () {
  1806. originalStop.apply(stream);
  1807. if (jitsiTrack.isActive()) {
  1808. stream.onended();
  1809. }
  1810. };
  1811. }
  1812. /**
  1813. * Adds onended/oninactive handler to a MediaStream.
  1814. * @param mediaStream a MediaStream to attach onended/oninactive handler
  1815. * @param handler the handler
  1816. */
  1817. function addMediaStreamInactiveHandler(mediaStream, handler) {
  1818. if(RTCBrowserType.isTemasysPluginUsed()) {
  1819. // themasys
  1820. //FIXME: Seems that not working properly.
  1821. if(mediaStream.onended) {
  1822. mediaStream.onended = handler;
  1823. } else if(mediaStream.addEventListener) {
  1824. mediaStream.addEventListener('ended', function () {
  1825. handler(mediaStream);
  1826. });
  1827. } else if(mediaStream.attachEvent) {
  1828. mediaStream.attachEvent('ended', function () {
  1829. handler(mediaStream);
  1830. });
  1831. }
  1832. }
  1833. else {
  1834. if(typeof mediaStream.active !== "undefined")
  1835. mediaStream.oninactive = handler;
  1836. else
  1837. mediaStream.onended = handler;
  1838. }
  1839. }
  1840. /**
  1841. * Represents a single media track (either audio or video).
  1842. * @constructor
  1843. * @param rtc the rtc instance
  1844. * @param stream the stream
  1845. * @param streamInactiveHandler the function that will handle
  1846. * onended/oninactive events of the stream.
  1847. */
  1848. function JitsiTrack(rtc, stream, streamInactiveHandler)
  1849. {
  1850. /**
  1851. * Array with the HTML elements that are displaying the streams.
  1852. * @type {Array}
  1853. */
  1854. this.containers = [];
  1855. this.rtc = rtc;
  1856. this.stream = stream;
  1857. this.eventEmitter = new EventEmitter();
  1858. this.audioLevel = -1;
  1859. this.type = (this.stream.getVideoTracks().length > 0)?
  1860. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  1861. if(this.type == "audio") {
  1862. this._getTracks = function () {
  1863. return this.stream.getAudioTracks();
  1864. }.bind(this);
  1865. } else {
  1866. this._getTracks = function () {
  1867. return this.stream.getVideoTracks();
  1868. }.bind(this);
  1869. }
  1870. if (RTCBrowserType.isFirefox() && this.stream) {
  1871. implementOnEndedHandling(this);
  1872. }
  1873. if(stream)
  1874. addMediaStreamInactiveHandler(stream, streamInactiveHandler);
  1875. }
  1876. /**
  1877. * JitsiTrack video type.
  1878. * @type {string}
  1879. */
  1880. JitsiTrack.VIDEO = "video";
  1881. /**
  1882. * JitsiTrack audio type.
  1883. * @type {string}
  1884. */
  1885. JitsiTrack.AUDIO = "audio";
  1886. /**
  1887. * Returns the type (audio or video) of this track.
  1888. */
  1889. JitsiTrack.prototype.getType = function() {
  1890. return this.type;
  1891. };
  1892. /**
  1893. * Check if this is audiotrack.
  1894. */
  1895. JitsiTrack.prototype.isAudioTrack = function () {
  1896. return this.getType() === JitsiTrack.AUDIO;
  1897. };
  1898. /**
  1899. * Check if this is videotrack.
  1900. */
  1901. JitsiTrack.prototype.isVideoTrack = function () {
  1902. return this.getType() === JitsiTrack.VIDEO;
  1903. };
  1904. /**
  1905. * Returns the RTCMediaStream from the browser (?).
  1906. */
  1907. JitsiTrack.prototype.getOriginalStream = function() {
  1908. return this.stream;
  1909. }
  1910. /**
  1911. * Mutes the track.
  1912. */
  1913. JitsiTrack.prototype.mute = function () {
  1914. this._setMute(true);
  1915. }
  1916. /**
  1917. * Unmutes the stream.
  1918. */
  1919. JitsiTrack.prototype.unmute = function () {
  1920. this._setMute(false);
  1921. }
  1922. /**
  1923. * Attaches the MediaStream of this track to an HTML container (?).
  1924. * Adds the container to the list of containers that are displaying the track.
  1925. * @param container the HTML container
  1926. */
  1927. JitsiTrack.prototype.attach = function (container) {
  1928. if(this.stream)
  1929. require("./RTCUtils").attachMediaStream(container, this.stream);
  1930. this.containers.push(container);
  1931. }
  1932. /**
  1933. * Removes the track from the passed HTML container.
  1934. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  1935. */
  1936. JitsiTrack.prototype.detach = function (container) {
  1937. for(var i = 0; i < this.containers.length; i++)
  1938. {
  1939. if(this.containers[i].is(container))
  1940. {
  1941. this.containers.splice(i,1);
  1942. }
  1943. if(!container)
  1944. {
  1945. this.containers[i].find(">video").remove();
  1946. }
  1947. }
  1948. if(container)
  1949. $(container).find(">video").remove();
  1950. }
  1951. /**
  1952. * Stops sending the media track. And removes it from the HTML.
  1953. * NOTE: Works for local tracks only.
  1954. */
  1955. JitsiTrack.prototype.stop = function () {
  1956. }
  1957. /**
  1958. * Returns true if this is a video track and the source of the video is a
  1959. * screen capture as opposed to a camera.
  1960. */
  1961. JitsiTrack.prototype.isScreenSharing = function(){
  1962. }
  1963. /**
  1964. * Returns id of the track.
  1965. * @returns {string} id of the track or null if this is fake track.
  1966. */
  1967. JitsiTrack.prototype._getId = function () {
  1968. var tracks = this.stream.getTracks();
  1969. if(!tracks || tracks.length === 0)
  1970. return null;
  1971. return tracks[0].id;
  1972. };
  1973. /**
  1974. * Returns id of the track.
  1975. * @returns {string} id of the track or null if this is fake track.
  1976. */
  1977. JitsiTrack.prototype.getId = function () {
  1978. return RTC.getStreamID(this.stream);
  1979. };
  1980. /**
  1981. * Checks whether the MediaStream is avtive/not ended.
  1982. * When there is no check for active we don't have information and so
  1983. * will return that stream is active (in case of FF).
  1984. * @returns {boolean} whether MediaStream is active.
  1985. */
  1986. JitsiTrack.prototype.isActive = function () {
  1987. if((typeof this.stream.active !== "undefined"))
  1988. return this.stream.active;
  1989. else
  1990. return true;
  1991. };
  1992. /**
  1993. * Attaches a handler for events(For example - "audio level changed".).
  1994. * All possible event are defined in JitsiTrackEvents.
  1995. * @param eventId the event ID.
  1996. * @param handler handler for the event.
  1997. */
  1998. JitsiTrack.prototype.on = function (eventId, handler) {
  1999. if(this.eventEmitter)
  2000. this.eventEmitter.on(eventId, handler);
  2001. }
  2002. /**
  2003. * Removes event listener
  2004. * @param eventId the event ID.
  2005. * @param [handler] optional, the specific handler to unbind
  2006. */
  2007. JitsiTrack.prototype.off = function (eventId, handler) {
  2008. if(this.eventEmitter)
  2009. this.eventEmitter.removeListener(eventId, handler);
  2010. }
  2011. // Common aliases for event emitter
  2012. JitsiTrack.prototype.addEventListener = JitsiTrack.prototype.on;
  2013. JitsiTrack.prototype.removeEventListener = JitsiTrack.prototype.off;
  2014. /**
  2015. * Sets the audio level for the stream
  2016. * @param audioLevel the new audio level
  2017. */
  2018. JitsiTrack.prototype.setAudioLevel = function (audioLevel) {
  2019. if(this.audioLevel !== audioLevel) {
  2020. this.eventEmitter.emit(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  2021. audioLevel);
  2022. this.audioLevel = audioLevel;
  2023. }
  2024. }
  2025. module.exports = JitsiTrack;
  2026. },{"../../JitsiTrackEvents":10,"./RTCBrowserType":17,"./RTCUtils":18,"events":43}],16:[function(require,module,exports){
  2027. /* global APP */
  2028. var EventEmitter = require("events");
  2029. var RTCBrowserType = require("./RTCBrowserType");
  2030. var RTCUtils = require("./RTCUtils.js");
  2031. var JitsiTrack = require("./JitsiTrack");
  2032. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  2033. var DataChannels = require("./DataChannels");
  2034. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  2035. var DesktopSharingEventTypes
  2036. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2037. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  2038. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  2039. function createLocalTracks(streams) {
  2040. var newStreams = []
  2041. for (var i = 0; i < streams.length; i++) {
  2042. var localStream = new JitsiLocalTrack(streams[i].stream,
  2043. streams[i].videoType, streams[i].resolution);
  2044. newStreams.push(localStream);
  2045. if (streams[i].isMuted === true)
  2046. localStream.setMute(true);
  2047. }
  2048. return newStreams;
  2049. }
  2050. function RTC(room, options) {
  2051. this.room = room;
  2052. this.localStreams = [];
  2053. //FIXME: we should start removing those streams.
  2054. //FIXME: We should support multiple streams per jid.
  2055. this.remoteStreams = {};
  2056. this.localAudio = null;
  2057. this.localVideo = null;
  2058. this.eventEmitter = new EventEmitter();
  2059. var self = this;
  2060. this.options = options || {};
  2061. room.addPresenceListener("videomuted", function (values, from) {
  2062. if(self.remoteStreams[from]) {
  2063. self.remoteStreams[from][JitsiTrack.VIDEO].setMute(values.value == "true");
  2064. }
  2065. });
  2066. room.addPresenceListener("audiomuted", function (values, from) {
  2067. if(self.remoteStreams[from]) {
  2068. self.remoteStreams[from][JitsiTrack.AUDIO].setMute(values.value == "true");
  2069. }
  2070. });
  2071. }
  2072. /**
  2073. * Creates the local MediaStreams.
  2074. * @param {Object} [options] optional parameters
  2075. * @param {Array} options.devices the devices that will be requested
  2076. * @param {string} options.resolution resolution constraints
  2077. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2078. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2079. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2080. * @param {string} options.cameraDeviceId
  2081. * @param {string} options.micDeviceId
  2082. * @returns {*} Promise object that will receive the new JitsiTracks
  2083. */
  2084. RTC.obtainAudioAndVideoPermissions = function (options) {
  2085. return RTCUtils.obtainAudioAndVideoPermissions(options).then(createLocalTracks);
  2086. }
  2087. RTC.prototype.onIncommingCall = function(event) {
  2088. if(this.options.config.openSctp)
  2089. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  2090. for(var i = 0; i < this.localStreams.length; i++)
  2091. if(this.localStreams[i])
  2092. {
  2093. this.room.addStream(this.localStreams[i].getOriginalStream(), function () {});
  2094. }
  2095. }
  2096. RTC.prototype.selectedEndpoint = function (id) {
  2097. if(this.dataChannels)
  2098. this.dataChannels.handleSelectedEndpointEvent(id);
  2099. }
  2100. RTC.prototype.pinEndpoint = function (id) {
  2101. if(this.dataChannels)
  2102. this.dataChannels.handlePinnedEndpointEvent(id);
  2103. }
  2104. RTC.prototype.addListener = function (type, listener) {
  2105. this.eventEmitter.on(type, listener);
  2106. };
  2107. RTC.prototype.removeListener = function (eventType, listener) {
  2108. this.eventEmitter.removeListener(eventType, listener);
  2109. };
  2110. RTC.addListener = function (eventType, listener) {
  2111. RTCUtils.addListener(eventType, listener);
  2112. }
  2113. RTC.removeListener = function (eventType, listener) {
  2114. RTCUtils.removeListener(eventType, listener)
  2115. }
  2116. RTC.isRTCReady = function () {
  2117. return RTCUtils.isRTCReady();
  2118. }
  2119. RTC.init = function (options) {
  2120. this.options = options || {};
  2121. return RTCUtils.init(this.options);
  2122. }
  2123. RTC.getDeviceAvailability = function () {
  2124. return RTCUtils.getDeviceAvailability();
  2125. }
  2126. RTC.prototype.addLocalStream = function (stream) {
  2127. this.localStreams.push(stream);
  2128. stream._setRTC(this);
  2129. if (stream.type == "audio") {
  2130. this.localAudio = stream;
  2131. } else {
  2132. this.localVideo = stream;
  2133. }
  2134. };
  2135. /**
  2136. * Set mute for all local audio streams attached to the conference.
  2137. * @param value the mute value
  2138. */
  2139. RTC.prototype.setAudioMute = function (value) {
  2140. for(var i = 0; i < this.localStreams.length; i++) {
  2141. var stream = this.localStreams[i];
  2142. if(stream.getType() !== "audio") {
  2143. continue;
  2144. }
  2145. stream._setMute(value);
  2146. }
  2147. }
  2148. RTC.prototype.removeLocalStream = function (track) {
  2149. var pos = this.localStreams.indexOf(track);
  2150. if (pos > -1) {
  2151. this.localStreams.splice(pos, 1);
  2152. }
  2153. };
  2154. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  2155. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc);
  2156. if(!data.peerjid)
  2157. return;
  2158. var jid = Strophe.getResourceFromJid(data.peerjid);
  2159. if(!this.remoteStreams[jid]) {
  2160. this.remoteStreams[jid] = {};
  2161. }
  2162. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  2163. return remoteStream;
  2164. };
  2165. RTC.getPCConstraints = function () {
  2166. return RTCUtils.pc_constraints;
  2167. };
  2168. RTC.attachMediaStream = function (elSelector, stream) {
  2169. RTCUtils.attachMediaStream(elSelector, stream);
  2170. };
  2171. RTC.getStreamID = function (stream) {
  2172. return RTCUtils.getStreamID(stream);
  2173. };
  2174. RTC.getVideoSrc = function (element) {
  2175. return RTCUtils.getVideoSrc(element);
  2176. };
  2177. /**
  2178. * Returns true if retrieving the the list of input devices is supported and
  2179. * false if not.
  2180. */
  2181. RTC.isDeviceListAvailable = function () {
  2182. return RTCUtils.isDeviceListAvailable();
  2183. };
  2184. /**
  2185. * Returns true if changing the camera / microphone device is supported and
  2186. * false if not.
  2187. */
  2188. RTC.isDeviceChangeAvailable = function () {
  2189. return RTCUtils.isDeviceChangeAvailable();
  2190. }
  2191. /**
  2192. * Allows to receive list of available cameras/microphones.
  2193. * @param {function} callback would receive array of devices as an argument
  2194. */
  2195. RTC.enumerateDevices = function (callback) {
  2196. RTCUtils.enumerateDevices(callback);
  2197. };
  2198. RTC.setVideoSrc = function (element, src) {
  2199. RTCUtils.setVideoSrc(element, src);
  2200. };
  2201. /**
  2202. * A method to handle stopping of the stream.
  2203. * One point to handle the differences in various implementations.
  2204. * @param mediaStream MediaStream object to stop.
  2205. */
  2206. RTC.stopMediaStream = function (mediaStream) {
  2207. RTCUtils.stopMediaStream(mediaStream);
  2208. };
  2209. /**
  2210. * Returns whether the desktop sharing is enabled or not.
  2211. * @returns {boolean}
  2212. */
  2213. RTC.isDesktopSharingEnabled = function () {
  2214. return RTCUtils.isDesktopSharingEnabled();
  2215. }
  2216. RTC.prototype.getVideoElementName = function () {
  2217. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  2218. };
  2219. RTC.prototype.dispose = function() {
  2220. };
  2221. RTC.prototype.switchVideoStreams = function (newStream) {
  2222. this.localVideo.stream = newStream;
  2223. this.localStreams = [];
  2224. //in firefox we have only one stream object
  2225. if (this.localAudio.getOriginalStream() != newStream)
  2226. this.localStreams.push(this.localAudio);
  2227. this.localStreams.push(this.localVideo);
  2228. };
  2229. RTC.prototype.setAudioLevel = function (jid, audioLevel) {
  2230. if(!jid)
  2231. return;
  2232. var resource = Strophe.getResourceFromJid(jid);
  2233. if(this.remoteStreams[resource] && this.remoteStreams[resource][JitsiTrack.AUDIO])
  2234. this.remoteStreams[resource][JitsiTrack.AUDIO].setAudioLevel(audioLevel);
  2235. }
  2236. module.exports = RTC;
  2237. },{"../../service/RTC/MediaStreamTypes":78,"../../service/RTC/RTCEvents.js":79,"../../service/desktopsharing/DesktopSharingEventTypes":82,"./DataChannels":12,"./JitsiLocalTrack.js":13,"./JitsiRemoteTrack.js":14,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils.js":18,"events":43}],17:[function(require,module,exports){
  2238. var currentBrowser;
  2239. var browserVersion;
  2240. var isAndroid;
  2241. var RTCBrowserType = {
  2242. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  2243. RTC_BROWSER_OPERA: "rtc_browser.opera",
  2244. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  2245. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  2246. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  2247. getBrowserType: function () {
  2248. return currentBrowser;
  2249. },
  2250. isChrome: function () {
  2251. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  2252. },
  2253. isOpera: function () {
  2254. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  2255. },
  2256. isFirefox: function () {
  2257. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  2258. },
  2259. isIExplorer: function () {
  2260. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2261. },
  2262. isSafari: function () {
  2263. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  2264. },
  2265. isTemasysPluginUsed: function () {
  2266. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  2267. },
  2268. getFirefoxVersion: function () {
  2269. return RTCBrowserType.isFirefox() ? browserVersion : null;
  2270. },
  2271. getChromeVersion: function () {
  2272. return RTCBrowserType.isChrome() ? browserVersion : null;
  2273. },
  2274. usesPlanB: function() {
  2275. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  2276. RTCBrowserType.isTemasysPluginUsed();
  2277. },
  2278. usesUnifiedPlan: function() {
  2279. return RTCBrowserType.isFirefox();
  2280. },
  2281. /**
  2282. * Whether the browser is running on an android device.
  2283. */
  2284. isAndroid: function() {
  2285. return isAndroid;
  2286. }
  2287. // Add version getters for other browsers when needed
  2288. };
  2289. // detectOpera() must be called before detectChrome() !!!
  2290. // otherwise Opera wil be detected as Chrome
  2291. function detectChrome() {
  2292. if (navigator.webkitGetUserMedia) {
  2293. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  2294. var userAgent = navigator.userAgent.toLowerCase();
  2295. // We can assume that user agent is chrome, because it's
  2296. // enforced when 'ext' streaming method is set
  2297. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  2298. console.log("This appears to be Chrome, ver: " + ver);
  2299. return ver;
  2300. }
  2301. return null;
  2302. }
  2303. function detectOpera() {
  2304. var userAgent = navigator.userAgent;
  2305. if (userAgent.match(/Opera|OPR/)) {
  2306. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  2307. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  2308. console.info("This appears to be Opera, ver: " + version);
  2309. return version;
  2310. }
  2311. return null;
  2312. }
  2313. function detectFirefox() {
  2314. if (navigator.mozGetUserMedia) {
  2315. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  2316. var version = parseInt(
  2317. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2318. console.log('This appears to be Firefox, ver: ' + version);
  2319. return version;
  2320. }
  2321. return null;
  2322. }
  2323. function detectSafari() {
  2324. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  2325. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  2326. console.info("This appears to be Safari");
  2327. // FIXME detect Safari version when needed
  2328. return 1;
  2329. }
  2330. return null;
  2331. }
  2332. function detectIE() {
  2333. var version;
  2334. var ua = window.navigator.userAgent;
  2335. var msie = ua.indexOf('MSIE ');
  2336. if (msie > 0) {
  2337. // IE 10 or older => return version number
  2338. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  2339. }
  2340. var trident = ua.indexOf('Trident/');
  2341. if (!version && trident > 0) {
  2342. // IE 11 => return version number
  2343. var rv = ua.indexOf('rv:');
  2344. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  2345. }
  2346. var edge = ua.indexOf('Edge/');
  2347. if (!version && edge > 0) {
  2348. // IE 12 => return version number
  2349. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  2350. }
  2351. if (version) {
  2352. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2353. console.info("This appears to be IExplorer, ver: " + version);
  2354. }
  2355. return version;
  2356. }
  2357. function detectBrowser() {
  2358. var version;
  2359. var detectors = [
  2360. detectOpera,
  2361. detectChrome,
  2362. detectFirefox,
  2363. detectIE,
  2364. detectSafari
  2365. ];
  2366. // Try all browser detectors
  2367. for (var i = 0; i < detectors.length; i++) {
  2368. version = detectors[i]();
  2369. if (version)
  2370. return version;
  2371. }
  2372. console.warn("Browser type defaults to Safari ver 1");
  2373. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  2374. return 1;
  2375. }
  2376. browserVersion = detectBrowser();
  2377. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  2378. module.exports = RTCBrowserType;
  2379. },{}],18:[function(require,module,exports){
  2380. (function (__filename){
  2381. /* global config, require, attachMediaStream, getUserMedia,
  2382. RTCPeerConnection, RTCSessionDescription, RTCIceCandidate, MediaStreamTrack,
  2383. mozRTCPeerConnection, mozRTCSessionDescription, mozRTCIceCandidate,
  2384. webkitRTCPeerConnection, webkitMediaStream, webkitURL
  2385. */
  2386. /* jshint -W101 */
  2387. var logger = require("jitsi-meet-logger").getLogger(__filename);
  2388. var RTCBrowserType = require("./RTCBrowserType");
  2389. var Resolutions = require("../../service/RTC/Resolutions");
  2390. var RTCEvents = require("../../service/RTC/RTCEvents");
  2391. var AdapterJS = require("./adapter.screenshare");
  2392. var SDPUtil = require("../xmpp/SDPUtil");
  2393. var EventEmitter = require("events");
  2394. var screenObtainer = require("./ScreenObtainer");
  2395. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  2396. var eventEmitter = new EventEmitter();
  2397. var devices = {
  2398. audio: true,
  2399. video: true
  2400. };
  2401. var rtcReady = false;
  2402. function setResolutionConstraints(constraints, resolution) {
  2403. var isAndroid = RTCBrowserType.isAndroid();
  2404. if (Resolutions[resolution]) {
  2405. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  2406. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  2407. }
  2408. else if (isAndroid) {
  2409. // FIXME can't remember if the purpose of this was to always request
  2410. // low resolution on Android ? if yes it should be moved up front
  2411. constraints.video.mandatory.minWidth = 320;
  2412. constraints.video.mandatory.minHeight = 240;
  2413. constraints.video.mandatory.maxFrameRate = 15;
  2414. }
  2415. if (constraints.video.mandatory.minWidth)
  2416. constraints.video.mandatory.maxWidth =
  2417. constraints.video.mandatory.minWidth;
  2418. if (constraints.video.mandatory.minHeight)
  2419. constraints.video.mandatory.maxHeight =
  2420. constraints.video.mandatory.minHeight;
  2421. }
  2422. /**
  2423. * @param {string[]} um required user media types
  2424. *
  2425. * @param {Object} [options={}] optional parameters
  2426. * @param {string} options.resolution
  2427. * @param {number} options.bandwidth
  2428. * @param {number} options.fps
  2429. * @param {string} options.desktopStream
  2430. * @param {string} options.cameraDeviceId
  2431. * @param {string} options.micDeviceId
  2432. * @param {bool} firefox_fake_device
  2433. */
  2434. function getConstraints(um, options) {
  2435. var constraints = {audio: false, video: false};
  2436. if (um.indexOf('video') >= 0) {
  2437. // same behaviour as true
  2438. constraints.video = { mandatory: {}, optional: [] };
  2439. if (options.cameraDeviceId) {
  2440. constraints.video.optional.push({
  2441. sourceId: options.cameraDeviceId
  2442. });
  2443. }
  2444. constraints.video.optional.push({ googLeakyBucket: true });
  2445. setResolutionConstraints(constraints, options.resolution);
  2446. }
  2447. if (um.indexOf('audio') >= 0) {
  2448. if (!RTCBrowserType.isFirefox()) {
  2449. // same behaviour as true
  2450. constraints.audio = { mandatory: {}, optional: []};
  2451. if (options.micDeviceId) {
  2452. constraints.audio.optional.push({
  2453. sourceId: options.micDeviceId
  2454. });
  2455. }
  2456. // if it is good enough for hangouts...
  2457. constraints.audio.optional.push(
  2458. {googEchoCancellation: true},
  2459. {googAutoGainControl: true},
  2460. {googNoiseSupression: true},
  2461. {googHighpassFilter: true},
  2462. {googNoisesuppression2: true},
  2463. {googEchoCancellation2: true},
  2464. {googAutoGainControl2: true}
  2465. );
  2466. } else {
  2467. if (options.micDeviceId) {
  2468. constraints.audio = {
  2469. mandatory: {},
  2470. optional: [{
  2471. sourceId: options.micDeviceId
  2472. }]};
  2473. } else {
  2474. constraints.audio = true;
  2475. }
  2476. }
  2477. }
  2478. if (um.indexOf('screen') >= 0) {
  2479. if (RTCBrowserType.isChrome()) {
  2480. constraints.video = {
  2481. mandatory: {
  2482. chromeMediaSource: "screen",
  2483. googLeakyBucket: true,
  2484. maxWidth: window.screen.width,
  2485. maxHeight: window.screen.height,
  2486. maxFrameRate: 3
  2487. },
  2488. optional: []
  2489. };
  2490. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  2491. constraints.video = {
  2492. optional: [
  2493. {
  2494. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  2495. }
  2496. ]
  2497. };
  2498. } else if (RTCBrowserType.isFirefox()) {
  2499. constraints.video = {
  2500. mozMediaSource: "window",
  2501. mediaSource: "window"
  2502. };
  2503. } else {
  2504. logger.error(
  2505. "'screen' WebRTC media source is supported only in Chrome" +
  2506. " and with Temasys plugin");
  2507. }
  2508. }
  2509. if (um.indexOf('desktop') >= 0) {
  2510. constraints.video = {
  2511. mandatory: {
  2512. chromeMediaSource: "desktop",
  2513. chromeMediaSourceId: options.desktopStream,
  2514. googLeakyBucket: true,
  2515. maxWidth: window.screen.width,
  2516. maxHeight: window.screen.height,
  2517. maxFrameRate: 3
  2518. },
  2519. optional: []
  2520. };
  2521. }
  2522. if (options.bandwidth) {
  2523. if (!constraints.video) {
  2524. //same behaviour as true
  2525. constraints.video = {mandatory: {}, optional: []};
  2526. }
  2527. constraints.video.optional.push({bandwidth: options.bandwidth});
  2528. }
  2529. if (options.fps) {
  2530. // for some cameras it might be necessary to request 30fps
  2531. // so they choose 30fps mjpg over 10fps yuy2
  2532. if (!constraints.video) {
  2533. // same behaviour as true;
  2534. constraints.video = {mandatory: {}, optional: []};
  2535. }
  2536. constraints.video.mandatory.minFrameRate = options.fps;
  2537. }
  2538. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  2539. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  2540. // this later can be a problem with some of the tests
  2541. if(RTCBrowserType.isFirefox() && options.firefox_fake_device)
  2542. {
  2543. // seems to be fixed now, removing this experimental fix, as having
  2544. // multiple audio tracks brake the tests
  2545. //constraints.audio = true;
  2546. constraints.fake = true;
  2547. }
  2548. return constraints;
  2549. }
  2550. function setAvailableDevices(um, available) {
  2551. if (um.indexOf("video") != -1) {
  2552. devices.video = available;
  2553. }
  2554. if (um.indexOf("audio") != -1) {
  2555. devices.audio = available;
  2556. }
  2557. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  2558. }
  2559. // In case of IE we continue from 'onReady' callback
  2560. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  2561. // once it is initialized.
  2562. function onReady (options, GUM) {
  2563. rtcReady = true;
  2564. eventEmitter.emit(RTCEvents.RTC_READY, true);
  2565. screenObtainer.init(options, GUM);
  2566. }
  2567. /**
  2568. * Apply function with arguments if function exists.
  2569. * Do nothing if function not provided.
  2570. * @param {function} [fn] function to apply
  2571. * @param {Array} [args=[]] arguments for function
  2572. */
  2573. function maybeApply(fn, args) {
  2574. if (fn) {
  2575. fn.apply(null, args || []);
  2576. }
  2577. }
  2578. var getUserMediaStatus = {
  2579. initialized: false,
  2580. callbacks: []
  2581. };
  2582. /**
  2583. * Wrap `getUserMedia` to allow others to know if it was executed at least
  2584. * once or not. Wrapper function uses `getUserMediaStatus` object.
  2585. * @param {Function} getUserMedia native function
  2586. * @returns {Function} wrapped function
  2587. */
  2588. function wrapGetUserMedia(getUserMedia) {
  2589. return function (constraints, successCallback, errorCallback) {
  2590. getUserMedia(constraints, function (stream) {
  2591. maybeApply(successCallback, [stream]);
  2592. if (!getUserMediaStatus.initialized) {
  2593. getUserMediaStatus.initialized = true;
  2594. getUserMediaStatus.callbacks.forEach(function (callback) {
  2595. callback();
  2596. });
  2597. getUserMediaStatus.callbacks.length = 0;
  2598. }
  2599. }, function (error) {
  2600. maybeApply(errorCallback, [error]);
  2601. });
  2602. };
  2603. }
  2604. /**
  2605. * Create stub device which equals to auto selected device.
  2606. * @param {string} kind if that should be `audio` or `video` device
  2607. * @returns {Object} stub device description in `enumerateDevices` format
  2608. */
  2609. function createAutoDeviceInfo(kind) {
  2610. return {
  2611. facing: null,
  2612. label: 'Auto',
  2613. kind: kind,
  2614. deviceId: '',
  2615. groupId: null
  2616. };
  2617. }
  2618. /**
  2619. * Execute function after getUserMedia was executed at least once.
  2620. * @param {Function} callback function to execute after getUserMedia
  2621. */
  2622. function afterUserMediaInitialized(callback) {
  2623. if (getUserMediaStatus.initialized) {
  2624. callback();
  2625. } else {
  2626. getUserMediaStatus.callbacks.push(callback);
  2627. }
  2628. }
  2629. /**
  2630. * Wrapper function which makes enumerateDevices to wait
  2631. * until someone executes getUserMedia first time.
  2632. * @param {Function} enumerateDevices native function
  2633. * @returns {Funtion} wrapped function
  2634. */
  2635. function wrapEnumerateDevices(enumerateDevices) {
  2636. return function (callback) {
  2637. // enumerate devices only after initial getUserMedia
  2638. afterUserMediaInitialized(function () {
  2639. enumerateDevices().then(function (devices) {
  2640. //add auto devices
  2641. devices.unshift(
  2642. createAutoDeviceInfo('audioinput'),
  2643. createAutoDeviceInfo('videoinput')
  2644. );
  2645. callback(devices);
  2646. }, function (err) {
  2647. console.error('cannot enumerate devices: ', err);
  2648. // return only auto devices
  2649. callback([createAutoDeviceInfo('audioInput'),
  2650. createAutoDeviceInfo('videoinput')]);
  2651. });
  2652. });
  2653. };
  2654. }
  2655. /**
  2656. * Use old MediaStreamTrack to get devices list and
  2657. * convert it to enumerateDevices format.
  2658. * @param {Function} callback function to call when received devices list.
  2659. */
  2660. function enumerateDevicesThroughMediaStreamTrack (callback) {
  2661. MediaStreamTrack.getSources(function (sources) {
  2662. var devices = sources.map(function (source) {
  2663. var kind = (source.kind || '').toLowerCase();
  2664. return {
  2665. facing: source.facing || null,
  2666. label: source.label,
  2667. kind: kind ? kind + 'input': null,
  2668. deviceId: source.id,
  2669. groupId: source.groupId || null
  2670. };
  2671. });
  2672. //add auto devices
  2673. devices.unshift(
  2674. createAutoDeviceInfo('audioinput'),
  2675. createAutoDeviceInfo('videoinput')
  2676. );
  2677. callback(devices);
  2678. });
  2679. }
  2680. function obtainDevices(options) {
  2681. if(!options.devices || options.devices.length === 0) {
  2682. return options.successCallback(options.streams || {});
  2683. }
  2684. var device = options.devices.splice(0, 1);
  2685. var devices = [];
  2686. devices.push(device);
  2687. options.deviceGUM[device](function (stream) {
  2688. options.streams = options.streams || {};
  2689. options.streams[device] = stream;
  2690. obtainDevices(options);
  2691. },
  2692. function (error) {
  2693. Object.keys(options.streams).forEach(function(device) {
  2694. RTCUtils.stopMediaStream(options.streams[device]);
  2695. });
  2696. logger.error(
  2697. "failed to obtain " + device + " stream - stop", error);
  2698. options.errorCallback(JitsiTrackErrors.parseError(error, devices));
  2699. });
  2700. }
  2701. /**
  2702. * Handles the newly created Media Streams.
  2703. * @param streams the new Media Streams
  2704. * @param resolution the resolution of the video streams
  2705. * @returns {*[]} object that describes the new streams
  2706. */
  2707. function handleLocalStream(streams, resolution) {
  2708. var audioStream, videoStream, desktopStream, res = [];
  2709. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  2710. // an object with two properties: audioStream, videoStream.
  2711. if (window.webkitMediaStream) {
  2712. var audioVideo = streams.audioVideo;
  2713. if (audioVideo) {
  2714. var audioTracks = audioVideo.getAudioTracks();
  2715. if(audioTracks.length) {
  2716. audioStream = new webkitMediaStream();
  2717. for (var i = 0; i < audioTracks.length; i++) {
  2718. audioStream.addTrack(audioTracks[i]);
  2719. }
  2720. }
  2721. var videoTracks = audioVideo.getVideoTracks();
  2722. if(videoTracks.length) {
  2723. videoStream = new webkitMediaStream();
  2724. for (var j = 0; j < videoTracks.length; j++) {
  2725. videoStream.addTrack(videoTracks[j]);
  2726. }
  2727. }
  2728. }
  2729. if (streams && streams.desktopStream)
  2730. desktopStream = streams.desktopStream;
  2731. }
  2732. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  2733. if (streams && streams.audio)
  2734. audioStream = streams.audio;
  2735. if (streams && streams.video)
  2736. videoStream = streams.video;
  2737. if(streams && streams.desktop)
  2738. desktopStream = streams.desktop;
  2739. }
  2740. if (desktopStream)
  2741. res.push({stream: desktopStream,
  2742. type: "video", videoType: "desktop"});
  2743. if(audioStream)
  2744. res.push({stream: audioStream, type: "audio", videoType: null});
  2745. if(videoStream)
  2746. res.push({stream: videoStream, type: "video", videoType: "camera",
  2747. resolution: resolution});
  2748. return res;
  2749. }
  2750. //Options parameter is to pass config options. Currently uses only "useIPv6".
  2751. var RTCUtils = {
  2752. init: function (options) {
  2753. return new Promise(function(resolve, reject) {
  2754. if (RTCBrowserType.isFirefox()) {
  2755. var FFversion = RTCBrowserType.getFirefoxVersion();
  2756. if (FFversion < 40) {
  2757. logger.error(
  2758. "Firefox version too old: " + FFversion +
  2759. ". Required >= 40.");
  2760. reject(new Error("Firefox version too old: " + FFversion +
  2761. ". Required >= 40."));
  2762. return;
  2763. }
  2764. this.peerconnection = mozRTCPeerConnection;
  2765. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  2766. this.enumerateDevices = wrapEnumerateDevices(
  2767. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2768. );
  2769. this.pc_constraints = {};
  2770. this.attachMediaStream = function (element, stream) {
  2771. // srcObject is being standardized and FF will eventually
  2772. // support that unprefixed. FF also supports the
  2773. // "element.src = URL.createObjectURL(...)" combo, but that
  2774. // will be deprecated in favour of srcObject.
  2775. //
  2776. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  2777. // https://github.com/webrtc/samples/issues/302
  2778. if (!element[0])
  2779. return;
  2780. element[0].mozSrcObject = stream;
  2781. element[0].play();
  2782. };
  2783. this.getStreamID = function (stream) {
  2784. var id = stream.id;
  2785. if (!id) {
  2786. var tracks = stream.getVideoTracks();
  2787. if (!tracks || tracks.length === 0) {
  2788. tracks = stream.getAudioTracks();
  2789. }
  2790. id = tracks[0].id;
  2791. }
  2792. return SDPUtil.filter_special_chars(id);
  2793. };
  2794. this.getVideoSrc = function (element) {
  2795. if (!element)
  2796. return null;
  2797. return element.mozSrcObject;
  2798. };
  2799. this.setVideoSrc = function (element, src) {
  2800. if (element)
  2801. element.mozSrcObject = src;
  2802. };
  2803. RTCSessionDescription = mozRTCSessionDescription;
  2804. RTCIceCandidate = mozRTCIceCandidate;
  2805. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  2806. this.peerconnection = webkitRTCPeerConnection;
  2807. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2808. if (navigator.mediaDevices) {
  2809. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  2810. this.enumerateDevices = wrapEnumerateDevices(
  2811. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2812. );
  2813. } else {
  2814. this.getUserMedia = getUserMedia;
  2815. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2816. }
  2817. this.attachMediaStream = function (element, stream) {
  2818. // saves the created url for the stream, so we can reuse it
  2819. // and not keep creating urls
  2820. if (!stream.jitsiObjectURL) {
  2821. stream.jitsiObjectURL
  2822. = webkitURL.createObjectURL(stream);
  2823. }
  2824. element.attr('src', stream.jitsiObjectURL);
  2825. };
  2826. this.getStreamID = function (stream) {
  2827. // streams from FF endpoints have the characters '{' and '}'
  2828. // that make jQuery choke.
  2829. return SDPUtil.filter_special_chars(stream.id);
  2830. };
  2831. this.getVideoSrc = function (element) {
  2832. if (!element)
  2833. return null;
  2834. return element.getAttribute("src");
  2835. };
  2836. this.setVideoSrc = function (element, src) {
  2837. if (element)
  2838. element.setAttribute("src", src);
  2839. };
  2840. // DTLS should now be enabled by default but..
  2841. this.pc_constraints = {'optional': [
  2842. {'DtlsSrtpKeyAgreement': 'true'}
  2843. ]};
  2844. if (options.useIPv6) {
  2845. // https://code.google.com/p/webrtc/issues/detail?id=2828
  2846. this.pc_constraints.optional.push({googIPv6: true});
  2847. }
  2848. if (RTCBrowserType.isAndroid()) {
  2849. this.pc_constraints = {}; // disable DTLS on Android
  2850. }
  2851. if (!webkitMediaStream.prototype.getVideoTracks) {
  2852. webkitMediaStream.prototype.getVideoTracks = function () {
  2853. return this.videoTracks;
  2854. };
  2855. }
  2856. if (!webkitMediaStream.prototype.getAudioTracks) {
  2857. webkitMediaStream.prototype.getAudioTracks = function () {
  2858. return this.audioTracks;
  2859. };
  2860. }
  2861. }
  2862. // Detect IE/Safari
  2863. else if (RTCBrowserType.isTemasysPluginUsed()) {
  2864. //AdapterJS.WebRTCPlugin.setLogLevel(
  2865. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  2866. var self = this;
  2867. AdapterJS.webRTCReady(function (isPlugin) {
  2868. self.peerconnection = RTCPeerConnection;
  2869. self.getUserMedia = window.getUserMedia;
  2870. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2871. self.attachMediaStream = function (elSel, stream) {
  2872. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  2873. return;
  2874. }
  2875. attachMediaStream(elSel[0], stream);
  2876. };
  2877. self.getStreamID = function (stream) {
  2878. var id = SDPUtil.filter_special_chars(stream.label);
  2879. return id;
  2880. };
  2881. self.getVideoSrc = function (element) {
  2882. if (!element) {
  2883. logger.warn("Attempt to get video SRC of null element");
  2884. return null;
  2885. }
  2886. var children = element.children;
  2887. for (var i = 0; i !== children.length; ++i) {
  2888. if (children[i].name === 'streamId') {
  2889. return children[i].value;
  2890. }
  2891. }
  2892. //logger.info(element.id + " SRC: " + src);
  2893. return null;
  2894. };
  2895. self.setVideoSrc = function (element, src) {
  2896. //logger.info("Set video src: ", element, src);
  2897. if (!src) {
  2898. logger.warn("Not attaching video stream, 'src' is null");
  2899. return;
  2900. }
  2901. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2902. var stream = AdapterJS.WebRTCPlugin.plugin
  2903. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  2904. attachMediaStream(element, stream);
  2905. };
  2906. onReady(options, self.getUserMediaWithConstraints);
  2907. resolve();
  2908. });
  2909. } else {
  2910. try {
  2911. logger.error('Browser does not appear to be WebRTC-capable');
  2912. } catch (e) {
  2913. }
  2914. reject('Browser does not appear to be WebRTC-capable');
  2915. return;
  2916. }
  2917. // Call onReady() if Temasys plugin is not used
  2918. if (!RTCBrowserType.isTemasysPluginUsed()) {
  2919. onReady(options, this.getUserMediaWithConstraints);
  2920. resolve();
  2921. }
  2922. }.bind(this));
  2923. },
  2924. /**
  2925. * @param {string[]} um required user media types
  2926. * @param {function} success_callback
  2927. * @param {Function} failure_callback
  2928. * @param {Object} [options] optional parameters
  2929. * @param {string} options.resolution
  2930. * @param {number} options.bandwidth
  2931. * @param {number} options.fps
  2932. * @param {string} options.desktopStream
  2933. * @param {string} options.cameraDeviceId
  2934. * @param {string} options.micDeviceId
  2935. **/
  2936. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  2937. options = options || {};
  2938. var resolution = options.resolution;
  2939. var constraints = getConstraints(um, options);
  2940. logger.info("Get media constraints", constraints);
  2941. try {
  2942. this.getUserMedia(constraints,
  2943. function (stream) {
  2944. logger.log('onUserMediaSuccess');
  2945. setAvailableDevices(um, true);
  2946. success_callback(stream);
  2947. },
  2948. function (error) {
  2949. setAvailableDevices(um, false);
  2950. logger.warn('Failed to get access to local media. Error ',
  2951. error, constraints);
  2952. if (failure_callback) {
  2953. failure_callback(error, resolution);
  2954. }
  2955. });
  2956. } catch (e) {
  2957. logger.error('GUM failed: ', e);
  2958. if (failure_callback) {
  2959. failure_callback(e);
  2960. }
  2961. }
  2962. },
  2963. /**
  2964. * Creates the local MediaStreams.
  2965. * @param {Object} [options] optional parameters
  2966. * @param {Array} options.devices the devices that will be requested
  2967. * @param {string} options.resolution resolution constraints
  2968. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2969. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2970. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2971. * @param {string} options.cameraDeviceId
  2972. * @param {string} options.micDeviceId
  2973. * @returns {*} Promise object that will receive the new JitsiTracks
  2974. */
  2975. obtainAudioAndVideoPermissions: function (options) {
  2976. var self = this;
  2977. options = options || {};
  2978. return new Promise(function (resolve, reject) {
  2979. var successCallback = function (stream) {
  2980. resolve(handleLocalStream(stream, options.resolution));
  2981. };
  2982. options.devices = options.devices || ['audio', 'video'];
  2983. if(!screenObtainer.isSupported()
  2984. && options.devices.indexOf("desktop") !== -1){
  2985. reject(new Error("Desktop sharing is not supported!"));
  2986. }
  2987. if (RTCBrowserType.isFirefox() ||
  2988. RTCBrowserType.isTemasysPluginUsed()) {
  2989. var GUM = function (device, s, e) {
  2990. this.getUserMediaWithConstraints(device, s, e, options);
  2991. };
  2992. var deviceGUM = {
  2993. "audio": GUM.bind(self, ["audio"]),
  2994. "video": GUM.bind(self, ["video"])
  2995. };
  2996. if(screenObtainer.isSupported()){
  2997. deviceGUM["desktop"] = screenObtainer.obtainStream.bind(
  2998. screenObtainer);
  2999. }
  3000. // With FF/IE we can't split the stream into audio and video because FF
  3001. // doesn't support media stream constructors. So, we need to get the
  3002. // audio stream separately from the video stream using two distinct GUM
  3003. // calls. Not very user friendly :-( but we don't have many other
  3004. // options neither.
  3005. //
  3006. // Note that we pack those 2 streams in a single object and pass it to
  3007. // the successCallback method.
  3008. obtainDevices({
  3009. devices: options.devices,
  3010. streams: [],
  3011. successCallback: successCallback,
  3012. errorCallback: reject,
  3013. deviceGUM: deviceGUM
  3014. });
  3015. } else {
  3016. var hasDesktop = options.devices.indexOf('desktop') > -1;
  3017. if (hasDesktop) {
  3018. options.devices.splice(options.devices.indexOf("desktop"), 1);
  3019. }
  3020. options.resolution = options.resolution || '360';
  3021. if(options.devices.length) {
  3022. this.getUserMediaWithConstraints(
  3023. options.devices,
  3024. function (stream) {
  3025. if((options.devices.indexOf("audio") !== -1 &&
  3026. !stream.getAudioTracks().length) ||
  3027. (options.devices.indexOf("video") !== -1 &&
  3028. !stream.getVideoTracks().length))
  3029. {
  3030. self.stopMediaStream(stream);
  3031. reject(JitsiTrackErrors.parseError(
  3032. new Error("Unable to get the audio and " +
  3033. "video tracks."),
  3034. options.devices));
  3035. return;
  3036. }
  3037. if(hasDesktop) {
  3038. screenObtainer.obtainStream(
  3039. function (desktopStream) {
  3040. successCallback({audioVideo: stream,
  3041. desktopStream: desktopStream});
  3042. }, function (error) {
  3043. self.stopMediaStream(stream);
  3044. reject(
  3045. JitsiTrackErrors.parseError(error,
  3046. options.devices));
  3047. });
  3048. } else {
  3049. successCallback({audioVideo: stream});
  3050. }
  3051. },
  3052. function (error) {
  3053. reject(JitsiTrackErrors.parseError(error,
  3054. options.devices));
  3055. },
  3056. options);
  3057. } else if (hasDesktop) {
  3058. screenObtainer.obtainStream(
  3059. function (stream) {
  3060. successCallback({desktopStream: stream});
  3061. }, function (error) {
  3062. reject(
  3063. JitsiTrackErrors.parseError(error,
  3064. ["desktop"]));
  3065. });
  3066. }
  3067. }
  3068. }.bind(this));
  3069. },
  3070. addListener: function (eventType, listener) {
  3071. eventEmitter.on(eventType, listener);
  3072. },
  3073. removeListener: function (eventType, listener) {
  3074. eventEmitter.removeListener(eventType, listener);
  3075. },
  3076. getDeviceAvailability: function () {
  3077. return devices;
  3078. },
  3079. isRTCReady: function () {
  3080. return rtcReady;
  3081. },
  3082. /**
  3083. * Checks if its possible to enumerate available cameras/micropones.
  3084. * @returns {boolean} true if available, false otherwise.
  3085. */
  3086. isDeviceListAvailable: function () {
  3087. var isEnumerateDevicesAvailable = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  3088. if (isEnumerateDevicesAvailable) {
  3089. return true;
  3090. }
  3091. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  3092. },
  3093. /**
  3094. * Returns true if changing the camera / microphone device is supported and
  3095. * false if not.
  3096. */
  3097. isDeviceChangeAvailable: function () {
  3098. if(RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  3099. RTCBrowserType.isTemasysPluginUsed())
  3100. return true;
  3101. return false;
  3102. },
  3103. /**
  3104. * A method to handle stopping of the stream.
  3105. * One point to handle the differences in various implementations.
  3106. * @param mediaStream MediaStream object to stop.
  3107. */
  3108. stopMediaStream: function (mediaStream) {
  3109. mediaStream.getTracks().forEach(function (track) {
  3110. // stop() not supported with IE
  3111. if (track.stop) {
  3112. track.stop();
  3113. }
  3114. });
  3115. // leave stop for implementation still using it
  3116. if (mediaStream.stop) {
  3117. mediaStream.stop();
  3118. }
  3119. // if we have done createObjectURL, lets clean it
  3120. if (mediaStream.jitsiObjectURL) {
  3121. webkitURL.revokeObjectURL(mediaStream.jitsiObjectURL);
  3122. }
  3123. },
  3124. /**
  3125. * Returns whether the desktop sharing is enabled or not.
  3126. * @returns {boolean}
  3127. */
  3128. isDesktopSharingEnabled: function () {
  3129. return screenObtainer.isSupported();
  3130. }
  3131. };
  3132. module.exports = RTCUtils;
  3133. }).call(this,"/modules/RTC/RTCUtils.js")
  3134. },{"../../JitsiTrackErrors":9,"../../service/RTC/RTCEvents":79,"../../service/RTC/Resolutions":80,"../xmpp/SDPUtil":31,"./RTCBrowserType":17,"./ScreenObtainer":19,"./adapter.screenshare":20,"events":43,"jitsi-meet-logger":47}],19:[function(require,module,exports){
  3135. (function (__filename){
  3136. /* global chrome, $, alert */
  3137. /* jshint -W003 */
  3138. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3139. var RTCBrowserType = require("./RTCBrowserType");
  3140. var AdapterJS = require("./adapter.screenshare");
  3141. var DesktopSharingEventTypes
  3142. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  3143. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  3144. /**
  3145. * Indicates whether the Chrome desktop sharing extension is installed.
  3146. * @type {boolean}
  3147. */
  3148. var chromeExtInstalled = false;
  3149. /**
  3150. * Indicates whether an update of the Chrome desktop sharing extension is
  3151. * required.
  3152. * @type {boolean}
  3153. */
  3154. var chromeExtUpdateRequired = false;
  3155. /**
  3156. * Whether the jidesha extension for firefox is installed for the domain on
  3157. * which we are running. Null designates an unknown value.
  3158. * @type {null}
  3159. */
  3160. var firefoxExtInstalled = null;
  3161. /**
  3162. * If set to true, detection of an installed firefox extension will be started
  3163. * again the next time obtainScreenOnFirefox is called (e.g. next time the
  3164. * user tries to enable screen sharing).
  3165. */
  3166. var reDetectFirefoxExtension = false;
  3167. var GUM = null;
  3168. /**
  3169. * Handles obtaining a stream from a screen capture on different browsers.
  3170. */
  3171. var ScreenObtainer = {
  3172. obtainStream: null,
  3173. /**
  3174. * Initializes the function used to obtain a screen capture
  3175. * (this.obtainStream).
  3176. *
  3177. * If the browser is Chrome, it uses the value of
  3178. * 'options.desktopSharingChromeMethod' (or 'options.desktopSharing') to
  3179. * decide whether to use the a Chrome extension (if the value is 'ext'),
  3180. * use the "screen" media source (if the value is 'webrtc'),
  3181. * or disable screen capture (if the value is other).
  3182. * Note that for the "screen" media source to work the
  3183. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be set.
  3184. */
  3185. init: function(options, gum) {
  3186. var obtainDesktopStream = null;
  3187. this.options = options = options || {};
  3188. GUM = gum;
  3189. if (RTCBrowserType.isFirefox())
  3190. initFirefoxExtensionDetection(options);
  3191. // TODO remove this, options.desktopSharing is deprecated.
  3192. var chromeMethod =
  3193. (options.desktopSharingChromeMethod || options.desktopSharing);
  3194. if (RTCBrowserType.isTemasysPluginUsed()) {
  3195. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  3196. logger.info("Screensharing not supported by this plugin " +
  3197. "version");
  3198. } else if(!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3199. logger.info(
  3200. "Screensharing not available with Temasys plugin on" +
  3201. " this site");
  3202. } else {
  3203. obtainDesktopStream = obtainWebRTCScreen;
  3204. logger.info("Using Temasys plugin for desktop sharing");
  3205. }
  3206. } else if (RTCBrowserType.isChrome()) {
  3207. if (chromeMethod == "ext") {
  3208. if (RTCBrowserType.getChromeVersion() >= 34) {
  3209. obtainDesktopStream =
  3210. this.obtainScreenFromExtension;
  3211. logger.info("Using Chrome extension for desktop sharing");
  3212. initChromeExtension(options);
  3213. } else {
  3214. logger.info("Chrome extension not supported until ver 34");
  3215. }
  3216. } else if (chromeMethod == "webrtc") {
  3217. obtainDesktopStream = obtainWebRTCScreen;
  3218. logger.info("Using Chrome WebRTC for desktop sharing");
  3219. }
  3220. } else if (RTCBrowserType.isFirefox()) {
  3221. if (options.desktopSharingFirefoxDisabled) {
  3222. obtainDesktopStream = null;
  3223. } else if (window.location.protocol === "http:"){
  3224. logger.log("Screen sharing is not supported over HTTP. " +
  3225. "Use of HTTPS is required.");
  3226. obtainDesktopStream = null;
  3227. } else {
  3228. obtainDesktopStream = this.obtainScreenOnFirefox;
  3229. }
  3230. }
  3231. if (!obtainDesktopStream) {
  3232. logger.info("Desktop sharing disabled");
  3233. }
  3234. this.obtainStream = obtainDesktopStream;
  3235. },
  3236. /**
  3237. * Checks whether obtaining a screen capture is supported in the current
  3238. * environment.
  3239. * @returns {boolean}
  3240. */
  3241. isSupported: function() {
  3242. return !!this.obtainStream;
  3243. },
  3244. /**
  3245. * Obtains a screen capture stream on Firefox.
  3246. * @param callback
  3247. * @param errorCallback
  3248. */
  3249. obtainScreenOnFirefox:
  3250. function (callback, errorCallback) {
  3251. var self = this;
  3252. var extensionRequired = false;
  3253. if (this.options.desktopSharingFirefoxMaxVersionExtRequired === -1 ||
  3254. (this.options.desktopSharingFirefoxMaxVersionExtRequired >= 0 &&
  3255. RTCBrowserType.getFirefoxVersion() <=
  3256. this.options.desktopSharingFirefoxMaxVersionExtRequired)) {
  3257. extensionRequired = true;
  3258. logger.log("Jidesha extension required on firefox version " +
  3259. RTCBrowserType.getFirefoxVersion());
  3260. }
  3261. if (!extensionRequired || firefoxExtInstalled === true) {
  3262. obtainWebRTCScreen(callback, errorCallback);
  3263. return;
  3264. }
  3265. if (reDetectFirefoxExtension) {
  3266. reDetectFirefoxExtension = false;
  3267. initFirefoxExtensionDetection(this.options);
  3268. }
  3269. // Give it some (more) time to initialize, and assume lack of
  3270. // extension if it hasn't.
  3271. if (firefoxExtInstalled === null) {
  3272. window.setTimeout(
  3273. function() {
  3274. if (firefoxExtInstalled === null)
  3275. firefoxExtInstalled = false;
  3276. self.obtainScreenOnFirefox(callback, errorCallback);
  3277. },
  3278. 300
  3279. );
  3280. logger.log("Waiting for detection of jidesha on firefox to " +
  3281. "finish.");
  3282. return;
  3283. }
  3284. // We need an extension and it isn't installed.
  3285. // Make sure we check for the extension when the user clicks again.
  3286. firefoxExtInstalled = null;
  3287. reDetectFirefoxExtension = true;
  3288. // Make sure desktopsharing knows that we failed, so that it doesn't get
  3289. // stuck in 'switching' mode.
  3290. errorCallback({
  3291. type: "jitsiError",
  3292. errorObject: JitsiTrackErrors.FIREFOX_EXTENSION_NEEDED
  3293. });
  3294. },
  3295. /**
  3296. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  3297. * 'desktop' stream for returned stream token.
  3298. */
  3299. obtainScreenFromExtension: function (streamCallback, failCallback) {
  3300. var self = this;
  3301. if (chromeExtInstalled) {
  3302. doGetStreamFromExtension(this.options, streamCallback,
  3303. failCallback);
  3304. } else {
  3305. if (chromeExtUpdateRequired) {
  3306. alert(
  3307. 'Jitsi Desktop Streamer requires update. ' +
  3308. 'Changes will take effect after next Chrome restart.');
  3309. }
  3310. chrome.webstore.install(
  3311. getWebStoreInstallUrl(this.options),
  3312. function (arg) {
  3313. logger.log("Extension installed successfully", arg);
  3314. chromeExtInstalled = true;
  3315. // We need to give a moment for the endpoint to become
  3316. // available
  3317. window.setTimeout(function () {
  3318. doGetStreamFromExtension(self.options, streamCallback,
  3319. failCallback);
  3320. }, 500);
  3321. },
  3322. function (arg) {
  3323. logger.log("Failed to install the extension", arg);
  3324. failCallback(arg);
  3325. }
  3326. );
  3327. }
  3328. }
  3329. };
  3330. /**
  3331. * Obtains a desktop stream using getUserMedia.
  3332. * For this to work on Chrome, the
  3333. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  3334. *
  3335. * On firefox, the document's domain must be white-listed in the
  3336. * 'media.getusermedia.screensharing.allowed_domains' preference in
  3337. * 'about:config'.
  3338. */
  3339. function obtainWebRTCScreen(streamCallback, failCallback) {
  3340. GUM(
  3341. ['screen'],
  3342. streamCallback,
  3343. failCallback
  3344. );
  3345. }
  3346. /**
  3347. * Constructs inline install URL for Chrome desktop streaming extension.
  3348. * The 'chromeExtensionId' must be defined in options parameter.
  3349. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3350. * @returns {string}
  3351. */
  3352. function getWebStoreInstallUrl(options)
  3353. {
  3354. //TODO remove chromeExtensionId (deprecated)
  3355. return "https://chrome.google.com/webstore/detail/" +
  3356. (options.desktopSharingChromeExtId || options.chromeExtensionId);
  3357. }
  3358. /**
  3359. * Checks whether an update of the Chrome extension is required.
  3360. * @param minVersion minimal required version
  3361. * @param extVersion current extension version
  3362. * @returns {boolean}
  3363. */
  3364. function isUpdateRequired(minVersion, extVersion) {
  3365. try {
  3366. var s1 = minVersion.split('.');
  3367. var s2 = extVersion.split('.');
  3368. var len = Math.max(s1.length, s2.length);
  3369. for (var i = 0; i < len; i++) {
  3370. var n1 = 0,
  3371. n2 = 0;
  3372. if (i < s1.length)
  3373. n1 = parseInt(s1[i]);
  3374. if (i < s2.length)
  3375. n2 = parseInt(s2[i]);
  3376. if (isNaN(n1) || isNaN(n2)) {
  3377. return true;
  3378. } else if (n1 !== n2) {
  3379. return n1 > n2;
  3380. }
  3381. }
  3382. // will happen if both versions have identical numbers in
  3383. // their components (even if one of them is longer, has more components)
  3384. return false;
  3385. }
  3386. catch (e) {
  3387. logger.error("Failed to parse extension version", e);
  3388. return true;
  3389. }
  3390. }
  3391. function checkChromeExtInstalled(callback, options) {
  3392. if (!chrome || !chrome.runtime) {
  3393. // No API, so no extension for sure
  3394. callback(false, false);
  3395. return;
  3396. }
  3397. chrome.runtime.sendMessage(
  3398. //TODO: remove chromeExtensionId (deprecated)
  3399. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3400. { getVersion: true },
  3401. function (response) {
  3402. if (!response || !response.version) {
  3403. // Communication failure - assume that no endpoint exists
  3404. logger.warn(
  3405. "Extension not installed?: ", chrome.runtime.lastError);
  3406. callback(false, false);
  3407. return;
  3408. }
  3409. // Check installed extension version
  3410. var extVersion = response.version;
  3411. logger.log('Extension version is: ' + extVersion);
  3412. //TODO: remove minChromeExtVersion (deprecated)
  3413. var updateRequired
  3414. = isUpdateRequired(
  3415. (options.desktopSharingChromeMinExtVersion ||
  3416. options.minChromeExtVersion),
  3417. extVersion);
  3418. callback(!updateRequired, updateRequired);
  3419. }
  3420. );
  3421. }
  3422. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  3423. // Sends 'getStream' msg to the extension.
  3424. // Extension id must be defined in the config.
  3425. chrome.runtime.sendMessage(
  3426. //TODO: remove chromeExtensionId (deprecated)
  3427. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3428. {
  3429. getStream: true,
  3430. //TODO: remove desktopSharingSources (deprecated).
  3431. sources: (options.desktopSharingChromeSources ||
  3432. options.desktopSharingSources)
  3433. },
  3434. function (response) {
  3435. if (!response) {
  3436. failCallback(chrome.runtime.lastError);
  3437. return;
  3438. }
  3439. logger.log("Response from extension: " + response);
  3440. if (response.streamId) {
  3441. GUM(
  3442. ['desktop'],
  3443. function (stream) {
  3444. streamCallback(stream);
  3445. },
  3446. failCallback,
  3447. {desktopStream: response.streamId});
  3448. } else {
  3449. failCallback("Extension failed to get the stream");
  3450. }
  3451. }
  3452. );
  3453. }
  3454. /**
  3455. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3456. * config.js to support inline installs. Host site must be selected as main
  3457. * website of published extension.
  3458. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3459. */
  3460. function initInlineInstalls(options)
  3461. {
  3462. $("link[rel=chrome-webstore-item]").attr("href",
  3463. getWebStoreInstallUrl(options));
  3464. }
  3465. function initChromeExtension(options) {
  3466. // Initialize Chrome extension inline installs
  3467. initInlineInstalls(options);
  3468. // Check if extension is installed
  3469. checkChromeExtInstalled(function (installed, updateRequired) {
  3470. chromeExtInstalled = installed;
  3471. chromeExtUpdateRequired = updateRequired;
  3472. logger.info(
  3473. "Chrome extension installed: " + chromeExtInstalled +
  3474. " updateRequired: " + chromeExtUpdateRequired);
  3475. }, options);
  3476. }
  3477. /**
  3478. * Starts the detection of an installed jidesha extension for firefox.
  3479. * @param options supports "desktopSharingFirefoxDisabled",
  3480. * "desktopSharingFirefoxExtId" and "chromeExtensionId"
  3481. */
  3482. function initFirefoxExtensionDetection(options) {
  3483. if (options.desktopSharingFirefoxDisabled) {
  3484. return;
  3485. }
  3486. if (firefoxExtInstalled === false || firefoxExtInstalled === true)
  3487. return;
  3488. if (!options.desktopSharingFirefoxExtId) {
  3489. firefoxExtInstalled = false;
  3490. return;
  3491. }
  3492. var img = document.createElement('img');
  3493. img.onload = function(){
  3494. logger.log("Detected firefox screen sharing extension.");
  3495. firefoxExtInstalled = true;
  3496. };
  3497. img.onerror = function(){
  3498. logger.log("Detected lack of firefox screen sharing extension.");
  3499. firefoxExtInstalled = false;
  3500. };
  3501. // The jidesha extension exposes an empty image file under the url:
  3502. // "chrome://EXT_ID/content/DOMAIN.png"
  3503. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  3504. // DOMAIN is a domain whitelisted by the extension.
  3505. var src = "chrome://" +
  3506. (options.desktopSharingFirefoxExtId.replace('@', '.')) +
  3507. "/content/" + document.location.hostname + ".png";
  3508. img.setAttribute('src', src);
  3509. }
  3510. module.exports = ScreenObtainer;
  3511. }).call(this,"/modules/RTC/ScreenObtainer.js")
  3512. },{"../../JitsiTrackErrors":9,"../../service/desktopsharing/DesktopSharingEventTypes":82,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":47}],20:[function(require,module,exports){
  3513. (function (__filename){
  3514. /*! adapterjs - v0.12.3 - 2015-11-16 */
  3515. var console = require("jitsi-meet-logger").getLogger(__filename);
  3516. // Adapter's interface.
  3517. var AdapterJS = AdapterJS || {};
  3518. // Browserify compatibility
  3519. if(typeof exports !== 'undefined') {
  3520. module.exports = AdapterJS;
  3521. }
  3522. AdapterJS.options = AdapterJS.options || {};
  3523. // uncomment to get virtual webcams
  3524. // AdapterJS.options.getAllCams = true;
  3525. // uncomment to prevent the install prompt when the plugin in not yet installed
  3526. // AdapterJS.options.hidePluginInstallPrompt = true;
  3527. // AdapterJS version
  3528. AdapterJS.VERSION = '0.12.3';
  3529. // This function will be called when the WebRTC API is ready to be used
  3530. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  3531. // the plugin
  3532. // You may Override this function to synchronise the start of your application
  3533. // with the WebRTC API being ready.
  3534. // If you decide not to override use this synchronisation, it may result in
  3535. // an extensive CPU usage on the plugin start (once per tab loaded)
  3536. // Params:
  3537. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  3538. //
  3539. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  3540. // The WebRTC API is ready.
  3541. // Override me and do whatever you want here
  3542. };
  3543. // Sets a callback function to be called when the WebRTC interface is ready.
  3544. // The first argument is the function to callback.\
  3545. // Throws an error if the first argument is not a function
  3546. AdapterJS.webRTCReady = function (callback) {
  3547. if (typeof callback !== 'function') {
  3548. throw new Error('Callback provided is not a function');
  3549. }
  3550. if (true === AdapterJS.onwebrtcreadyDone) {
  3551. // All WebRTC interfaces are ready, just call the callback
  3552. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  3553. } else {
  3554. // will be triggered automatically when your browser/plugin is ready.
  3555. AdapterJS.onwebrtcready = callback;
  3556. }
  3557. };
  3558. // Plugin namespace
  3559. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  3560. // The object to store plugin information
  3561. AdapterJS.WebRTCPlugin.pluginInfo = {
  3562. prefix : 'Tem',
  3563. plugName : 'TemWebRTCPlugin',
  3564. pluginId : 'plugin0',
  3565. type : 'application/x-temwebrtcplugin',
  3566. onload : '__TemWebRTCReady0',
  3567. portalLink : 'http://skylink.io/plugin/',
  3568. downloadLink : null, //set below
  3569. companyName: 'Temasys'
  3570. };
  3571. if(!!navigator.platform.match(/^Mac/i)) {
  3572. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  3573. }
  3574. else if(!!navigator.platform.match(/^Win/i)) {
  3575. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  3576. }
  3577. AdapterJS.WebRTCPlugin.TAGS = {
  3578. NONE : 'none',
  3579. AUDIO : 'audio',
  3580. VIDEO : 'video'
  3581. };
  3582. // Unique identifier of each opened page
  3583. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  3584. // Use this whenever you want to call the plugin.
  3585. AdapterJS.WebRTCPlugin.plugin = null;
  3586. // Set log level for the plugin once it is ready.
  3587. // The different values are
  3588. // This is an asynchronous function that will run when the plugin is ready
  3589. AdapterJS.WebRTCPlugin.setLogLevel = null;
  3590. // Defines webrtc's JS interface according to the plugin's implementation.
  3591. // Define plugin Browsers as WebRTC Interface.
  3592. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  3593. // This function detects whether or not a plugin is installed.
  3594. // Checks if Not IE (firefox, for example), else if it's IE,
  3595. // we're running IE and do something. If not it is not supported.
  3596. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  3597. // Lets adapter.js wait until the the document is ready before injecting the plugin
  3598. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  3599. // Inject the HTML DOM object element into the page.
  3600. AdapterJS.WebRTCPlugin.injectPlugin = null;
  3601. // States of readiness that the plugin goes through when
  3602. // being injected and stated
  3603. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  3604. NONE : 0, // no plugin use
  3605. INITIALIZING : 1, // Detected need for plugin
  3606. INJECTING : 2, // Injecting plugin
  3607. INJECTED: 3, // Plugin element injected but not usable yet
  3608. READY: 4 // Plugin ready to be used
  3609. };
  3610. // Current state of the plugin. You cannot use the plugin before this is
  3611. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  3612. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  3613. // True is AdapterJS.onwebrtcready was already called, false otherwise
  3614. // Used to make sure AdapterJS.onwebrtcready is only called once
  3615. AdapterJS.onwebrtcreadyDone = false;
  3616. // Log levels for the plugin.
  3617. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  3618. /*
  3619. Log outputs are prefixed in some cases.
  3620. INFO: Information reported by the plugin.
  3621. ERROR: Errors originating from within the plugin.
  3622. WEBRTC: Error originating from within the libWebRTC library
  3623. */
  3624. // From the least verbose to the most verbose
  3625. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  3626. NONE : 'NONE',
  3627. ERROR : 'ERROR',
  3628. WARNING : 'WARNING',
  3629. INFO: 'INFO',
  3630. VERBOSE: 'VERBOSE',
  3631. SENSITIVE: 'SENSITIVE'
  3632. };
  3633. // Does a waiting check before proceeding to load the plugin.
  3634. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  3635. // This methid will use an interval to wait for the plugin to be ready.
  3636. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  3637. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  3638. // This function will be called when plugin is ready. It sends necessary
  3639. // details to the plugin.
  3640. // The function will wait for the document to be ready and the set the
  3641. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  3642. // indicating that it can start being requested.
  3643. // This function is not in the IE/Safari condition brackets so that
  3644. // TemPluginLoaded function might be called on Chrome/Firefox.
  3645. // This function is the only private function that is not encapsulated to
  3646. // allow the plugin method to be called.
  3647. __TemWebRTCReady0 = function () {
  3648. if (document.readyState === 'complete') {
  3649. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3650. AdapterJS.maybeThroughWebRTCReady();
  3651. } else {
  3652. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  3653. if (document.readyState === 'complete') {
  3654. // TODO: update comments, we wait for the document to be ready
  3655. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  3656. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3657. AdapterJS.maybeThroughWebRTCReady();
  3658. }
  3659. }, 100);
  3660. }
  3661. };
  3662. AdapterJS.maybeThroughWebRTCReady = function() {
  3663. if (!AdapterJS.onwebrtcreadyDone) {
  3664. AdapterJS.onwebrtcreadyDone = true;
  3665. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  3666. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  3667. }
  3668. }
  3669. };
  3670. // Text namespace
  3671. AdapterJS.TEXT = {
  3672. PLUGIN: {
  3673. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  3674. 'to work on this browser.',
  3675. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  3676. BUTTON: 'Install Now'
  3677. },
  3678. REFRESH: {
  3679. REQUIRE_REFRESH: 'Please refresh page',
  3680. BUTTON: 'Refresh Page'
  3681. }
  3682. };
  3683. // The result of ice connection states.
  3684. // - starting: Ice connection is starting.
  3685. // - checking: Ice connection is checking.
  3686. // - connected Ice connection is connected.
  3687. // - completed Ice connection is connected.
  3688. // - done Ice connection has been completed.
  3689. // - disconnected Ice connection has been disconnected.
  3690. // - failed Ice connection has failed.
  3691. // - closed Ice connection is closed.
  3692. AdapterJS._iceConnectionStates = {
  3693. starting : 'starting',
  3694. checking : 'checking',
  3695. connected : 'connected',
  3696. completed : 'connected',
  3697. done : 'completed',
  3698. disconnected : 'disconnected',
  3699. failed : 'failed',
  3700. closed : 'closed'
  3701. };
  3702. //The IceConnection states that has been fired for each peer.
  3703. AdapterJS._iceConnectionFiredStates = [];
  3704. // Check if WebRTC Interface is defined.
  3705. AdapterJS.isDefined = null;
  3706. // This function helps to retrieve the webrtc detected browser information.
  3707. // This sets:
  3708. // - webrtcDetectedBrowser: The browser agent name.
  3709. // - webrtcDetectedVersion: The browser version.
  3710. // - webrtcDetectedType: The types of webRTC support.
  3711. // - 'moz': Mozilla implementation of webRTC.
  3712. // - 'webkit': WebKit implementation of webRTC.
  3713. // - 'plugin': Using the plugin implementation.
  3714. AdapterJS.parseWebrtcDetectedBrowser = function () {
  3715. var hasMatch, checkMatch = navigator.userAgent.match(
  3716. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  3717. if (/trident/i.test(checkMatch[1])) {
  3718. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  3719. webrtcDetectedBrowser = 'IE';
  3720. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  3721. } else if (checkMatch[1] === 'Chrome') {
  3722. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3723. if (hasMatch !== null) {
  3724. webrtcDetectedBrowser = 'opera';
  3725. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  3726. }
  3727. }
  3728. if (navigator.userAgent.indexOf('Safari')) {
  3729. if (typeof InstallTrigger !== 'undefined') {
  3730. webrtcDetectedBrowser = 'firefox';
  3731. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  3732. webrtcDetectedBrowser = 'IE';
  3733. } else if (
  3734. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  3735. webrtcDetectedBrowser = 'safari';
  3736. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  3737. webrtcDetectedBrowser = 'opera';
  3738. } else if (!!window.chrome) {
  3739. webrtcDetectedBrowser = 'chrome';
  3740. }
  3741. }
  3742. if (!webrtcDetectedBrowser) {
  3743. webrtcDetectedVersion = checkMatch[1];
  3744. }
  3745. if (!webrtcDetectedVersion) {
  3746. try {
  3747. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  3748. [navigator.appName, navigator.appVersion, '-?'];
  3749. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  3750. checkMatch.splice(1, 1, hasMatch[1]);
  3751. }
  3752. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  3753. } catch (error) { }
  3754. }
  3755. };
  3756. // To fix configuration as some browsers does not support
  3757. // the 'urls' attribute.
  3758. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  3759. if (pcConfig === null) {
  3760. return;
  3761. }
  3762. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  3763. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  3764. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  3765. delete pcConfig.iceServers[i].urls;
  3766. }
  3767. }
  3768. };
  3769. AdapterJS.addEvent = function(elem, evnt, func) {
  3770. if (elem.addEventListener) { // W3C DOM
  3771. elem.addEventListener(evnt, func, false);
  3772. } else if (elem.attachEvent) {// OLD IE DOM
  3773. elem.attachEvent('on'+evnt, func);
  3774. } else { // No much to do
  3775. elem[evnt] = func;
  3776. }
  3777. };
  3778. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  3779. // only inject once the page is ready
  3780. if (document.readyState !== 'complete') {
  3781. return;
  3782. }
  3783. var w = window;
  3784. var i = document.createElement('iframe');
  3785. i.style.position = 'fixed';
  3786. i.style.top = '-41px';
  3787. i.style.left = 0;
  3788. i.style.right = 0;
  3789. i.style.width = '100%';
  3790. i.style.height = '40px';
  3791. i.style.backgroundColor = '#ffffe1';
  3792. i.style.border = 'none';
  3793. i.style.borderBottom = '1px solid #888888';
  3794. i.style.zIndex = '9999999';
  3795. if(typeof i.style.webkitTransition === 'string') {
  3796. i.style.webkitTransition = 'all .5s ease-out';
  3797. } else if(typeof i.style.transition === 'string') {
  3798. i.style.transition = 'all .5s ease-out';
  3799. }
  3800. document.body.appendChild(i);
  3801. c = (i.contentWindow) ? i.contentWindow :
  3802. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  3803. c.document.open();
  3804. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  3805. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  3806. 'middle; cursor: default;">' + text + '</span>');
  3807. if(buttonText && buttonLink) {
  3808. c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
  3809. c.document.close();
  3810. // On click on okay
  3811. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  3812. if (!!displayRefreshBar) {
  3813. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  3814. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  3815. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  3816. }
  3817. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  3818. e.preventDefault();
  3819. try {
  3820. event.cancelBubble = true;
  3821. } catch(error) { }
  3822. var pluginInstallInterval = setInterval(function(){
  3823. if(! isIE) {
  3824. navigator.plugins.refresh(false);
  3825. }
  3826. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3827. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3828. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3829. function() { // plugin now installed
  3830. clearInterval(pluginInstallInterval);
  3831. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  3832. },
  3833. function() {
  3834. // still no plugin detected, nothing to do
  3835. });
  3836. } , 500);
  3837. });
  3838. // On click on Cancel
  3839. AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
  3840. w.document.body.removeChild(i);
  3841. });
  3842. } else {
  3843. c.document.close();
  3844. }
  3845. setTimeout(function() {
  3846. if(typeof i.style.webkitTransform === 'string') {
  3847. i.style.webkitTransform = 'translateY(40px)';
  3848. } else if(typeof i.style.transform === 'string') {
  3849. i.style.transform = 'translateY(40px)';
  3850. } else {
  3851. i.style.top = '0px';
  3852. }
  3853. }, 300);
  3854. };
  3855. // -----------------------------------------------------------
  3856. // Detected webrtc implementation. Types are:
  3857. // - 'moz': Mozilla implementation of webRTC.
  3858. // - 'webkit': WebKit implementation of webRTC.
  3859. // - 'plugin': Using the plugin implementation.
  3860. webrtcDetectedType = null;
  3861. // Detected webrtc datachannel support. Types are:
  3862. // - 'SCTP': SCTP datachannel support.
  3863. // - 'RTP': RTP datachannel support.
  3864. webrtcDetectedDCSupport = null;
  3865. // Set the settings for creating DataChannels, MediaStream for
  3866. // Cross-browser compability.
  3867. // - This is only for SCTP based support browsers.
  3868. // the 'urls' attribute.
  3869. checkMediaDataChannelSettings =
  3870. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  3871. if (typeof callback !== 'function') {
  3872. return;
  3873. }
  3874. var beOfferer = true;
  3875. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  3876. // Nightly version does not require MozDontOfferDataChannel for interop
  3877. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  3878. var isPeerFirefox = peerBrowserAgent === 'firefox';
  3879. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  3880. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  3881. // Resends an updated version of constraints for MozDataChannel to work
  3882. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  3883. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  3884. try {
  3885. delete constraints.mandatory.MozDontOfferDataChannel;
  3886. } catch (error) {
  3887. console.error('Failed deleting MozDontOfferDataChannel');
  3888. console.error(error);
  3889. }
  3890. } else if ((isLocalFirefox && !isPeerFirefox)) {
  3891. constraints.mandatory.MozDontOfferDataChannel = true;
  3892. }
  3893. if (!isLocalFirefox) {
  3894. // temporary measure to remove Moz* constraints in non Firefox browsers
  3895. for (var prop in constraints.mandatory) {
  3896. if (constraints.mandatory.hasOwnProperty(prop)) {
  3897. if (prop.indexOf('Moz') !== -1) {
  3898. delete constraints.mandatory[prop];
  3899. }
  3900. }
  3901. }
  3902. }
  3903. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  3904. // interopability of the media stream
  3905. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  3906. beOfferer = false;
  3907. }
  3908. callback(beOfferer, constraints);
  3909. };
  3910. // Handles the differences for all browsers ice connection state output.
  3911. // - Tested outcomes are:
  3912. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  3913. // - Chrome (answerer) : 'checking' > 'connected'
  3914. // - Firefox (offerer) : 'checking' > 'connected'
  3915. // - Firefox (answerer): 'checking' > 'connected'
  3916. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  3917. if (typeof callback !== 'function') {
  3918. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  3919. return;
  3920. }
  3921. peerId = (peerId) ? peerId : 'peer';
  3922. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  3923. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  3924. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  3925. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  3926. AdapterJS._iceConnectionFiredStates[peerId] = [];
  3927. }
  3928. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  3929. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  3930. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  3931. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  3932. setTimeout(function () {
  3933. AdapterJS._iceConnectionFiredStates[peerId]
  3934. .push(AdapterJS._iceConnectionStates.done);
  3935. callback(AdapterJS._iceConnectionStates.done);
  3936. }, 1000);
  3937. }
  3938. callback(iceConnectionState);
  3939. }
  3940. return;
  3941. };
  3942. // Firefox:
  3943. // - Creates iceServer from the url for Firefox.
  3944. // - Create iceServer with stun url.
  3945. // - Create iceServer with turn url.
  3946. // - Ignore the transport parameter from TURN url for FF version <=27.
  3947. // - Return null for createIceServer if transport=tcp.
  3948. // - FF 27 and above supports transport parameters in TURN url,
  3949. // - So passing in the full url to create iceServer.
  3950. // Chrome:
  3951. // - Creates iceServer from the url for Chrome M33 and earlier.
  3952. // - Create iceServer with stun url.
  3953. // - Chrome M28 & above uses below TURN format.
  3954. // Plugin:
  3955. // - Creates Ice Server for Plugin Browsers
  3956. // - If Stun - Create iceServer with stun url.
  3957. // - Else - Create iceServer with turn url
  3958. // - This is a WebRTC Function
  3959. createIceServer = null;
  3960. // Firefox:
  3961. // - Creates IceServers for Firefox
  3962. // - Use .url for FireFox.
  3963. // - Multiple Urls support
  3964. // Chrome:
  3965. // - Creates iceServers from the urls for Chrome M34 and above.
  3966. // - .urls is supported since Chrome M34.
  3967. // - Multiple Urls support
  3968. // Plugin:
  3969. // - Creates Ice Servers for Plugin Browsers
  3970. // - Multiple Urls support
  3971. // - This is a WebRTC Function
  3972. createIceServers = null;
  3973. //------------------------------------------------------------
  3974. //The RTCPeerConnection object.
  3975. RTCPeerConnection = null;
  3976. // Creates RTCSessionDescription object for Plugin Browsers
  3977. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  3978. RTCSessionDescription : null;
  3979. // Creates RTCIceCandidate object for Plugin Browsers
  3980. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  3981. RTCIceCandidate : null;
  3982. // Get UserMedia (only difference is the prefix).
  3983. // Code from Adam Barth.
  3984. getUserMedia = null;
  3985. // Attach a media stream to an element.
  3986. attachMediaStream = null;
  3987. // Re-attach a media stream to an element.
  3988. reattachMediaStream = null;
  3989. // Detected browser agent name. Types are:
  3990. // - 'firefox': Firefox browser.
  3991. // - 'chrome': Chrome browser.
  3992. // - 'opera': Opera browser.
  3993. // - 'safari': Safari browser.
  3994. // - 'IE' - Internet Explorer browser.
  3995. webrtcDetectedBrowser = null;
  3996. // Detected browser version.
  3997. webrtcDetectedVersion = null;
  3998. // Check for browser types and react accordingly
  3999. if (navigator.mozGetUserMedia) {
  4000. webrtcDetectedBrowser = 'firefox';
  4001. webrtcDetectedVersion = parseInt(navigator
  4002. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  4003. webrtcDetectedType = 'moz';
  4004. webrtcDetectedDCSupport = 'SCTP';
  4005. RTCPeerConnection = function (pcConfig, pcConstraints) {
  4006. AdapterJS.maybeFixConfiguration(pcConfig);
  4007. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  4008. };
  4009. // The RTCSessionDescription object.
  4010. RTCSessionDescription = mozRTCSessionDescription;
  4011. window.RTCSessionDescription = RTCSessionDescription;
  4012. // The RTCIceCandidate object.
  4013. RTCIceCandidate = mozRTCIceCandidate;
  4014. window.RTCIceCandidate = RTCIceCandidate;
  4015. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  4016. navigator.getUserMedia = window.getUserMedia;
  4017. // Shim for MediaStreamTrack.getSources.
  4018. MediaStreamTrack.getSources = function(successCb) {
  4019. setTimeout(function() {
  4020. var infos = [
  4021. { kind: 'audio', id: 'default', label:'', facing:'' },
  4022. { kind: 'video', id: 'default', label:'', facing:'' }
  4023. ];
  4024. successCb(infos);
  4025. }, 0);
  4026. };
  4027. createIceServer = function (url, username, password) {
  4028. var iceServer = null;
  4029. var url_parts = url.split(':');
  4030. if (url_parts[0].indexOf('stun') === 0) {
  4031. iceServer = { url : url };
  4032. } else if (url_parts[0].indexOf('turn') === 0) {
  4033. if (webrtcDetectedVersion < 27) {
  4034. var turn_url_parts = url.split('?');
  4035. if (turn_url_parts.length === 1 ||
  4036. turn_url_parts[1].indexOf('transport=udp') === 0) {
  4037. iceServer = {
  4038. url : turn_url_parts[0],
  4039. credential : password,
  4040. username : username
  4041. };
  4042. }
  4043. } else {
  4044. iceServer = {
  4045. url : url,
  4046. credential : password,
  4047. username : username
  4048. };
  4049. }
  4050. }
  4051. return iceServer;
  4052. };
  4053. createIceServers = function (urls, username, password) {
  4054. var iceServers = [];
  4055. for (var i = 0; i < urls.length; i++) {
  4056. var iceServer = createIceServer(urls[i], username, password);
  4057. if (iceServer !== null) {
  4058. iceServers.push(iceServer);
  4059. }
  4060. }
  4061. return iceServers;
  4062. };
  4063. attachMediaStream = function (element, stream) {
  4064. element.mozSrcObject = stream;
  4065. if (stream !== null)
  4066. element.play();
  4067. return element;
  4068. };
  4069. reattachMediaStream = function (to, from) {
  4070. to.mozSrcObject = from.mozSrcObject;
  4071. to.play();
  4072. return to;
  4073. };
  4074. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  4075. if (!callback) {
  4076. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  4077. ': 1 argument required, but only 0 present.');
  4078. }
  4079. return callback([]);
  4080. };
  4081. // Fake get{Video,Audio}Tracks
  4082. if (!MediaStream.prototype.getVideoTracks) {
  4083. MediaStream.prototype.getVideoTracks = function () {
  4084. return [];
  4085. };
  4086. }
  4087. if (!MediaStream.prototype.getAudioTracks) {
  4088. MediaStream.prototype.getAudioTracks = function () {
  4089. return [];
  4090. };
  4091. }
  4092. AdapterJS.maybeThroughWebRTCReady();
  4093. } else if (navigator.webkitGetUserMedia) {
  4094. webrtcDetectedBrowser = 'chrome';
  4095. webrtcDetectedType = 'webkit';
  4096. webrtcDetectedVersion = parseInt(navigator
  4097. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  4098. // check if browser is opera 20+
  4099. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  4100. if (checkIfOpera !== null) {
  4101. webrtcDetectedBrowser = 'opera';
  4102. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  4103. }
  4104. // check browser datachannel support
  4105. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  4106. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  4107. webrtcDetectedDCSupport = 'SCTP';
  4108. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  4109. webrtcDetectedVersion > 24) {
  4110. webrtcDetectedDCSupport = 'RTP';
  4111. } else {
  4112. webrtcDetectedDCSupport = '';
  4113. }
  4114. createIceServer = function (url, username, password) {
  4115. var iceServer = null;
  4116. var url_parts = url.split(':');
  4117. if (url_parts[0].indexOf('stun') === 0) {
  4118. iceServer = { 'url' : url };
  4119. } else if (url_parts[0].indexOf('turn') === 0) {
  4120. iceServer = {
  4121. 'url' : url,
  4122. 'credential' : password,
  4123. 'username' : username
  4124. };
  4125. }
  4126. return iceServer;
  4127. };
  4128. createIceServers = function (urls, username, password) {
  4129. var iceServers = [];
  4130. if (webrtcDetectedVersion >= 34) {
  4131. iceServers = {
  4132. 'urls' : urls,
  4133. 'credential' : password,
  4134. 'username' : username
  4135. };
  4136. } else {
  4137. for (var i = 0; i < urls.length; i++) {
  4138. var iceServer = createIceServer(urls[i], username, password);
  4139. if (iceServer !== null) {
  4140. iceServers.push(iceServer);
  4141. }
  4142. }
  4143. }
  4144. return iceServers;
  4145. };
  4146. RTCPeerConnection = function (pcConfig, pcConstraints) {
  4147. if (webrtcDetectedVersion < 34) {
  4148. AdapterJS.maybeFixConfiguration(pcConfig);
  4149. }
  4150. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  4151. };
  4152. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  4153. navigator.getUserMedia = window.getUserMedia;
  4154. attachMediaStream = function (element, stream) {
  4155. if (typeof element.srcObject !== 'undefined') {
  4156. element.srcObject = stream;
  4157. } else if (typeof element.mozSrcObject !== 'undefined') {
  4158. element.mozSrcObject = stream;
  4159. } else if (typeof element.src !== 'undefined') {
  4160. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  4161. } else {
  4162. console.log('Error attaching stream to element.');
  4163. }
  4164. return element;
  4165. };
  4166. reattachMediaStream = function (to, from) {
  4167. to.src = from.src;
  4168. return to;
  4169. };
  4170. AdapterJS.maybeThroughWebRTCReady();
  4171. } else if (navigator.mediaDevices && navigator.userAgent.match(
  4172. /Edge\/(\d+).(\d+)$/)) {
  4173. webrtcDetectedBrowser = 'edge';
  4174. webrtcDetectedVersion =
  4175. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  4176. // the minimum version still supported by adapter.
  4177. webrtcMinimumVersion = 12;
  4178. window.getUserMedia = navigator.getUserMedia.bind(navigator);
  4179. attachMediaStream = function(element, stream) {
  4180. element.srcObject = stream;
  4181. return element;
  4182. };
  4183. reattachMediaStream = function(to, from) {
  4184. to.srcObject = from.srcObject;
  4185. return to;
  4186. };
  4187. AdapterJS.maybeThroughWebRTCReady();
  4188. } else { // TRY TO USE PLUGIN
  4189. // IE 9 is not offering an implementation of console.log until you open a console
  4190. if (typeof console !== 'object' || typeof console.log !== 'function') {
  4191. /* jshint -W020 */
  4192. console = {} || console;
  4193. // Implemented based on console specs from MDN
  4194. // You may override these functions
  4195. console.log = function (arg) {};
  4196. console.info = function (arg) {};
  4197. console.error = function (arg) {};
  4198. console.dir = function (arg) {};
  4199. console.exception = function (arg) {};
  4200. console.trace = function (arg) {};
  4201. console.warn = function (arg) {};
  4202. console.count = function (arg) {};
  4203. console.debug = function (arg) {};
  4204. console.count = function (arg) {};
  4205. console.time = function (arg) {};
  4206. console.timeEnd = function (arg) {};
  4207. console.group = function (arg) {};
  4208. console.groupCollapsed = function (arg) {};
  4209. console.groupEnd = function (arg) {};
  4210. /* jshint +W020 */
  4211. }
  4212. webrtcDetectedType = 'plugin';
  4213. webrtcDetectedDCSupport = 'plugin';
  4214. AdapterJS.parseWebrtcDetectedBrowser();
  4215. isIE = webrtcDetectedBrowser === 'IE';
  4216. /* jshint -W035 */
  4217. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  4218. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4219. /* empty because it needs to prevent the function from running. */
  4220. }
  4221. };
  4222. /* jshint +W035 */
  4223. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  4224. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4225. // Call immediately if possible
  4226. // Once the plugin is set, the code will always take this path
  4227. callback();
  4228. } else {
  4229. // otherwise start a 100ms interval
  4230. var checkPluginReadyState = setInterval(function () {
  4231. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4232. clearInterval(checkPluginReadyState);
  4233. callback();
  4234. }
  4235. }, 100);
  4236. }
  4237. };
  4238. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  4239. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4240. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  4241. });
  4242. };
  4243. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  4244. // only inject once the page is ready
  4245. if (document.readyState !== 'complete') {
  4246. return;
  4247. }
  4248. // Prevent multiple injections
  4249. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  4250. return;
  4251. }
  4252. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  4253. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  4254. var frag = document.createDocumentFragment();
  4255. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  4256. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  4257. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  4258. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  4259. '<param name="pluginId" value="' +
  4260. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  4261. '<param name="windowless" value="false" /> ' +
  4262. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4263. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  4264. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  4265. // uncomment to be able to use virtual cams
  4266. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4267. '</object>';
  4268. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  4269. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  4270. }
  4271. document.body.appendChild(frag);
  4272. // Need to re-fetch the plugin
  4273. AdapterJS.WebRTCPlugin.plugin =
  4274. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  4275. } else {
  4276. // Load Plugin
  4277. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  4278. AdapterJS.WebRTCPlugin.plugin.id =
  4279. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  4280. // IE will only start the plugin if it's ACTUALLY visible
  4281. if (isIE) {
  4282. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  4283. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  4284. } else { // The size of the plugin on Safari should be 0x0px
  4285. // so that the autorisation prompt is at the top
  4286. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  4287. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  4288. }
  4289. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  4290. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  4291. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  4292. '<param name="pluginId" value="' +
  4293. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  4294. '<param name="windowless" value="false" /> ' +
  4295. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4296. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  4297. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  4298. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  4299. }
  4300. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  4301. };
  4302. AdapterJS.WebRTCPlugin.isPluginInstalled =
  4303. function (comName, plugName, installedCb, notInstalledCb) {
  4304. if (!isIE) {
  4305. var pluginArray = navigator.plugins;
  4306. for (var i = 0; i < pluginArray.length; i++) {
  4307. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  4308. installedCb();
  4309. return;
  4310. }
  4311. }
  4312. notInstalledCb();
  4313. } else {
  4314. try {
  4315. var axo = new ActiveXObject(comName + '.' + plugName);
  4316. } catch (e) {
  4317. notInstalledCb();
  4318. return;
  4319. }
  4320. installedCb();
  4321. }
  4322. };
  4323. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  4324. if (AdapterJS.WebRTCPlugin.pluginState ===
  4325. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4326. console.error("AdapterJS - WebRTC interface has already been defined");
  4327. return;
  4328. }
  4329. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  4330. AdapterJS.isDefined = function (variable) {
  4331. return variable !== null && variable !== undefined;
  4332. };
  4333. createIceServer = function (url, username, password) {
  4334. var iceServer = null;
  4335. var url_parts = url.split(':');
  4336. if (url_parts[0].indexOf('stun') === 0) {
  4337. iceServer = {
  4338. 'url' : url,
  4339. 'hasCredentials' : false
  4340. };
  4341. } else if (url_parts[0].indexOf('turn') === 0) {
  4342. iceServer = {
  4343. 'url' : url,
  4344. 'hasCredentials' : true,
  4345. 'credential' : password,
  4346. 'username' : username
  4347. };
  4348. }
  4349. return iceServer;
  4350. };
  4351. createIceServers = function (urls, username, password) {
  4352. var iceServers = [];
  4353. for (var i = 0; i < urls.length; ++i) {
  4354. iceServers.push(createIceServer(urls[i], username, password));
  4355. }
  4356. return iceServers;
  4357. };
  4358. RTCSessionDescription = function (info) {
  4359. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4360. return AdapterJS.WebRTCPlugin.plugin.
  4361. ConstructSessionDescription(info.type, info.sdp);
  4362. };
  4363. RTCPeerConnection = function (servers, constraints) {
  4364. var iceServers = null;
  4365. if (servers) {
  4366. iceServers = servers.iceServers;
  4367. for (var i = 0; i < iceServers.length; i++) {
  4368. if (iceServers[i].urls && !iceServers[i].url) {
  4369. iceServers[i].url = iceServers[i].urls;
  4370. }
  4371. iceServers[i].hasCredentials = AdapterJS.
  4372. isDefined(iceServers[i].username) &&
  4373. AdapterJS.isDefined(iceServers[i].credential);
  4374. }
  4375. }
  4376. var mandatory = (constraints && constraints.mandatory) ?
  4377. constraints.mandatory : null;
  4378. var optional = (constraints && constraints.optional) ?
  4379. constraints.optional : null;
  4380. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4381. return AdapterJS.WebRTCPlugin.plugin.
  4382. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  4383. iceServers, mandatory, optional);
  4384. };
  4385. MediaStreamTrack = {};
  4386. MediaStreamTrack.getSources = function (callback) {
  4387. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4388. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  4389. });
  4390. };
  4391. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  4392. constraints.audio = constraints.audio || false;
  4393. constraints.video = constraints.video || false;
  4394. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4395. AdapterJS.WebRTCPlugin.plugin.
  4396. getUserMedia(constraints, successCallback, failureCallback);
  4397. });
  4398. };
  4399. window.navigator.getUserMedia = window.getUserMedia;
  4400. attachMediaStream = function (element, stream) {
  4401. if (!element || !element.parentNode) {
  4402. return;
  4403. }
  4404. var streamId;
  4405. if (stream === null) {
  4406. streamId = '';
  4407. } else {
  4408. if (typeof stream.enableSoundTracks !== 'undefined') {
  4409. stream.enableSoundTracks(true);
  4410. }
  4411. streamId = stream.id;
  4412. }
  4413. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  4414. var nodeName = element.nodeName.toLowerCase();
  4415. if (nodeName !== 'object') { // not a plugin <object> tag yet
  4416. var tag;
  4417. switch(nodeName) {
  4418. case 'audio':
  4419. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  4420. break;
  4421. case 'video':
  4422. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  4423. break;
  4424. default:
  4425. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  4426. }
  4427. var frag = document.createDocumentFragment();
  4428. var temp = document.createElement('div');
  4429. var classHTML = '';
  4430. if (element.className) {
  4431. classHTML = 'class="' + element.className + '" ';
  4432. } else if (element.attributes && element.attributes['class']) {
  4433. classHTML = 'class="' + element.attributes['class'].value + '" ';
  4434. }
  4435. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  4436. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  4437. '<param name="pluginId" value="' + elementId + '" /> ' +
  4438. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4439. '<param name="windowless" value="true" /> ' +
  4440. '<param name="streamId" value="' + streamId + '" /> ' +
  4441. '<param name="tag" value="' + tag + '" /> ' +
  4442. '</object>';
  4443. while (temp.firstChild) {
  4444. frag.appendChild(temp.firstChild);
  4445. }
  4446. var height = '';
  4447. var width = '';
  4448. if (element.clientWidth || element.clientHeight) {
  4449. width = element.clientWidth;
  4450. height = element.clientHeight;
  4451. }
  4452. else if (element.width || element.height) {
  4453. width = element.width;
  4454. height = element.height;
  4455. }
  4456. element.parentNode.insertBefore(frag, element);
  4457. frag = document.getElementById(elementId);
  4458. frag.width = width;
  4459. frag.height = height;
  4460. element.parentNode.removeChild(element);
  4461. } else { // already an <object> tag, just change the stream id
  4462. var children = element.children;
  4463. for (var i = 0; i !== children.length; ++i) {
  4464. if (children[i].name === 'streamId') {
  4465. children[i].value = streamId;
  4466. break;
  4467. }
  4468. }
  4469. element.setStreamId(streamId);
  4470. }
  4471. var newElement = document.getElementById(elementId);
  4472. AdapterJS.forwardEventHandlers(newElement, element, Object.getPrototypeOf(element));
  4473. return newElement;
  4474. };
  4475. reattachMediaStream = function (to, from) {
  4476. var stream = null;
  4477. var children = from.children;
  4478. for (var i = 0; i !== children.length; ++i) {
  4479. if (children[i].name === 'streamId') {
  4480. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4481. stream = AdapterJS.WebRTCPlugin.plugin
  4482. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  4483. break;
  4484. }
  4485. }
  4486. if (stream !== null) {
  4487. return attachMediaStream(to, stream);
  4488. } else {
  4489. console.log('Could not find the stream associated with this element');
  4490. }
  4491. };
  4492. AdapterJS.forwardEventHandlers = function (destElem, srcElem, prototype) {
  4493. properties = Object.getOwnPropertyNames( prototype );
  4494. for(prop in properties) {
  4495. propName = properties[prop];
  4496. if (typeof(propName.slice) === 'function') {
  4497. if (propName.slice(0,2) == 'on' && srcElem[propName] != null) {
  4498. if (isIE) {
  4499. destElem.attachEvent(propName,srcElem[propName]);
  4500. } else {
  4501. destElem.addEventListener(propName.slice(2), srcElem[propName], false)
  4502. }
  4503. } else {
  4504. //TODO (http://jira.temasys.com.sg/browse/TWP-328) Forward non-event properties ?
  4505. }
  4506. }
  4507. }
  4508. var subPrototype = Object.getPrototypeOf(prototype)
  4509. if(subPrototype != null) {
  4510. AdapterJS.forwardEventHandlers(destElem, srcElem, subPrototype);
  4511. }
  4512. }
  4513. RTCIceCandidate = function (candidate) {
  4514. if (!candidate.sdpMid) {
  4515. candidate.sdpMid = '';
  4516. }
  4517. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4518. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  4519. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  4520. );
  4521. };
  4522. // inject plugin
  4523. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  4524. AdapterJS.WebRTCPlugin.injectPlugin();
  4525. };
  4526. // This function will be called if the plugin is needed (browser different
  4527. // from Chrome or Firefox), but the plugin is not installed.
  4528. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  4529. function() {
  4530. AdapterJS.addEvent(document,
  4531. 'readystatechange',
  4532. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  4533. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  4534. };
  4535. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  4536. if (AdapterJS.options.hidePluginInstallPrompt) {
  4537. return;
  4538. }
  4539. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  4540. if(downloadLink) { // if download link
  4541. var popupString;
  4542. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  4543. popupString = 'This website requires you to install the ' +
  4544. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  4545. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  4546. ' WebRTC Plugin</a>' +
  4547. ' to work on this browser.';
  4548. } else { // no portal link, just print a generic explanation
  4549. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  4550. }
  4551. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  4552. } else { // no download link, just print a generic explanation
  4553. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  4554. }
  4555. };
  4556. // Try to detect the plugin and act accordingly
  4557. AdapterJS.WebRTCPlugin.isPluginInstalled(
  4558. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  4559. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  4560. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  4561. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  4562. }
  4563. }).call(this,"/modules/RTC/adapter.screenshare.js")
  4564. },{"jitsi-meet-logger":47}],21:[function(require,module,exports){
  4565. (function (__filename){
  4566. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4567. function supportsLocalStorage() {
  4568. try {
  4569. return 'localStorage' in window && window.localStorage !== null;
  4570. } catch (e) {
  4571. logger.log("localstorage is not supported");
  4572. return false;
  4573. }
  4574. }
  4575. function generateUniqueId() {
  4576. function _p8() {
  4577. return (Math.random().toString(16) + "000000000").substr(2, 8);
  4578. }
  4579. return _p8() + _p8() + _p8() + _p8();
  4580. }
  4581. function Settings(conferenceID) {
  4582. this.displayName = '';
  4583. this.userId;
  4584. this.confSettings = null;
  4585. this.conferenceID = conferenceID;
  4586. if (supportsLocalStorage()) {
  4587. if(!window.localStorage.getItem(conferenceID))
  4588. this.confSettings = {};
  4589. else
  4590. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  4591. if(!this.confSettings.jitsiMeetId) {
  4592. this.confSettings.jitsiMeetId = generateUniqueId();
  4593. logger.log("generated id",
  4594. this.confSettings.jitsiMeetId);
  4595. this.save();
  4596. }
  4597. this.userId = this.confSettings.jitsiMeetId || '';
  4598. this.displayName = this.confSettings.displayname || '';
  4599. } else {
  4600. logger.log("local storage is not supported");
  4601. this.userId = generateUniqueId();
  4602. }
  4603. }
  4604. Settings.prototype.save = function () {
  4605. if(!supportsLocalStorage())
  4606. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  4607. }
  4608. Settings.prototype.setDisplayName = function (newDisplayName) {
  4609. this.displayName = newDisplayName;
  4610. if(this.confSettings != null)
  4611. this.confSettings.displayname = displayName;
  4612. this.save();
  4613. return this.displayName;
  4614. },
  4615. Settings.prototype.getSettings = function () {
  4616. return {
  4617. displayName: this.displayName,
  4618. uid: this.userId
  4619. };
  4620. },
  4621. module.exports = Settings;
  4622. }).call(this,"/modules/settings/Settings.js")
  4623. },{"jitsi-meet-logger":47}],22:[function(require,module,exports){
  4624. /* global config */
  4625. /**
  4626. * Provides statistics for the local stream.
  4627. */
  4628. var RTCBrowserType = require('../RTC/RTCBrowserType');
  4629. /**
  4630. * Size of the webaudio analyzer buffer.
  4631. * @type {number}
  4632. */
  4633. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  4634. /**
  4635. * Value of the webaudio analyzer smoothing time parameter.
  4636. * @type {number}
  4637. */
  4638. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  4639. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  4640. var context = null;
  4641. if(window.AudioContext) {
  4642. context = new AudioContext();
  4643. }
  4644. /**
  4645. * Converts time domain data array to audio level.
  4646. * @param samples the time domain data array.
  4647. * @returns {number} the audio level
  4648. */
  4649. function timeDomainDataToAudioLevel(samples) {
  4650. var maxVolume = 0;
  4651. var length = samples.length;
  4652. for (var i = 0; i < length; i++) {
  4653. if (maxVolume < samples[i])
  4654. maxVolume = samples[i];
  4655. }
  4656. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  4657. }
  4658. /**
  4659. * Animates audio level change
  4660. * @param newLevel the new audio level
  4661. * @param lastLevel the last audio level
  4662. * @returns {Number} the audio level to be set
  4663. */
  4664. function animateLevel(newLevel, lastLevel) {
  4665. var value = 0;
  4666. var diff = lastLevel - newLevel;
  4667. if(diff > 0.2) {
  4668. value = lastLevel - 0.2;
  4669. }
  4670. else if(diff < -0.4) {
  4671. value = lastLevel + 0.4;
  4672. }
  4673. else {
  4674. value = newLevel;
  4675. }
  4676. return parseFloat(value.toFixed(3));
  4677. }
  4678. /**
  4679. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  4680. *
  4681. * @param stream the local stream
  4682. * @param interval stats refresh interval given in ms.
  4683. * @param callback function that receives the audio levels.
  4684. * @constructor
  4685. */
  4686. function LocalStatsCollector(stream, interval, callback) {
  4687. this.stream = stream;
  4688. this.intervalId = null;
  4689. this.intervalMilis = interval;
  4690. this.audioLevel = 0;
  4691. this.callback = callback;
  4692. }
  4693. /**
  4694. * Starts the collecting the statistics.
  4695. */
  4696. LocalStatsCollector.prototype.start = function () {
  4697. if (!context ||
  4698. RTCBrowserType.isTemasysPluginUsed())
  4699. return;
  4700. var analyser = context.createAnalyser();
  4701. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  4702. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  4703. var source = context.createMediaStreamSource(this.stream);
  4704. source.connect(analyser);
  4705. var self = this;
  4706. this.intervalId = setInterval(
  4707. function () {
  4708. var array = new Uint8Array(analyser.frequencyBinCount);
  4709. analyser.getByteTimeDomainData(array);
  4710. var audioLevel = timeDomainDataToAudioLevel(array);
  4711. if (audioLevel != self.audioLevel) {
  4712. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  4713. self.callback(self.audioLevel);
  4714. }
  4715. },
  4716. this.intervalMilis
  4717. );
  4718. };
  4719. /**
  4720. * Stops collecting the statistics.
  4721. */
  4722. LocalStatsCollector.prototype.stop = function () {
  4723. if (this.intervalId) {
  4724. clearInterval(this.intervalId);
  4725. this.intervalId = null;
  4726. }
  4727. };
  4728. module.exports = LocalStatsCollector;
  4729. },{"../RTC/RTCBrowserType":17}],23:[function(require,module,exports){
  4730. (function (__filename){
  4731. /* global require, ssrc2jid */
  4732. /* jshint -W117 */
  4733. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4734. var RTCBrowserType = require("../RTC/RTCBrowserType");
  4735. var StatisticsEvents = require("../../service/statistics/Events");
  4736. /* Whether we support the browser we are running into for logging statistics */
  4737. var browserSupported = RTCBrowserType.isChrome() ||
  4738. RTCBrowserType.isOpera();
  4739. var keyMap = {};
  4740. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  4741. "ssrc": "ssrc",
  4742. "packetsReceived": "packetsReceived",
  4743. "packetsLost": "packetsLost",
  4744. "packetsSent": "packetsSent",
  4745. "bytesReceived": "bytesReceived",
  4746. "bytesSent": "bytesSent"
  4747. };
  4748. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  4749. "receiveBandwidth": "googAvailableReceiveBandwidth",
  4750. "sendBandwidth": "googAvailableSendBandwidth",
  4751. "remoteAddress": "googRemoteAddress",
  4752. "transportType": "googTransportType",
  4753. "localAddress": "googLocalAddress",
  4754. "activeConnection": "googActiveConnection",
  4755. "ssrc": "ssrc",
  4756. "packetsReceived": "packetsReceived",
  4757. "packetsSent": "packetsSent",
  4758. "packetsLost": "packetsLost",
  4759. "bytesReceived": "bytesReceived",
  4760. "bytesSent": "bytesSent",
  4761. "googFrameHeightReceived": "googFrameHeightReceived",
  4762. "googFrameWidthReceived": "googFrameWidthReceived",
  4763. "googFrameHeightSent": "googFrameHeightSent",
  4764. "googFrameWidthSent": "googFrameWidthSent",
  4765. "audioInputLevel": "audioInputLevel",
  4766. "audioOutputLevel": "audioOutputLevel"
  4767. };
  4768. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  4769. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  4770. /**
  4771. * Calculates packet lost percent using the number of lost packets and the
  4772. * number of all packet.
  4773. * @param lostPackets the number of lost packets
  4774. * @param totalPackets the number of all packets.
  4775. * @returns {number} packet loss percent
  4776. */
  4777. function calculatePacketLoss(lostPackets, totalPackets) {
  4778. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  4779. return 0;
  4780. return Math.round((lostPackets/totalPackets)*100);
  4781. }
  4782. function getStatValue(item, name) {
  4783. var browserType = RTCBrowserType.getBrowserType();
  4784. if (!keyMap[browserType][name])
  4785. throw "The property isn't supported!";
  4786. var key = keyMap[browserType][name];
  4787. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  4788. item.stat(key) : item[key];
  4789. }
  4790. function formatAudioLevel(audioLevel) {
  4791. return Math.min(Math.max(audioLevel, 0), 1);
  4792. }
  4793. /**
  4794. * Checks whether a certain record should be included in the logged statistics.
  4795. */
  4796. function acceptStat(reportId, reportType, statName) {
  4797. if (reportType == "googCandidatePair" && statName == "googChannelId")
  4798. return false;
  4799. if (reportType == "ssrc") {
  4800. if (statName == "googTrackId" ||
  4801. statName == "transportId" ||
  4802. statName == "ssrc")
  4803. return false;
  4804. }
  4805. return true;
  4806. }
  4807. /**
  4808. * Checks whether a certain record should be included in the logged statistics.
  4809. */
  4810. function acceptReport(id, type) {
  4811. if (id.substring(0, 15) == "googCertificate" ||
  4812. id.substring(0, 9) == "googTrack" ||
  4813. id.substring(0, 20) == "googLibjingleSession")
  4814. return false;
  4815. if (type == "googComponent")
  4816. return false;
  4817. return true;
  4818. }
  4819. /**
  4820. * Peer statistics data holder.
  4821. * @constructor
  4822. */
  4823. function PeerStats()
  4824. {
  4825. this.ssrc2Loss = {};
  4826. this.ssrc2AudioLevel = {};
  4827. this.ssrc2bitrate = {};
  4828. this.ssrc2resolution = {};
  4829. }
  4830. /**
  4831. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  4832. * represented by this instance.
  4833. * @param lossRate new packet loss rate value to be set.
  4834. */
  4835. PeerStats.prototype.setSsrcLoss = function (lossRate)
  4836. {
  4837. this.ssrc2Loss = lossRate;
  4838. };
  4839. /**
  4840. * Sets resolution that belong to the ssrc
  4841. * represented by this instance.
  4842. * @param resolution new resolution value to be set.
  4843. */
  4844. PeerStats.prototype.setSsrcResolution = function (resolution)
  4845. {
  4846. if(resolution === null && this.ssrc2resolution[ssrc])
  4847. {
  4848. delete this.ssrc2resolution[ssrc];
  4849. }
  4850. else if(resolution !== null)
  4851. this.ssrc2resolution[ssrc] = resolution;
  4852. };
  4853. /**
  4854. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  4855. * represented by this instance.
  4856. * @param ssrc audio or video RTP stream SSRC.
  4857. * @param bitrate new bitrate value to be set.
  4858. */
  4859. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  4860. {
  4861. if(this.ssrc2bitrate[ssrc])
  4862. {
  4863. this.ssrc2bitrate[ssrc].download += bitrate.download;
  4864. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  4865. }
  4866. else {
  4867. this.ssrc2bitrate[ssrc] = bitrate;
  4868. }
  4869. };
  4870. /**
  4871. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  4872. * the stream which belongs to the peer represented by this instance.
  4873. * @param ssrc RTP stream SSRC for which current audio level value will be
  4874. * updated.
  4875. * @param audioLevel the new audio level value to be set. Value is truncated to
  4876. * fit the range from 0 to 1.
  4877. */
  4878. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  4879. {
  4880. // Range limit 0 - 1
  4881. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  4882. };
  4883. function ConferenceStats() {
  4884. /**
  4885. * The bandwidth
  4886. * @type {{}}
  4887. */
  4888. this.bandwidth = {};
  4889. /**
  4890. * The bit rate
  4891. * @type {{}}
  4892. */
  4893. this.bitrate = {};
  4894. /**
  4895. * The packet loss rate
  4896. * @type {{}}
  4897. */
  4898. this.packetLoss = null;
  4899. /**
  4900. * Array with the transport information.
  4901. * @type {Array}
  4902. */
  4903. this.transport = [];
  4904. }
  4905. /**
  4906. * <tt>StatsCollector</tt> registers for stats updates of given
  4907. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  4908. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  4909. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  4910. * instance as an event source.
  4911. *
  4912. * @param peerconnection webRTC peer connection object.
  4913. * @param interval stats refresh interval given in ms.
  4914. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  4915. * called on stats update.
  4916. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  4917. * @constructor
  4918. */
  4919. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  4920. {
  4921. this.peerconnection = peerconnection;
  4922. this.baselineAudioLevelsReport = null;
  4923. this.currentAudioLevelsReport = null;
  4924. this.currentStatsReport = null;
  4925. this.baselineStatsReport = null;
  4926. this.audioLevelsIntervalId = null;
  4927. this.eventEmitter = eventEmitter;
  4928. this.config = config || {};
  4929. this.conferenceStats = new ConferenceStats();
  4930. /**
  4931. * Gather PeerConnection stats once every this many milliseconds.
  4932. */
  4933. this.GATHER_INTERVAL = 15000;
  4934. /**
  4935. * Log stats via the focus once every this many milliseconds.
  4936. */
  4937. this.LOG_INTERVAL = 60000;
  4938. /**
  4939. * Gather stats and store them in this.statsToBeLogged.
  4940. */
  4941. this.gatherStatsIntervalId = null;
  4942. /**
  4943. * Send the stats already saved in this.statsToBeLogged to be logged via
  4944. * the focus.
  4945. */
  4946. this.logStatsIntervalId = null;
  4947. /**
  4948. * Stores the statistics which will be send to the focus to be logged.
  4949. */
  4950. this.statsToBeLogged =
  4951. {
  4952. timestamps: [],
  4953. stats: {}
  4954. };
  4955. // Updates stats interval
  4956. this.audioLevelsIntervalMilis = audioLevelsInterval;
  4957. this.statsIntervalId = null;
  4958. this.statsIntervalMilis = statsInterval;
  4959. // Map of ssrcs to PeerStats
  4960. this.ssrc2stats = {};
  4961. }
  4962. module.exports = StatsCollector;
  4963. /**
  4964. * Stops stats updates.
  4965. */
  4966. StatsCollector.prototype.stop = function () {
  4967. if (this.audioLevelsIntervalId) {
  4968. clearInterval(this.audioLevelsIntervalId);
  4969. this.audioLevelsIntervalId = null;
  4970. }
  4971. if (this.statsIntervalId)
  4972. {
  4973. clearInterval(this.statsIntervalId);
  4974. this.statsIntervalId = null;
  4975. }
  4976. if(this.logStatsIntervalId)
  4977. {
  4978. clearInterval(this.logStatsIntervalId);
  4979. this.logStatsIntervalId = null;
  4980. }
  4981. if(this.gatherStatsIntervalId)
  4982. {
  4983. clearInterval(this.gatherStatsIntervalId);
  4984. this.gatherStatsIntervalId = null;
  4985. }
  4986. };
  4987. /**
  4988. * Callback passed to <tt>getStats</tt> method.
  4989. * @param error an error that occurred on <tt>getStats</tt> call.
  4990. */
  4991. StatsCollector.prototype.errorCallback = function (error)
  4992. {
  4993. logger.error("Get stats error", error);
  4994. this.stop();
  4995. };
  4996. /**
  4997. * Starts stats updates.
  4998. */
  4999. StatsCollector.prototype.start = function ()
  5000. {
  5001. var self = this;
  5002. this.audioLevelsIntervalId = setInterval(
  5003. function () {
  5004. // Interval updates
  5005. self.peerconnection.getStats(
  5006. function (report) {
  5007. var results = null;
  5008. if (!report || !report.result ||
  5009. typeof report.result != 'function') {
  5010. results = report;
  5011. }
  5012. else {
  5013. results = report.result();
  5014. }
  5015. //logger.error("Got interval report", results);
  5016. self.currentAudioLevelsReport = results;
  5017. self.processAudioLevelReport();
  5018. self.baselineAudioLevelsReport =
  5019. self.currentAudioLevelsReport;
  5020. },
  5021. self.errorCallback
  5022. );
  5023. },
  5024. self.audioLevelsIntervalMilis
  5025. );
  5026. // if (!this.config.disableStats && browserSupported) {
  5027. // this.statsIntervalId = setInterval(
  5028. // function () {
  5029. // // Interval updates
  5030. // self.peerconnection.getStats(
  5031. // function (report) {
  5032. // var results = null;
  5033. // if (!report || !report.result ||
  5034. // typeof report.result != 'function') {
  5035. // //firefox
  5036. // results = report;
  5037. // }
  5038. // else {
  5039. // //chrome
  5040. // results = report.result();
  5041. // }
  5042. // //logger.error("Got interval report", results);
  5043. // self.currentStatsReport = results;
  5044. // try {
  5045. // self.processStatsReport();
  5046. // }
  5047. // catch (e) {
  5048. // logger.error("Unsupported key:" + e, e);
  5049. // }
  5050. //
  5051. // self.baselineStatsReport = self.currentStatsReport;
  5052. // },
  5053. // self.errorCallback
  5054. // );
  5055. // },
  5056. // self.statsIntervalMilis
  5057. // );
  5058. // }
  5059. //
  5060. // if (this.config.logStats && browserSupported) {
  5061. // this.gatherStatsIntervalId = setInterval(
  5062. // function () {
  5063. // self.peerconnection.getStats(
  5064. // function (report) {
  5065. // self.addStatsToBeLogged(report.result());
  5066. // },
  5067. // function () {
  5068. // }
  5069. // );
  5070. // },
  5071. // this.GATHER_INTERVAL
  5072. // );
  5073. //
  5074. // this.logStatsIntervalId = setInterval(
  5075. // function() { self.logStats(); },
  5076. // this.LOG_INTERVAL);
  5077. // }
  5078. };
  5079. /**
  5080. * Converts the stats to the format used for logging, and saves the data in
  5081. * this.statsToBeLogged.
  5082. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  5083. */
  5084. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  5085. var self = this;
  5086. var num_records = this.statsToBeLogged.timestamps.length;
  5087. this.statsToBeLogged.timestamps.push(new Date().getTime());
  5088. reports.map(function (report) {
  5089. if (!acceptReport(report.id, report.type))
  5090. return;
  5091. var stat = self.statsToBeLogged.stats[report.id];
  5092. if (!stat) {
  5093. stat = self.statsToBeLogged.stats[report.id] = {};
  5094. }
  5095. stat.type = report.type;
  5096. report.names().map(function (name) {
  5097. if (!acceptStat(report.id, report.type, name))
  5098. return;
  5099. var values = stat[name];
  5100. if (!values) {
  5101. values = stat[name] = [];
  5102. }
  5103. while (values.length < num_records) {
  5104. values.push(null);
  5105. }
  5106. values.push(report.stat(name));
  5107. });
  5108. });
  5109. };
  5110. //FIXME:
  5111. //StatsCollector.prototype.logStats = function () {
  5112. //
  5113. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  5114. // return;
  5115. // // Reset the stats
  5116. // this.statsToBeLogged.stats = {};
  5117. // this.statsToBeLogged.timestamps = [];
  5118. //};
  5119. /**
  5120. * Stats processing logic.
  5121. */
  5122. StatsCollector.prototype.processStatsReport = function () {
  5123. if (!this.baselineStatsReport) {
  5124. return;
  5125. }
  5126. for (var idx in this.currentStatsReport) {
  5127. var now = this.currentStatsReport[idx];
  5128. try {
  5129. if (getStatValue(now, 'receiveBandwidth') ||
  5130. getStatValue(now, 'sendBandwidth')) {
  5131. this.conferenceStats.bandwidth = {
  5132. "download": Math.round(
  5133. (getStatValue(now, 'receiveBandwidth')) / 1000),
  5134. "upload": Math.round(
  5135. (getStatValue(now, 'sendBandwidth')) / 1000)
  5136. };
  5137. }
  5138. }
  5139. catch(e){/*not supported*/}
  5140. if(now.type == 'googCandidatePair')
  5141. {
  5142. var ip, type, localIP, active;
  5143. try {
  5144. ip = getStatValue(now, 'remoteAddress');
  5145. type = getStatValue(now, "transportType");
  5146. localIP = getStatValue(now, "localAddress");
  5147. active = getStatValue(now, "activeConnection");
  5148. }
  5149. catch(e){/*not supported*/}
  5150. if(!ip || !type || !localIP || active != "true")
  5151. continue;
  5152. var addressSaved = false;
  5153. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  5154. {
  5155. if(this.conferenceStats.transport[i].ip == ip &&
  5156. this.conferenceStats.transport[i].type == type &&
  5157. this.conferenceStats.transport[i].localip == localIP)
  5158. {
  5159. addressSaved = true;
  5160. }
  5161. }
  5162. if(addressSaved)
  5163. continue;
  5164. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  5165. continue;
  5166. }
  5167. if(now.type == "candidatepair")
  5168. {
  5169. if(now.state == "succeeded")
  5170. continue;
  5171. var local = this.currentStatsReport[now.localCandidateId];
  5172. var remote = this.currentStatsReport[now.remoteCandidateId];
  5173. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  5174. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  5175. }
  5176. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  5177. now.type != "inboundrtp") {
  5178. continue;
  5179. }
  5180. var before = this.baselineStatsReport[idx];
  5181. if (!before) {
  5182. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5183. continue;
  5184. }
  5185. var ssrc = getStatValue(now, 'ssrc');
  5186. if(!ssrc)
  5187. continue;
  5188. var ssrcStats = this.ssrc2stats[ssrc];
  5189. if (!ssrcStats) {
  5190. ssrcStats = new PeerStats();
  5191. this.ssrc2stats[ssrc] = ssrcStats;
  5192. }
  5193. var isDownloadStream = true;
  5194. var key = 'packetsReceived';
  5195. var packetsNow = getStatValue(now, key);
  5196. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  5197. isDownloadStream = false;
  5198. key = 'packetsSent';
  5199. packetsNow = getStatValue(now, key);
  5200. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  5201. console.warn("No packetsReceived nor packetsSent stat found");
  5202. continue;
  5203. }
  5204. }
  5205. if (!packetsNow || packetsNow < 0)
  5206. packetsNow = 0;
  5207. var packetsBefore = getStatValue(before, key);
  5208. if (!packetsBefore || packetsBefore < 0)
  5209. packetsBefore = 0;
  5210. var packetRate = packetsNow - packetsBefore;
  5211. if (!packetRate || packetRate < 0)
  5212. packetRate = 0;
  5213. var currentLoss = getStatValue(now, 'packetsLost');
  5214. if (!currentLoss || currentLoss < 0)
  5215. currentLoss = 0;
  5216. var previousLoss = getStatValue(before, 'packetsLost');
  5217. if (!previousLoss || previousLoss < 0)
  5218. previousLoss = 0;
  5219. var lossRate = currentLoss - previousLoss;
  5220. if (!lossRate || lossRate < 0)
  5221. lossRate = 0;
  5222. var packetsTotal = (packetRate + lossRate);
  5223. ssrcStats.setSsrcLoss(ssrc,
  5224. {"packetsTotal": packetsTotal,
  5225. "packetsLost": lossRate,
  5226. "isDownloadStream": isDownloadStream});
  5227. var bytesReceived = 0, bytesSent = 0;
  5228. if(getStatValue(now, "bytesReceived")) {
  5229. bytesReceived = getStatValue(now, "bytesReceived") -
  5230. getStatValue(before, "bytesReceived");
  5231. }
  5232. if (getStatValue(now, "bytesSent")) {
  5233. bytesSent = getStatValue(now, "bytesSent") -
  5234. getStatValue(before, "bytesSent");
  5235. }
  5236. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  5237. if (bytesReceived <= 0 || time <= 0) {
  5238. bytesReceived = 0;
  5239. } else {
  5240. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  5241. }
  5242. if (bytesSent <= 0 || time <= 0) {
  5243. bytesSent = 0;
  5244. } else {
  5245. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  5246. }
  5247. ssrcStats.setSsrcBitrate(ssrc, {
  5248. "download": bytesReceived,
  5249. "upload": bytesSent});
  5250. var resolution = {height: null, width: null};
  5251. try {
  5252. if (getStatValue(now, "googFrameHeightReceived") &&
  5253. getStatValue(now, "googFrameWidthReceived")) {
  5254. resolution.height =
  5255. getStatValue(now, "googFrameHeightReceived");
  5256. resolution.width = getStatValue(now, "googFrameWidthReceived");
  5257. }
  5258. else if (getStatValue(now, "googFrameHeightSent") &&
  5259. getStatValue(now, "googFrameWidthSent")) {
  5260. resolution.height = getStatValue(now, "googFrameHeightSent");
  5261. resolution.width = getStatValue(now, "googFrameWidthSent");
  5262. }
  5263. }
  5264. catch(e){/*not supported*/}
  5265. if (resolution.height && resolution.width) {
  5266. ssrcStats.setSsrcResolution(ssrc, resolution);
  5267. } else {
  5268. ssrcStats.setSsrcResolution(ssrc, null);
  5269. }
  5270. }
  5271. var self = this;
  5272. // Jid stats
  5273. var totalPackets = {download: 0, upload: 0};
  5274. var lostPackets = {download: 0, upload: 0};
  5275. var bitrateDownload = 0;
  5276. var bitrateUpload = 0;
  5277. var resolutions = {};
  5278. Object.keys(this.ssrc2stats).forEach(
  5279. function (jid) {
  5280. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  5281. function (ssrc) {
  5282. var type = "upload";
  5283. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  5284. type = "download";
  5285. totalPackets[type] +=
  5286. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  5287. lostPackets[type] +=
  5288. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  5289. }
  5290. );
  5291. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  5292. function (ssrc) {
  5293. bitrateDownload +=
  5294. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  5295. bitrateUpload +=
  5296. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  5297. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  5298. }
  5299. );
  5300. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  5301. }
  5302. );
  5303. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  5304. this.conferenceStats.packetLoss = {
  5305. total:
  5306. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  5307. totalPackets.download + totalPackets.upload),
  5308. download:
  5309. calculatePacketLoss(lostPackets.download, totalPackets.download),
  5310. upload:
  5311. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  5312. };
  5313. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS,
  5314. {
  5315. "bitrate": this.conferenceStats.bitrate,
  5316. "packetLoss": this.conferenceStats.packetLoss,
  5317. "bandwidth": this.conferenceStats.bandwidth,
  5318. "resolution": resolutions,
  5319. "transport": this.conferenceStats.transport
  5320. });
  5321. this.conferenceStats.transport = [];
  5322. };
  5323. /**
  5324. * Stats processing logic.
  5325. */
  5326. StatsCollector.prototype.processAudioLevelReport = function () {
  5327. if (!this.baselineAudioLevelsReport) {
  5328. return;
  5329. }
  5330. for (var idx in this.currentAudioLevelsReport) {
  5331. var now = this.currentAudioLevelsReport[idx];
  5332. //if we don't have "packetsReceived" this is local stream
  5333. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  5334. continue;
  5335. }
  5336. var before = this.baselineAudioLevelsReport[idx];
  5337. if (!before) {
  5338. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5339. continue;
  5340. }
  5341. var ssrc = getStatValue(now, 'ssrc');
  5342. if (!ssrc) {
  5343. if((Date.now() - now.timestamp) < 3000)
  5344. logger.warn("No ssrc: ");
  5345. continue;
  5346. }
  5347. var ssrcStats = this.ssrc2stats[ssrc];
  5348. if (!ssrcStats) {
  5349. ssrcStats = new PeerStats();
  5350. this.ssrc2stats[ssrc] = ssrcStats;
  5351. }
  5352. // Audio level
  5353. var audioLevel = null;
  5354. try {
  5355. audioLevel = getStatValue(now, 'audioInputLevel');
  5356. if (!audioLevel)
  5357. audioLevel = getStatValue(now, 'audioOutputLevel');
  5358. }
  5359. catch(e) {/*not supported*/
  5360. logger.warn("Audio Levels are not available in the statistics.");
  5361. clearInterval(this.audioLevelsIntervalId);
  5362. return;
  5363. }
  5364. if (audioLevel) {
  5365. // TODO: can't find specs about what this value really is,
  5366. // but it seems to vary between 0 and around 32k.
  5367. audioLevel = audioLevel / 32767;
  5368. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  5369. this.eventEmitter.emit(
  5370. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel);
  5371. }
  5372. }
  5373. };
  5374. }).call(this,"/modules/statistics/RTPStatsCollector.js")
  5375. },{"../../service/statistics/Events":83,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":47}],24:[function(require,module,exports){
  5376. /* global require, APP */
  5377. var LocalStats = require("./LocalStatsCollector.js");
  5378. var RTPStats = require("./RTPStatsCollector.js");
  5379. var EventEmitter = require("events");
  5380. var StatisticsEvents = require("../../service/statistics/Events");
  5381. //var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  5382. //var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5383. //var CallStats = require("./CallStats");
  5384. //var RTCEvents = require("../../service/RTC/RTCEvents");
  5385. //
  5386. //function onDisposeConference(onUnload) {
  5387. // CallStats.sendTerminateEvent();
  5388. // stopRemote();
  5389. // if(onUnload) {
  5390. // stopLocal();
  5391. // eventEmitter.removeAllListeners();
  5392. // }
  5393. //}
  5394. var eventEmitter = new EventEmitter();
  5395. function Statistics() {
  5396. this.rtpStats = null;
  5397. this.eventEmitter = new EventEmitter();
  5398. }
  5399. Statistics.prototype.startRemoteStats = function (peerconnection) {
  5400. if (this.rtpStats) {
  5401. this.rtpStats.stop();
  5402. }
  5403. this.rtpStats = new RTPStats(peerconnection, 200, 2000, this.eventEmitter);
  5404. this.rtpStats.start();
  5405. }
  5406. Statistics.localStats = [];
  5407. Statistics.startLocalStats = function (stream, callback) {
  5408. var localStats = new LocalStats(stream, 200, callback);
  5409. this.localStats.push(localStats);
  5410. localStats.start();
  5411. }
  5412. Statistics.prototype.addAudioLevelListener = function(listener)
  5413. {
  5414. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  5415. }
  5416. Statistics.prototype.removeAudioLevelListener = function(listener)
  5417. {
  5418. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  5419. }
  5420. Statistics.prototype.dispose = function () {
  5421. Statistics.stopAllLocalStats();
  5422. this.stopRemote();
  5423. if(this.eventEmitter)
  5424. this.eventEmitter.removeAllListeners();
  5425. if(eventEmitter)
  5426. eventEmitter.removeAllListeners();
  5427. }
  5428. Statistics.stopAllLocalStats = function () {
  5429. for(var i = 0; i < this.localStats.length; i++)
  5430. this.localStats[i].stop();
  5431. this.localStats = [];
  5432. }
  5433. Statistics.stopLocalStats = function (stream) {
  5434. for(var i = 0; i < Statistics.localStats.length; i++)
  5435. if(Statistics.localStats[i].stream === stream){
  5436. var localStats = Statistics.localStats.splice(i, 1);
  5437. localStats.stop();
  5438. break;
  5439. }
  5440. }
  5441. Statistics.prototype.stopRemote = function () {
  5442. if (this.rtpStats) {
  5443. this.rtpStats.stop();
  5444. this.eventEmitter.emit(StatisticsEvents.STOP);
  5445. this.rtpStats = null;
  5446. }
  5447. };
  5448. /**
  5449. * Obtains audio level reported in the stats for specified peer.
  5450. * @param peerJid full MUC jid of the user for whom we want to obtain last
  5451. * audio level.
  5452. * @param ssrc the SSRC of audio stream for which we want to obtain audio
  5453. * level.
  5454. * @returns {*} a float form 0 to 1 that represents current audio level or
  5455. * <tt>null</tt> if for any reason the value is not available
  5456. * at this time.
  5457. */
  5458. Statistics.prototype.getPeerSSRCAudioLevel = function (peerJid, ssrc) {
  5459. var peerStats = this.rtpStats.jid2stats[peerJid];
  5460. return peerStats ? peerStats.ssrc2AudioLevel[ssrc] : null;
  5461. };
  5462. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  5463. //
  5464. //var statistics = {
  5465. // /**
  5466. // * Indicates that this audio level is for local jid.
  5467. // * @type {string}
  5468. // */
  5469. // LOCAL_JID: 'local',
  5470. //
  5471. // addConnectionStatsListener: function(listener)
  5472. // {
  5473. // eventEmitter.on("statistics.connectionstats", listener);
  5474. // },
  5475. //
  5476. // removeConnectionStatsListener: function(listener)
  5477. // {
  5478. // eventEmitter.removeListener("statistics.connectionstats", listener);
  5479. // },
  5480. //
  5481. //
  5482. // addRemoteStatsStopListener: function(listener)
  5483. // {
  5484. // eventEmitter.on("statistics.stop", listener);
  5485. // },
  5486. //
  5487. // removeRemoteStatsStopListener: function(listener)
  5488. // {
  5489. // eventEmitter.removeListener("statistics.stop", listener);
  5490. // },
  5491. //
  5492. //
  5493. // stopRemoteStatistics: function()
  5494. // {
  5495. // stopRemote();
  5496. // },
  5497. //
  5498. //// Already implemented with the constructor
  5499. // start: function () {
  5500. // APP.RTC.addStreamListener(onStreamCreated,
  5501. // StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  5502. // APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  5503. // //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  5504. // APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  5505. // startRemoteStats(event.peerconnection);
  5506. //// CallStats.init(event);
  5507. // });
  5508. //// APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  5509. //// CallStats.init(session);
  5510. //// });
  5511. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  5512. //// APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  5513. //// CallStats.sendMuteEvent(mute, "audio");
  5514. //// });
  5515. //// APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  5516. //// CallStats.sendSetupFailedEvent();
  5517. //// });
  5518. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  5519. //// APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  5520. //// CallStats.sendMuteEvent(mute, "video");
  5521. //// });
  5522. // }
  5523. //};
  5524. module.exports = Statistics;
  5525. },{"../../service/statistics/Events":83,"../../service/statistics/constants":84,"./LocalStatsCollector.js":22,"./RTPStatsCollector.js":23,"events":43}],25:[function(require,module,exports){
  5526. /**
  5527. /**
  5528. * @const
  5529. */
  5530. var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  5531. /**
  5532. * Hexadecimal digits.
  5533. * @const
  5534. */
  5535. var HEX_DIGITS = '0123456789abcdef';
  5536. /**
  5537. * Generates random int within the range [min, max]
  5538. * @param min the minimum value for the generated number
  5539. * @param max the maximum value for the generated number
  5540. * @returns random int number
  5541. */
  5542. function randomInt(min, max) {
  5543. return Math.floor(Math.random() * (max - min + 1)) + min;
  5544. }
  5545. /**
  5546. * Get random element from array or string.
  5547. * @param {Array|string} arr source
  5548. * @returns array element or string character
  5549. */
  5550. function randomElement(arr) {
  5551. return arr[randomInt(0, arr.length - 1)];
  5552. }
  5553. /**
  5554. * Generate random alphanumeric string.
  5555. * @param {number} length expected string length
  5556. * @returns {string} random string of specified length
  5557. */
  5558. function randomAlphanumStr(length) {
  5559. var result = '';
  5560. for (var i = 0; i < length; i += 1) {
  5561. result += randomElement(ALPHANUM);
  5562. }
  5563. return result;
  5564. }
  5565. /**
  5566. * Exported interface.
  5567. */
  5568. var RandomUtil = {
  5569. /**
  5570. * Returns a random hex digit.
  5571. * @returns {*}
  5572. */
  5573. randomHexDigit: function() {
  5574. return randomElement(HEX_DIGITS);
  5575. },
  5576. /**
  5577. * Returns a random string of hex digits with length 'len'.
  5578. * @param len the length.
  5579. */
  5580. randomHexString: function (len) {
  5581. var ret = '';
  5582. while (len--) {
  5583. ret += this.randomHexDigit();
  5584. }
  5585. return ret;
  5586. },
  5587. randomElement: randomElement,
  5588. randomAlphanumStr: randomAlphanumStr,
  5589. randomInt: randomInt
  5590. };
  5591. module.exports = RandomUtil;
  5592. },{}],26:[function(require,module,exports){
  5593. (function (__filename){
  5594. /* global Strophe, $, $pres, $iq, $msg */
  5595. /* jshint -W101,-W069 */
  5596. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5597. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5598. var Moderator = require("./moderator");
  5599. var EventEmitter = require("events");
  5600. var Recorder = require("./recording");
  5601. var JIBRI_XMLNS = 'http://jitsi.org/protocol/jibri';
  5602. var parser = {
  5603. packet2JSON: function (packet, nodes) {
  5604. var self = this;
  5605. $(packet).children().each(function (index) {
  5606. var tagName = $(this).prop("tagName");
  5607. var node = {
  5608. tagName: tagName
  5609. };
  5610. node.attributes = {};
  5611. $($(this)[0].attributes).each(function( index, attr ) {
  5612. node.attributes[ attr.name ] = attr.value;
  5613. });
  5614. var text = Strophe.getText($(this)[0]);
  5615. if (text) {
  5616. node.value = text;
  5617. }
  5618. node.children = [];
  5619. nodes.push(node);
  5620. self.packet2JSON($(this), node.children);
  5621. });
  5622. },
  5623. JSON2packet: function (nodes, packet) {
  5624. for(var i = 0; i < nodes.length; i++) {
  5625. var node = nodes[i];
  5626. if(!node || node === null){
  5627. continue;
  5628. }
  5629. packet.c(node.tagName, node.attributes);
  5630. if(node.value)
  5631. packet.t(node.value);
  5632. if(node.children)
  5633. this.JSON2packet(node.children, packet);
  5634. packet.up();
  5635. }
  5636. // packet.up();
  5637. }
  5638. };
  5639. /**
  5640. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  5641. * @param pres the presence JSON
  5642. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  5643. */
  5644. function filterNodeFromPresenceJSON(pres, nodeName){
  5645. var res = [];
  5646. for(var i = 0; i < pres.length; i++)
  5647. if(pres[i].tagName === nodeName)
  5648. res.push(pres[i]);
  5649. return res;
  5650. }
  5651. function ChatRoom(connection, jid, password, XMPP, options) {
  5652. this.eventEmitter = new EventEmitter();
  5653. this.xmpp = XMPP;
  5654. this.connection = connection;
  5655. this.roomjid = Strophe.getBareJidFromJid(jid);
  5656. this.myroomjid = jid;
  5657. this.password = password;
  5658. logger.info("Joined MUC as " + this.myroomjid);
  5659. this.members = {};
  5660. this.presMap = {};
  5661. this.presHandlers = {};
  5662. this.joined = false;
  5663. this.role = 'none';
  5664. this.focusMucJid = null;
  5665. this.bridgeIsDown = false;
  5666. this.options = options || {};
  5667. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter);
  5668. this.initPresenceMap();
  5669. this.session = null;
  5670. var self = this;
  5671. this.lastPresences = {};
  5672. this.phoneNumber = null;
  5673. this.phonePin = null;
  5674. }
  5675. ChatRoom.prototype.initPresenceMap = function () {
  5676. this.presMap['to'] = this.myroomjid;
  5677. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  5678. this.presMap["nodes"] = [];
  5679. this.presMap["nodes"].push( {
  5680. "tagName": "user-agent",
  5681. "value": navigator.userAgent,
  5682. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  5683. });
  5684. };
  5685. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  5686. this.presMap["nodes"].push( {
  5687. "tagName": "devices",
  5688. "children": [
  5689. {
  5690. "tagName": "audio",
  5691. "value": devices.audio,
  5692. },
  5693. {
  5694. "tagName": "video",
  5695. "value": devices.video,
  5696. }
  5697. ]
  5698. });
  5699. };
  5700. ChatRoom.prototype.join = function (password) {
  5701. if(password)
  5702. this.password = password;
  5703. var self = this;
  5704. this.moderator.allocateConferenceFocus(function()
  5705. {
  5706. self.sendPresence(true);
  5707. }.bind(this));
  5708. };
  5709. ChatRoom.prototype.sendPresence = function (fromJoin) {
  5710. if (!this.presMap['to'] || (!this.joined && !fromJoin)) {
  5711. // Too early to send presence - not initialized
  5712. return;
  5713. }
  5714. var pres = $pres({to: this.presMap['to'] });
  5715. pres.c('x', {xmlns: this.presMap['xns']});
  5716. if (this.password) {
  5717. pres.c('password').t(this.password).up();
  5718. }
  5719. pres.up();
  5720. // Send XEP-0115 'c' stanza that contains our capabilities info
  5721. if (this.connection.caps) {
  5722. this.connection.caps.node = this.xmpp.options.clientNode;
  5723. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  5724. }
  5725. parser.JSON2packet(this.presMap.nodes, pres);
  5726. this.connection.send(pres);
  5727. };
  5728. ChatRoom.prototype.doLeave = function () {
  5729. logger.log("do leave", this.myroomjid);
  5730. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  5731. this.presMap.length = 0;
  5732. this.connection.send(pres);
  5733. };
  5734. ChatRoom.prototype.createNonAnonymousRoom = function () {
  5735. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  5736. var getForm = $iq({type: 'get', to: this.roomjid})
  5737. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  5738. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5739. var self = this;
  5740. this.connection.sendIQ(getForm, function (form) {
  5741. if (!$(form).find(
  5742. '>query>x[xmlns="jabber:x:data"]' +
  5743. '>field[var="muc#roomconfig_whois"]').length) {
  5744. logger.error('non-anonymous rooms not supported');
  5745. return;
  5746. }
  5747. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  5748. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5749. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5750. formSubmit.c('field', {'var': 'FORM_TYPE'})
  5751. .c('value')
  5752. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5753. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  5754. .c('value').t('anyone').up().up();
  5755. self.connection.sendIQ(formSubmit);
  5756. }, function (error) {
  5757. logger.error("Error getting room configuration form");
  5758. });
  5759. };
  5760. ChatRoom.prototype.onPresence = function (pres) {
  5761. var from = pres.getAttribute('from');
  5762. // Parse roles.
  5763. var member = {};
  5764. member.show = $(pres).find('>show').text();
  5765. member.status = $(pres).find('>status').text();
  5766. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  5767. member.affiliation = tmp.attr('affiliation');
  5768. member.role = tmp.attr('role');
  5769. // Focus recognition
  5770. member.jid = tmp.attr('jid');
  5771. member.isFocus = false;
  5772. if (member.jid
  5773. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") === 0) {
  5774. member.isFocus = true;
  5775. }
  5776. $(pres).find(">x").remove();
  5777. var nodes = [];
  5778. parser.packet2JSON(pres, nodes);
  5779. this.lastPresences[from] = nodes;
  5780. var jibri = null;
  5781. // process nodes to extract data needed for MUC_JOINED and MUC_MEMBER_JOINED
  5782. // events
  5783. for(var i = 0; i < nodes.length; i++)
  5784. {
  5785. var node = nodes[i];
  5786. switch(node.tagName)
  5787. {
  5788. case "nick":
  5789. member.nick = node.value;
  5790. break;
  5791. case "userId":
  5792. member.id = node.value;
  5793. break;
  5794. }
  5795. }
  5796. if (from == this.myroomjid) {
  5797. if (member.affiliation == 'owner'
  5798. && this.role !== member.role) {
  5799. this.role = member.role;
  5800. this.eventEmitter.emit(
  5801. XMPPEvents.LOCAL_ROLE_CHANGED, this.role);
  5802. }
  5803. if (!this.joined) {
  5804. this.joined = true;
  5805. console.log("(TIME) MUC joined:\t", window.performance.now());
  5806. this.eventEmitter.emit(XMPPEvents.MUC_JOINED);
  5807. }
  5808. } else if (this.members[from] === undefined) {
  5809. // new participant
  5810. this.members[from] = member;
  5811. logger.log('entered', from, member);
  5812. if (member.isFocus) {
  5813. this.focusMucJid = from;
  5814. if(!this.recording) {
  5815. this.recording = new Recorder(this.options.recordingType,
  5816. this.eventEmitter, this.connection, this.focusMucJid,
  5817. this.options.jirecon, this.roomjid);
  5818. if(this.lastJibri)
  5819. this.recording.handleJibriPresence(this.lastJibri);
  5820. }
  5821. logger.info("Ignore focus: " + from + ", real JID: " + member.jid);
  5822. }
  5823. else {
  5824. this.eventEmitter.emit(
  5825. XMPPEvents.MUC_MEMBER_JOINED, from, member.nick, member.role);
  5826. }
  5827. } else {
  5828. // Presence update for existing participant
  5829. // Watch role change:
  5830. if (this.members[from].role != member.role) {
  5831. this.members[from].role = member.role;
  5832. this.eventEmitter.emit(
  5833. XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  5834. }
  5835. // store the new display name
  5836. if(member.displayName)
  5837. this.members[from].displayName = member.displayName;
  5838. }
  5839. // after we had fired member or room joined events, lets fire events
  5840. // for the rest info we got in presence
  5841. for(var i = 0; i < nodes.length; i++)
  5842. {
  5843. var node = nodes[i];
  5844. switch(node.tagName)
  5845. {
  5846. case "nick":
  5847. if(!member.isFocus) {
  5848. var displayName = !this.xmpp.options.displayJids
  5849. ? member.nick : Strophe.getResourceFromJid(from);
  5850. if (displayName && displayName.length > 0) {
  5851. this.eventEmitter.emit(
  5852. XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  5853. }
  5854. }
  5855. break;
  5856. case "bridgeIsDown":
  5857. if(!this.bridgeIsDown) {
  5858. this.bridgeIsDown = true;
  5859. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  5860. }
  5861. break;
  5862. case "jibri-recording-status":
  5863. var jibri = node;
  5864. break;
  5865. case "call-control":
  5866. var att = node.attributes;
  5867. if(!att)
  5868. break;
  5869. this.phoneNumber = att.phone || null;
  5870. this.phonePin = att.pin || null;
  5871. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  5872. break;
  5873. default :
  5874. this.processNode(node, from);
  5875. }
  5876. }
  5877. if(!member.isFocus)
  5878. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id);
  5879. // Trigger status message update
  5880. if (member.status) {
  5881. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  5882. }
  5883. if(jibri)
  5884. {
  5885. this.lastJibri = jibri;
  5886. if(this.recording)
  5887. this.recording.handleJibriPresence(jibri);
  5888. }
  5889. };
  5890. ChatRoom.prototype.processNode = function (node, from) {
  5891. if(this.presHandlers[node.tagName])
  5892. this.presHandlers[node.tagName](node, Strophe.getResourceFromJid(from));
  5893. };
  5894. ChatRoom.prototype.sendMessage = function (body, nickname) {
  5895. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5896. msg.c('body', body).up();
  5897. if (nickname) {
  5898. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  5899. }
  5900. this.connection.send(msg);
  5901. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  5902. };
  5903. ChatRoom.prototype.setSubject = function (subject) {
  5904. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5905. msg.c('subject', subject);
  5906. this.connection.send(msg);
  5907. logger.log("topic changed to " + subject);
  5908. };
  5909. ChatRoom.prototype.onParticipantLeft = function (jid) {
  5910. delete this.lastPresences[jid];
  5911. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  5912. this.moderator.onMucMemberLeft(jid);
  5913. };
  5914. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  5915. // room destroyed ?
  5916. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5917. '>destroy').length) {
  5918. var reason;
  5919. var reasonSelect = $(pres).find(
  5920. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5921. '>destroy>reason');
  5922. if (reasonSelect.length) {
  5923. reason = reasonSelect.text();
  5924. }
  5925. this.xmpp.leaveRoom(this.roomjid);
  5926. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  5927. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(from)];
  5928. return true;
  5929. }
  5930. // Status code 110 indicates that this notification is "self-presence".
  5931. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  5932. delete this.members[from];
  5933. this.onParticipantLeft(from);
  5934. }
  5935. // If the status code is 110 this means we're leaving and we would like
  5936. // to remove everyone else from our view, so we trigger the event.
  5937. else if (Object.keys(this.members).length > 1) {
  5938. for (var i in this.members) {
  5939. var member = this.members[i];
  5940. delete this.members[i];
  5941. this.onParticipantLeft(member);
  5942. }
  5943. }
  5944. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  5945. if (this.myroomjid === from) {
  5946. this.xmpp.leaveRoom(this.roomjid);
  5947. this.eventEmitter.emit(XMPPEvents.KICKED);
  5948. }
  5949. }
  5950. };
  5951. ChatRoom.prototype.onMessage = function (msg, from) {
  5952. var nick =
  5953. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  5954. .text() ||
  5955. Strophe.getResourceFromJid(from);
  5956. var txt = $(msg).find('>body').text();
  5957. var type = msg.getAttribute("type");
  5958. if (type == "error") {
  5959. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  5960. $(msg).find('>text').text(), txt);
  5961. return true;
  5962. }
  5963. var subject = $(msg).find('>subject');
  5964. if (subject.length) {
  5965. var subjectText = subject.text();
  5966. if (subjectText || subjectText === "") {
  5967. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  5968. logger.log("Subject is changed to " + subjectText);
  5969. }
  5970. }
  5971. // xep-0203 delay
  5972. var stamp = $(msg).find('>delay').attr('stamp');
  5973. if (!stamp) {
  5974. // or xep-0091 delay, UTC timestamp
  5975. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  5976. if (stamp) {
  5977. // the format is CCYYMMDDThh:mm:ss
  5978. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  5979. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  5980. }
  5981. }
  5982. if (txt) {
  5983. logger.log('chat', nick, txt);
  5984. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  5985. from, nick, txt, this.myroomjid, stamp);
  5986. }
  5987. };
  5988. ChatRoom.prototype.onPresenceError = function (pres, from) {
  5989. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5990. logger.log('on password required', from);
  5991. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  5992. } else if ($(pres).find(
  5993. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5994. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  5995. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  5996. // enter the room by replying with 'not-authorized'. This would
  5997. // result in reconnection from authorized domain.
  5998. // We're either missing Jicofo/Prosody config for anonymous
  5999. // domains or something is wrong.
  6000. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  6001. } else {
  6002. logger.warn('onPresError ', pres);
  6003. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  6004. }
  6005. } else {
  6006. logger.warn('onPresError ', pres);
  6007. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  6008. }
  6009. };
  6010. ChatRoom.prototype.kick = function (jid) {
  6011. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  6012. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  6013. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  6014. .c('reason').t('You have been kicked.').up().up().up();
  6015. this.connection.sendIQ(
  6016. kickIQ,
  6017. function (result) {
  6018. logger.log('Kick participant with jid: ', jid, result);
  6019. },
  6020. function (error) {
  6021. logger.log('Kick participant error: ', error);
  6022. });
  6023. };
  6024. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  6025. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  6026. var ob = this;
  6027. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  6028. function (res) {
  6029. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  6030. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  6031. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  6032. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  6033. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  6034. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  6035. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  6036. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  6037. ob.connection.sendIQ(formsubmit,
  6038. onSuccess,
  6039. onError);
  6040. } else {
  6041. onNotSupported();
  6042. }
  6043. }, onError);
  6044. };
  6045. ChatRoom.prototype.addToPresence = function (key, values) {
  6046. values.tagName = key;
  6047. this.presMap["nodes"].push(values);
  6048. };
  6049. ChatRoom.prototype.removeFromPresence = function (key) {
  6050. for(var i = 0; i < this.presMap.nodes.length; i++)
  6051. {
  6052. if(key === this.presMap.nodes[i].tagName)
  6053. this.presMap.nodes.splice(i, 1);
  6054. }
  6055. };
  6056. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  6057. this.presHandlers[name] = handler;
  6058. };
  6059. ChatRoom.prototype.removePresenceListener = function (name) {
  6060. delete this.presHandlers[name];
  6061. };
  6062. ChatRoom.prototype.isModerator = function () {
  6063. return this.role === 'moderator';
  6064. };
  6065. ChatRoom.prototype.getMemberRole = function (peerJid) {
  6066. if (this.members[peerJid]) {
  6067. return this.members[peerJid].role;
  6068. }
  6069. return null;
  6070. };
  6071. ChatRoom.prototype.setJingleSession = function(session){
  6072. this.session = session;
  6073. this.session.room = this;
  6074. };
  6075. ChatRoom.prototype.removeStream = function (stream, callback) {
  6076. if(!this.session)
  6077. return;
  6078. this.session.removeStream(stream, callback);
  6079. };
  6080. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  6081. if(this.session) {
  6082. // FIXME: will block switchInProgress on true value in case of exception
  6083. this.session.switchStreams(stream, oldStream, callback, isAudio);
  6084. } else {
  6085. // We are done immediately
  6086. logger.warn("No conference handler or conference not started yet");
  6087. callback();
  6088. }
  6089. };
  6090. ChatRoom.prototype.addStream = function (stream, callback) {
  6091. if(this.session) {
  6092. // FIXME: will block switchInProgress on true value in case of exception
  6093. this.session.addStream(stream, callback);
  6094. } else {
  6095. // We are done immediately
  6096. logger.warn("No conference handler or conference not started yet");
  6097. callback();
  6098. }
  6099. };
  6100. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  6101. var self = this;
  6102. var localCallback = function (mute) {
  6103. self.sendVideoInfoPresence(mute);
  6104. if(callback)
  6105. callback(mute);
  6106. };
  6107. if(this.session)
  6108. {
  6109. this.session.setVideoMute(
  6110. mute, localCallback, options);
  6111. }
  6112. else {
  6113. localCallback(mute);
  6114. }
  6115. };
  6116. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  6117. //This will be for remote streams only
  6118. // if (this.forceMuted && !mute) {
  6119. // logger.info("Asking focus for unmute");
  6120. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  6121. // // FIXME: wait for result before resetting muted status
  6122. // this.forceMuted = false;
  6123. // }
  6124. return this.sendAudioInfoPresence(mute, callback);
  6125. };
  6126. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  6127. this.removeFromPresence("audiomuted");
  6128. this.addToPresence("audiomuted",
  6129. {attributes:
  6130. {"audions": "http://jitsi.org/jitmeet/audio"},
  6131. value: mute.toString()});
  6132. };
  6133. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  6134. this.addAudioInfoToPresence(mute);
  6135. if(this.connection) {
  6136. this.sendPresence();
  6137. }
  6138. if(callback)
  6139. callback();
  6140. };
  6141. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  6142. this.removeFromPresence("videomuted");
  6143. this.addToPresence("videomuted",
  6144. {attributes:
  6145. {"videons": "http://jitsi.org/jitmeet/video"},
  6146. value: mute.toString()});
  6147. };
  6148. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  6149. this.addVideoInfoToPresence(mute);
  6150. if(!this.connection)
  6151. return;
  6152. this.sendPresence();
  6153. };
  6154. ChatRoom.prototype.addListener = function(type, listener) {
  6155. this.eventEmitter.on(type, listener);
  6156. };
  6157. ChatRoom.prototype.removeListener = function (type, listener) {
  6158. this.eventEmitter.removeListener(type, listener);
  6159. };
  6160. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  6161. if(this.lastPresences[data.peerjid])
  6162. {
  6163. var pres = this.lastPresences[data.peerjid];
  6164. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  6165. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  6166. data.videomuted = ((videomuted.length > 0
  6167. && videomuted[0]
  6168. && videomuted[0]["value"] === "true")? true : false);
  6169. data.audiomuted = ((audiomuted.length > 0
  6170. && audiomuted[0]
  6171. && audiomuted[0]["value"] === "true")? true : false);
  6172. }
  6173. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  6174. };
  6175. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  6176. if (!this.session)
  6177. return null;
  6178. return this.session.getSsrcOwner(ssrc);
  6179. };
  6180. /**
  6181. * Returns true if the recording is supproted and false if not.
  6182. */
  6183. ChatRoom.prototype.isRecordingSupported = function () {
  6184. if(this.recording)
  6185. return this.recording.isSupported();
  6186. return false;
  6187. };
  6188. /**
  6189. * Returns null if the recording is not supported, "on" if the recording started
  6190. * and "off" if the recording is not started.
  6191. */
  6192. ChatRoom.prototype.getRecordingState = function () {
  6193. if(this.recording)
  6194. return this.recording.getState();
  6195. return "off";
  6196. }
  6197. /**
  6198. * Returns the url of the recorded video.
  6199. */
  6200. ChatRoom.prototype.getRecordingURL = function () {
  6201. if(this.recording)
  6202. return this.recording.getURL();
  6203. return null;
  6204. }
  6205. /**
  6206. * Starts/stops the recording
  6207. * @param token token for authentication
  6208. * @param statusChangeHandler {function} receives the new status as argument.
  6209. */
  6210. ChatRoom.prototype.toggleRecording = function (options, statusChangeHandler) {
  6211. if(this.recording)
  6212. return this.recording.toggleRecording(options, statusChangeHandler);
  6213. return statusChangeHandler("error",
  6214. new Error("The conference is not created yet!"));
  6215. }
  6216. /**
  6217. * Returns true if the SIP calls are supported and false otherwise
  6218. */
  6219. ChatRoom.prototype.isSIPCallingSupported = function () {
  6220. if(this.moderator)
  6221. return this.moderator.isSipGatewayEnabled();
  6222. return false;
  6223. }
  6224. /**
  6225. * Dials a number.
  6226. * @param number the number
  6227. */
  6228. ChatRoom.prototype.dial = function (number) {
  6229. return this.connection.rayo.dial(number, "fromnumber",
  6230. Strophe.getNodeFromJid(this.myroomjid), this.password,
  6231. this.focusMucJid);
  6232. }
  6233. /**
  6234. * Hangup an existing call
  6235. */
  6236. ChatRoom.prototype.hangup = function () {
  6237. return this.connection.rayo.hangup();
  6238. }
  6239. /**
  6240. * Returns the phone number for joining the conference.
  6241. */
  6242. ChatRoom.prototype.getPhoneNumber = function () {
  6243. return this.phoneNumber;
  6244. }
  6245. /**
  6246. * Returns the pin for joining the conference with phone.
  6247. */
  6248. ChatRoom.prototype.getPhonePin = function () {
  6249. return this.phonePin;
  6250. }
  6251. /**
  6252. * Returns the connection state for the current session.
  6253. */
  6254. ChatRoom.prototype.getConnectionState = function () {
  6255. if(!this.session)
  6256. return null;
  6257. return this.session.getIceConnectionState();
  6258. }
  6259. /**
  6260. * Mutes remote participant.
  6261. * @param jid of the participant
  6262. * @param mute
  6263. */
  6264. ChatRoom.prototype.muteParticipant = function (jid, mute) {
  6265. logger.info("set mute", mute);
  6266. var iqToFocus = $iq(
  6267. {to: this.focusMucJid, type: 'set'})
  6268. .c('mute', {
  6269. xmlns: 'http://jitsi.org/jitmeet/audio',
  6270. jid: jid
  6271. })
  6272. .t(mute.toString())
  6273. .up();
  6274. this.connection.sendIQ(
  6275. iqToFocus,
  6276. function (result) {
  6277. logger.log('set mute', result);
  6278. },
  6279. function (error) {
  6280. logger.log('set mute error', error);
  6281. });
  6282. }
  6283. ChatRoom.prototype.onMute = function (iq) {
  6284. var from = iq.getAttribute('from');
  6285. if (from !== this.focusMucJid) {
  6286. logger.warn("Ignored mute from non focus peer");
  6287. return false;
  6288. }
  6289. var mute = $(iq).find('mute');
  6290. if (mute.length) {
  6291. var doMuteAudio = mute.text() === "true";
  6292. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  6293. }
  6294. return true;
  6295. }
  6296. module.exports = ChatRoom;
  6297. }).call(this,"/modules/xmpp/ChatRoom.js")
  6298. },{"../../service/xmpp/XMPPEvents":85,"./moderator":33,"./recording":34,"events":43,"jitsi-meet-logger":47}],27:[function(require,module,exports){
  6299. (function (__filename){
  6300. /*
  6301. * JingleSession provides an API to manage a single Jingle session. We will
  6302. * have different implementations depending on the underlying interface used
  6303. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  6304. */
  6305. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6306. function JingleSession(me, sid, connection, service, eventEmitter) {
  6307. /**
  6308. * Our JID.
  6309. */
  6310. this.me = me;
  6311. /**
  6312. * The Jingle session identifier.
  6313. */
  6314. this.sid = sid;
  6315. /**
  6316. * The XMPP connection.
  6317. */
  6318. this.connection = connection;
  6319. /**
  6320. * The XMPP service.
  6321. */
  6322. this.service = service;
  6323. /**
  6324. * The event emitter.
  6325. */
  6326. this.eventEmitter = eventEmitter;
  6327. /**
  6328. * Whether to use dripping or not. Dripping is sending trickle candidates
  6329. * not one-by-one.
  6330. * Note: currently we do not support 'false'.
  6331. */
  6332. this.usedrip = true;
  6333. /**
  6334. * When dripping is used, stores ICE candidates which are to be sent.
  6335. */
  6336. this.drip_container = [];
  6337. // Media constraints. Is this WebRTC only?
  6338. this.media_constraints = null;
  6339. // ICE servers config (RTCConfiguration?).
  6340. this.ice_config = {};
  6341. // The chat room instance associated with the session.
  6342. this.room = null;
  6343. }
  6344. /**
  6345. * Prepares this object to initiate a session.
  6346. * @param peerjid the JID of the remote peer.
  6347. * @param isInitiator whether we will be the Jingle initiator.
  6348. * @param media_constraints
  6349. * @param ice_config
  6350. */
  6351. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  6352. media_constraints, ice_config) {
  6353. this.media_constraints = media_constraints;
  6354. this.ice_config = ice_config;
  6355. if (this.state !== null) {
  6356. logger.error('attempt to initiate on session ' + this.sid +
  6357. 'in state ' + this.state);
  6358. return;
  6359. }
  6360. this.state = 'pending';
  6361. this.initiator = isInitiator ? this.me : peerjid;
  6362. this.responder = !isInitiator ? this.me : peerjid;
  6363. this.peerjid = peerjid;
  6364. this.doInitialize();
  6365. };
  6366. /**
  6367. * Finishes initialization.
  6368. */
  6369. JingleSession.prototype.doInitialize = function() {};
  6370. /**
  6371. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  6372. * Note: currently only used on transport-info
  6373. */
  6374. JingleSession.prototype.addIceCandidates = function(contents) {};
  6375. /**
  6376. * Handles an 'add-source' event.
  6377. *
  6378. * @param contents an array of Jingle 'content' elements.
  6379. */
  6380. JingleSession.prototype.addSources = function(contents) {};
  6381. /**
  6382. * Handles a 'remove-source' event.
  6383. *
  6384. * @param contents an array of Jingle 'content' elements.
  6385. */
  6386. JingleSession.prototype.removeSources = function(contents) {};
  6387. /**
  6388. * Terminates this Jingle session (stops sending media and closes the streams?)
  6389. */
  6390. JingleSession.prototype.terminate = function() {};
  6391. /**
  6392. * Sends a Jingle session-terminate message to the peer and terminates the
  6393. * session.
  6394. * @param reason
  6395. * @param text
  6396. */
  6397. JingleSession.prototype.sendTerminate = function(reason, text) {};
  6398. /**
  6399. * Handles an offer from the remote peer (prepares to accept a session).
  6400. * @param jingle the 'jingle' XML element.
  6401. */
  6402. JingleSession.prototype.setOffer = function(jingle) {};
  6403. /**
  6404. * Handles an answer from the remote peer (prepares to accept a session).
  6405. * @param jingle the 'jingle' XML element.
  6406. */
  6407. JingleSession.prototype.setAnswer = function(jingle) {};
  6408. module.exports = JingleSession;
  6409. }).call(this,"/modules/xmpp/JingleSession.js")
  6410. },{"jitsi-meet-logger":47}],28:[function(require,module,exports){
  6411. (function (__filename){
  6412. /* jshint -W117 */
  6413. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6414. var JingleSession = require("./JingleSession");
  6415. var TraceablePeerConnection = require("./TraceablePeerConnection");
  6416. var SDPDiffer = require("./SDPDiffer");
  6417. var SDPUtil = require("./SDPUtil");
  6418. var SDP = require("./SDP");
  6419. var async = require("async");
  6420. var transform = require("sdp-transform");
  6421. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  6422. var RTCBrowserType = require("../RTC/RTCBrowserType");
  6423. var RTC = require("../RTC/RTC");
  6424. // Jingle stuff
  6425. function JingleSessionPC(me, sid, connection, service) {
  6426. JingleSession.call(this, me, sid, connection, service);
  6427. this.initiator = null;
  6428. this.responder = null;
  6429. this.peerjid = null;
  6430. this.state = null;
  6431. this.localSDP = null;
  6432. this.remoteSDP = null;
  6433. this.relayedStreams = [];
  6434. this.usetrickle = true;
  6435. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  6436. this.hadstuncandidate = false;
  6437. this.hadturncandidate = false;
  6438. this.lasticecandidate = false;
  6439. this.statsinterval = null;
  6440. this.reason = null;
  6441. this.addssrc = [];
  6442. this.removessrc = [];
  6443. this.pendingop = null;
  6444. this.switchstreams = false;
  6445. this.addingStreams = false;
  6446. this.wait = true;
  6447. /**
  6448. * A map that stores SSRCs of local streams
  6449. * @type {{}} maps media type('audio' or 'video') to SSRC number
  6450. */
  6451. this.localStreamsSSRC = {};
  6452. this.ssrcOwners = {};
  6453. this.ssrcVideoTypes = {};
  6454. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  6455. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  6456. /**
  6457. * The indicator which determines whether the (local) video has been muted
  6458. * in response to a user command in contrast to an automatic decision made
  6459. * by the application logic.
  6460. */
  6461. this.videoMuteByUser = false;
  6462. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  6463. // We start with the queue paused. We resume it when the signaling state is
  6464. // stable and the ice connection state is connected.
  6465. this.modifySourcesQueue.pause();
  6466. }
  6467. //XXX this is badly broken...
  6468. JingleSessionPC.prototype = JingleSession.prototype;
  6469. JingleSessionPC.prototype.constructor = JingleSessionPC;
  6470. JingleSessionPC.prototype.setOffer = function(offer) {
  6471. this.setRemoteDescription(offer, 'offer');
  6472. };
  6473. JingleSessionPC.prototype.setAnswer = function(answer) {
  6474. this.setRemoteDescription(answer, 'answer');
  6475. };
  6476. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  6477. var signalingState = this.peerconnection.signalingState;
  6478. var iceConnectionState = this.peerconnection.iceConnectionState;
  6479. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  6480. this.modifySourcesQueue.resume();
  6481. } else {
  6482. this.modifySourcesQueue.pause();
  6483. }
  6484. };
  6485. JingleSessionPC.prototype.doInitialize = function () {
  6486. var self = this;
  6487. this.hadstuncandidate = false;
  6488. this.hadturncandidate = false;
  6489. this.lasticecandidate = false;
  6490. // True if reconnect is in progress
  6491. this.isreconnect = false;
  6492. // Set to true if the connection was ever stable
  6493. this.wasstable = false;
  6494. this.peerconnection = new TraceablePeerConnection(
  6495. this.connection.jingle.ice_config,
  6496. RTC.getPCConstraints(),
  6497. this);
  6498. this.peerconnection.onicecandidate = function (event) {
  6499. var protocol;
  6500. if (event && event.candidate) {
  6501. protocol = (typeof event.candidate.protocol === 'string')
  6502. ? event.candidate.protocol.toLowerCase() : '';
  6503. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  6504. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  6505. return;
  6506. }
  6507. }
  6508. self.sendIceCandidate(event.candidate);
  6509. };
  6510. this.peerconnection.onaddstream = function (event) {
  6511. if (event.stream.id !== 'default') {
  6512. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  6513. self.remoteStreamAdded(event);
  6514. } else {
  6515. // This is a recvonly stream. Clients that implement Unified Plan,
  6516. // such as Firefox use recvonly "streams/channels/tracks" for
  6517. // receiving remote stream/tracks, as opposed to Plan B where there
  6518. // are only 3 channels: audio, video and data.
  6519. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  6520. }
  6521. };
  6522. this.peerconnection.onremovestream = function (event) {
  6523. // Remove the stream from remoteStreams
  6524. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  6525. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  6526. };
  6527. this.peerconnection.onsignalingstatechange = function (event) {
  6528. if (!(self && self.peerconnection)) return;
  6529. if (self.peerconnection.signalingState === 'stable') {
  6530. self.wasstable = true;
  6531. }
  6532. self.updateModifySourcesQueue();
  6533. };
  6534. /**
  6535. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  6536. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  6537. * RTCPeerConnection.iceConnectionState changes.
  6538. *
  6539. * @param event the event containing information about the change
  6540. */
  6541. this.peerconnection.oniceconnectionstatechange = function (event) {
  6542. if (!(self && self.peerconnection)) return;
  6543. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  6544. ":\t", window.performance.now());
  6545. self.updateModifySourcesQueue();
  6546. switch (self.peerconnection.iceConnectionState) {
  6547. case 'connected':
  6548. // Informs interested parties that the connection has been restored.
  6549. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  6550. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  6551. self.isreconnect = false;
  6552. break;
  6553. case 'disconnected':
  6554. self.isreconnect = true;
  6555. // Informs interested parties that the connection has been interrupted.
  6556. if (self.wasstable)
  6557. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  6558. break;
  6559. case 'failed':
  6560. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6561. break;
  6562. }
  6563. onIceConnectionStateChange(self.sid, self);
  6564. };
  6565. this.peerconnection.onnegotiationneeded = function (event) {
  6566. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  6567. };
  6568. this.relayedStreams.forEach(function(stream) {
  6569. self.peerconnection.addStream(stream);
  6570. });
  6571. };
  6572. function onIceConnectionStateChange(sid, session) {
  6573. switch (session.peerconnection.iceConnectionState) {
  6574. case 'checking':
  6575. session.timeChecking = (new Date()).getTime();
  6576. session.firstconnect = true;
  6577. break;
  6578. case 'completed': // on caller side
  6579. case 'connected':
  6580. if (session.firstconnect) {
  6581. session.firstconnect = false;
  6582. var metadata = {};
  6583. metadata.setupTime
  6584. = (new Date()).getTime() - session.timeChecking;
  6585. session.peerconnection.getStats(function (res) {
  6586. if(res && res.result) {
  6587. res.result().forEach(function (report) {
  6588. if (report.type == 'googCandidatePair' &&
  6589. report.stat('googActiveConnection') == 'true') {
  6590. metadata.localCandidateType
  6591. = report.stat('googLocalCandidateType');
  6592. metadata.remoteCandidateType
  6593. = report.stat('googRemoteCandidateType');
  6594. // log pair as well so we can get nice pie
  6595. // charts
  6596. metadata.candidatePair
  6597. = report.stat('googLocalCandidateType') +
  6598. ';' +
  6599. report.stat('googRemoteCandidateType');
  6600. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  6601. {
  6602. metadata.ipv6 = true;
  6603. }
  6604. }
  6605. });
  6606. }
  6607. });
  6608. }
  6609. break;
  6610. }
  6611. }
  6612. JingleSessionPC.prototype.accept = function () {
  6613. this.state = 'active';
  6614. var pranswer = this.peerconnection.localDescription;
  6615. if (!pranswer || pranswer.type != 'pranswer') {
  6616. return;
  6617. }
  6618. logger.log('going from pranswer to answer');
  6619. if (this.usetrickle) {
  6620. // remove candidates already sent from session-accept
  6621. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  6622. for (var i = 0; i < lines.length; i++) {
  6623. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  6624. }
  6625. }
  6626. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  6627. // FIXME: change any inactive to sendrecv or whatever they were originally
  6628. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  6629. }
  6630. var prsdp = new SDP(pranswer.sdp);
  6631. if (this.webrtcIceTcpDisable) {
  6632. prsdp.removeTcpCandidates = true;
  6633. }
  6634. if (this.webrtcIceUdpDisable) {
  6635. prsdp.removeUdpCandidates = true;
  6636. }
  6637. var accept = $iq({to: this.peerjid,
  6638. type: 'set'})
  6639. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6640. action: 'session-accept',
  6641. initiator: this.initiator,
  6642. responder: this.responder,
  6643. sid: this.sid });
  6644. // FIXME why do we generate session-accept in 3 different places ?
  6645. prsdp.toJingle(
  6646. accept,
  6647. this.initiator == this.me ? 'initiator' : 'responder');
  6648. var sdp = this.peerconnection.localDescription.sdp;
  6649. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  6650. // FIXME: change any inactive to sendrecv or whatever they were originally
  6651. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  6652. }
  6653. var self = this;
  6654. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  6655. function () {
  6656. //logger.log('setLocalDescription success');
  6657. self.setLocalDescription();
  6658. self.connection.sendIQ(accept,
  6659. function () {
  6660. var ack = {};
  6661. ack.source = 'answer';
  6662. $(document).trigger('ack.jingle', [self.sid, ack]);
  6663. },
  6664. function (stanza) {
  6665. var error = ($(stanza).find('error').length) ? {
  6666. code: $(stanza).find('error').attr('code'),
  6667. reason: $(stanza).find('error :first')[0].tagName
  6668. }:{};
  6669. error.source = 'answer';
  6670. JingleSessionPC.onJingleError(self.sid, error);
  6671. },
  6672. 10000);
  6673. },
  6674. function (e) {
  6675. logger.error('setLocalDescription failed', e);
  6676. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6677. }
  6678. );
  6679. };
  6680. JingleSessionPC.prototype.terminate = function (reason) {
  6681. this.state = 'ended';
  6682. this.reason = reason;
  6683. this.peerconnection.close();
  6684. if (this.statsinterval !== null) {
  6685. window.clearInterval(this.statsinterval);
  6686. this.statsinterval = null;
  6687. }
  6688. };
  6689. JingleSessionPC.prototype.active = function () {
  6690. return this.state == 'active';
  6691. };
  6692. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  6693. var self = this;
  6694. if (candidate && !this.lasticecandidate) {
  6695. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  6696. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  6697. if (!(ice && jcand)) {
  6698. logger.error('failed to get ice && jcand');
  6699. return;
  6700. }
  6701. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6702. if (jcand.type === 'srflx') {
  6703. this.hadstuncandidate = true;
  6704. } else if (jcand.type === 'relay') {
  6705. this.hadturncandidate = true;
  6706. }
  6707. if (this.usetrickle) {
  6708. if (this.usedrip) {
  6709. if (this.drip_container.length === 0) {
  6710. // start 20ms callout
  6711. window.setTimeout(function () {
  6712. if (self.drip_container.length === 0) return;
  6713. self.sendIceCandidates(self.drip_container);
  6714. self.drip_container = [];
  6715. }, 20);
  6716. }
  6717. this.drip_container.push(candidate);
  6718. return;
  6719. } else {
  6720. self.sendIceCandidate([candidate]);
  6721. }
  6722. }
  6723. } else {
  6724. //logger.log('sendIceCandidate: last candidate.');
  6725. if (!this.usetrickle) {
  6726. //logger.log('should send full offer now...');
  6727. //FIXME why do we generate session-accept in 3 different places ?
  6728. var init = $iq({to: this.peerjid,
  6729. type: 'set'})
  6730. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6731. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  6732. initiator: this.initiator,
  6733. sid: this.sid});
  6734. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  6735. if (self.webrtcIceTcpDisable) {
  6736. this.localSDP.removeTcpCandidates = true;
  6737. }
  6738. if (self.webrtcIceUdpDisable) {
  6739. this.localSDP.removeUdpCandidates = true;
  6740. }
  6741. var sendJingle = function (ssrc) {
  6742. if(!ssrc)
  6743. ssrc = {};
  6744. self.localSDP.toJingle(
  6745. init,
  6746. self.initiator == self.me ? 'initiator' : 'responder',
  6747. ssrc);
  6748. self.connection.sendIQ(init,
  6749. function () {
  6750. //logger.log('session initiate ack');
  6751. var ack = {};
  6752. ack.source = 'offer';
  6753. $(document).trigger('ack.jingle', [self.sid, ack]);
  6754. },
  6755. function (stanza) {
  6756. self.state = 'error';
  6757. self.peerconnection.close();
  6758. var error = ($(stanza).find('error').length) ? {
  6759. code: $(stanza).find('error').attr('code'),
  6760. reason: $(stanza).find('error :first')[0].tagName,
  6761. }:{};
  6762. error.source = 'offer';
  6763. JingleSessionPC.onJingleError(self.sid, error);
  6764. },
  6765. 10000);
  6766. };
  6767. sendJingle();
  6768. }
  6769. this.lasticecandidate = true;
  6770. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  6771. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  6772. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  6773. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  6774. }
  6775. }
  6776. };
  6777. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  6778. logger.log('sendIceCandidates', candidates);
  6779. var cand = $iq({to: this.peerjid, type: 'set'})
  6780. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6781. action: 'transport-info',
  6782. initiator: this.initiator,
  6783. sid: this.sid});
  6784. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  6785. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  6786. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  6787. if (cands.length > 0) {
  6788. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  6789. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6790. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  6791. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  6792. }).c('transport', ice);
  6793. for (var i = 0; i < cands.length; i++) {
  6794. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  6795. }
  6796. // add fingerprint
  6797. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  6798. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  6799. tmp.required = true;
  6800. cand.c(
  6801. 'fingerprint',
  6802. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  6803. .t(tmp.fingerprint);
  6804. delete tmp.fingerprint;
  6805. cand.attrs(tmp);
  6806. cand.up();
  6807. }
  6808. cand.up(); // transport
  6809. cand.up(); // content
  6810. }
  6811. }
  6812. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  6813. //logger.log('was this the last candidate', this.lasticecandidate);
  6814. this.connection.sendIQ(cand,
  6815. function () {
  6816. var ack = {};
  6817. ack.source = 'transportinfo';
  6818. $(document).trigger('ack.jingle', [this.sid, ack]);
  6819. },
  6820. function (stanza) {
  6821. var error = ($(stanza).find('error').length) ? {
  6822. code: $(stanza).find('error').attr('code'),
  6823. reason: $(stanza).find('error :first')[0].tagName,
  6824. }:{};
  6825. error.source = 'transportinfo';
  6826. JingleSessionPC.onJingleError(this.sid, error);
  6827. },
  6828. 10000);
  6829. };
  6830. JingleSessionPC.prototype.sendOffer = function () {
  6831. //logger.log('sendOffer...');
  6832. var self = this;
  6833. this.peerconnection.createOffer(function (sdp) {
  6834. self.createdOffer(sdp);
  6835. },
  6836. function (e) {
  6837. logger.error('createOffer failed', e);
  6838. },
  6839. this.media_constraints
  6840. );
  6841. };
  6842. // FIXME createdOffer is never used in jitsi-meet
  6843. JingleSessionPC.prototype.createdOffer = function (sdp) {
  6844. //logger.log('createdOffer', sdp);
  6845. var self = this;
  6846. this.localSDP = new SDP(sdp.sdp);
  6847. //this.localSDP.mangle();
  6848. var sendJingle = function () {
  6849. var init = $iq({to: this.peerjid,
  6850. type: 'set'})
  6851. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6852. action: 'session-initiate',
  6853. initiator: this.initiator,
  6854. sid: this.sid});
  6855. self.localSDP.toJingle(
  6856. init,
  6857. this.initiator == this.me ? 'initiator' : 'responder');
  6858. self.connection.sendIQ(init,
  6859. function () {
  6860. var ack = {};
  6861. ack.source = 'offer';
  6862. $(document).trigger('ack.jingle', [self.sid, ack]);
  6863. },
  6864. function (stanza) {
  6865. self.state = 'error';
  6866. self.peerconnection.close();
  6867. var error = ($(stanza).find('error').length) ? {
  6868. code: $(stanza).find('error').attr('code'),
  6869. reason: $(stanza).find('error :first')[0].tagName,
  6870. }:{};
  6871. error.source = 'offer';
  6872. JingleSessionPC.onJingleError(self.sid, error);
  6873. },
  6874. 10000);
  6875. }
  6876. sdp.sdp = this.localSDP.raw;
  6877. this.peerconnection.setLocalDescription(sdp,
  6878. function () {
  6879. if(self.usetrickle)
  6880. {
  6881. sendJingle();
  6882. }
  6883. self.setLocalDescription();
  6884. //logger.log('setLocalDescription success');
  6885. },
  6886. function (e) {
  6887. logger.error('setLocalDescription failed', e);
  6888. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6889. }
  6890. );
  6891. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6892. for (var i = 0; i < cands.length; i++) {
  6893. var cand = SDPUtil.parse_icecandidate(cands[i]);
  6894. if (cand.type == 'srflx') {
  6895. this.hadstuncandidate = true;
  6896. } else if (cand.type == 'relay') {
  6897. this.hadturncandidate = true;
  6898. }
  6899. }
  6900. };
  6901. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  6902. var self = this;
  6903. $(contents).each(function (idx, content) {
  6904. var name = $(content).attr('name');
  6905. var mediaType = this.getAttribute('name');
  6906. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  6907. ssrcs.each(function () {
  6908. var ssrc = this.getAttribute('ssrc');
  6909. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  6910. function () {
  6911. var owner = this.getAttribute('owner');
  6912. self.ssrcOwners[ssrc] = owner;
  6913. }
  6914. );
  6915. });
  6916. });
  6917. };
  6918. /**
  6919. * Returns the SSRC of local audio stream.
  6920. * @param mediaType 'audio' or 'video' media type
  6921. * @returns {*} the SSRC number of local audio or video stream.
  6922. */
  6923. JingleSessionPC.prototype.getLocalSSRC = function (mediaType) {
  6924. return this.localStreamsSSRC[mediaType];
  6925. };
  6926. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  6927. return this.ssrcOwners[ssrc];
  6928. };
  6929. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  6930. //logger.log('setting remote description... ', desctype);
  6931. this.remoteSDP = new SDP('');
  6932. if (this.webrtcIceTcpDisable) {
  6933. this.remoteSDP.removeTcpCandidates = true;
  6934. }
  6935. if (this.webrtcIceUdpDisable) {
  6936. this.remoteSDP.removeUdpCandidates = true;
  6937. }
  6938. this.remoteSDP.fromJingle(elem);
  6939. this.readSsrcInfo($(elem).find(">content"));
  6940. if (this.peerconnection.remoteDescription) {
  6941. logger.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  6942. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  6943. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  6944. for (var i = 0; i < pranswer.media.length; i++) {
  6945. // make sure we have ice ufrag and pwd
  6946. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  6947. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  6948. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  6949. } else {
  6950. logger.warn('no ice ufrag?');
  6951. }
  6952. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  6953. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  6954. } else {
  6955. logger.warn('no ice pwd?');
  6956. }
  6957. }
  6958. // copy over candidates
  6959. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  6960. for (var j = 0; j < lines.length; j++) {
  6961. this.remoteSDP.media[i] += lines[j] + '\r\n';
  6962. }
  6963. }
  6964. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6965. }
  6966. }
  6967. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  6968. this.peerconnection.setRemoteDescription(remotedesc,
  6969. function () {
  6970. //logger.log('setRemoteDescription success');
  6971. },
  6972. function (e) {
  6973. logger.error('setRemoteDescription error', e);
  6974. JingleSessionPC.onJingleFatalError(self, e);
  6975. }
  6976. );
  6977. };
  6978. /**
  6979. * Adds remote ICE candidates to this Jingle session.
  6980. * @param elem An array of Jingle "content" elements?
  6981. */
  6982. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  6983. var self = this;
  6984. if (this.peerconnection.signalingState == 'closed') {
  6985. return;
  6986. }
  6987. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  6988. logger.log('trickle ice candidate arriving before session accept...');
  6989. // create a PRANSWER for setRemoteDescription
  6990. if (!this.remoteSDP) {
  6991. var cobbled = 'v=0\r\n' +
  6992. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  6993. 's=-\r\n' +
  6994. 't=0 0\r\n';
  6995. // first, take some things from the local description
  6996. for (var i = 0; i < this.localSDP.media.length; i++) {
  6997. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  6998. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  6999. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  7000. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  7001. }
  7002. cobbled += 'a=inactive\r\n';
  7003. }
  7004. this.remoteSDP = new SDP(cobbled);
  7005. }
  7006. // then add things like ice and dtls from remote candidate
  7007. elem.each(function () {
  7008. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  7009. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  7010. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  7011. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  7012. var tmp = $(this).find('transport');
  7013. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  7014. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  7015. tmp = $(this).find('transport>fingerprint');
  7016. if (tmp.length) {
  7017. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  7018. } else {
  7019. logger.log('no dtls fingerprint (webrtc issue #1718?)');
  7020. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  7021. }
  7022. break;
  7023. }
  7024. }
  7025. }
  7026. });
  7027. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  7028. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  7029. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  7030. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  7031. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  7032. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  7033. }).length == this.remoteSDP.media.length;
  7034. if (iscomplete) {
  7035. logger.log('setting pranswer');
  7036. try {
  7037. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  7038. function() {
  7039. },
  7040. function(e) {
  7041. logger.log('setRemoteDescription pranswer failed', e.toString());
  7042. });
  7043. } catch (e) {
  7044. logger.error('setting pranswer failed', e);
  7045. }
  7046. } else {
  7047. //logger.log('not yet setting pranswer');
  7048. }
  7049. }
  7050. // operate on each content element
  7051. elem.each(function () {
  7052. // would love to deactivate this, but firefox still requires it
  7053. var idx = -1;
  7054. var i;
  7055. for (i = 0; i < self.remoteSDP.media.length; i++) {
  7056. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  7057. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  7058. idx = i;
  7059. break;
  7060. }
  7061. }
  7062. if (idx == -1) { // fall back to localdescription
  7063. for (i = 0; i < self.localSDP.media.length; i++) {
  7064. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  7065. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  7066. idx = i;
  7067. break;
  7068. }
  7069. }
  7070. }
  7071. var name = $(this).attr('name');
  7072. // TODO: check ice-pwd and ice-ufrag?
  7073. $(this).find('transport>candidate').each(function () {
  7074. var line, candidate;
  7075. var protocol = this.getAttribute('protocol');
  7076. protocol =
  7077. (typeof protocol === 'string') ? protocol.toLowerCase() : '';
  7078. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  7079. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  7080. return;
  7081. }
  7082. line = SDPUtil.candidateFromJingle(this);
  7083. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  7084. sdpMid: name,
  7085. candidate: line});
  7086. try {
  7087. self.peerconnection.addIceCandidate(candidate);
  7088. } catch (e) {
  7089. logger.error('addIceCandidate failed', e.toString(), line);
  7090. self.room.eventEmitter.emit(XMPPEvents.ADD_ICE_CANDIDATE_FAILED,
  7091. err, self.peerconnection);
  7092. }
  7093. });
  7094. });
  7095. };
  7096. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  7097. //logger.log('createAnswer', provisional);
  7098. var self = this;
  7099. this.peerconnection.createAnswer(
  7100. function (sdp) {
  7101. self.createdAnswer(sdp, provisional);
  7102. },
  7103. function (e) {
  7104. logger.error('createAnswer failed', e);
  7105. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7106. },
  7107. this.media_constraints
  7108. );
  7109. };
  7110. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  7111. //logger.log('createAnswer callback');
  7112. var self = this;
  7113. this.localSDP = new SDP(sdp.sdp);
  7114. //this.localSDP.mangle();
  7115. this.usepranswer = provisional === true;
  7116. if (this.usetrickle) {
  7117. if (this.usepranswer) {
  7118. sdp.type = 'pranswer';
  7119. for (var i = 0; i < this.localSDP.media.length; i++) {
  7120. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  7121. }
  7122. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  7123. }
  7124. }
  7125. var self = this;
  7126. var sendJingle = function (ssrcs) {
  7127. // FIXME why do we generate session-accept in 3 different places ?
  7128. var accept = $iq({to: self.peerjid,
  7129. type: 'set'})
  7130. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7131. action: 'session-accept',
  7132. initiator: self.initiator,
  7133. responder: self.responder,
  7134. sid: self.sid });
  7135. if (self.webrtcIceTcpDisable) {
  7136. self.localSDP.removeTcpCandidates = true;
  7137. }
  7138. if (self.webrtcIceUdpDisable) {
  7139. self.localSDP.removeUdpCandidates = true;
  7140. }
  7141. self.localSDP.toJingle(
  7142. accept,
  7143. self.initiator == self.me ? 'initiator' : 'responder',
  7144. ssrcs);
  7145. self.connection.sendIQ(accept,
  7146. function () {
  7147. var ack = {};
  7148. ack.source = 'answer';
  7149. $(document).trigger('ack.jingle', [self.sid, ack]);
  7150. },
  7151. function (stanza) {
  7152. var error = ($(stanza).find('error').length) ? {
  7153. code: $(stanza).find('error').attr('code'),
  7154. reason: $(stanza).find('error :first')[0].tagName,
  7155. }:{};
  7156. error.source = 'answer';
  7157. JingleSessionPC.onJingleError(self.sid, error);
  7158. },
  7159. 10000);
  7160. }
  7161. sdp.sdp = this.localSDP.raw;
  7162. this.peerconnection.setLocalDescription(sdp,
  7163. function () {
  7164. //logger.log('setLocalDescription success');
  7165. if (self.usetrickle && !self.usepranswer) {
  7166. sendJingle();
  7167. }
  7168. self.setLocalDescription();
  7169. },
  7170. function (e) {
  7171. logger.error('setLocalDescription failed', e);
  7172. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7173. }
  7174. );
  7175. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  7176. for (var j = 0; j < cands.length; j++) {
  7177. var cand = SDPUtil.parse_icecandidate(cands[j]);
  7178. if (cand.type == 'srflx') {
  7179. this.hadstuncandidate = true;
  7180. } else if (cand.type == 'relay') {
  7181. this.hadturncandidate = true;
  7182. }
  7183. }
  7184. };
  7185. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  7186. var self = this,
  7187. term = $iq({to: this.peerjid,
  7188. type: 'set'})
  7189. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7190. action: 'session-terminate',
  7191. initiator: this.initiator,
  7192. sid: this.sid})
  7193. .c('reason')
  7194. .c(reason || 'success');
  7195. if (text) {
  7196. term.up().c('text').t(text);
  7197. }
  7198. this.connection.sendIQ(term,
  7199. function () {
  7200. self.peerconnection.close();
  7201. self.peerconnection = null;
  7202. self.terminate();
  7203. var ack = {};
  7204. ack.source = 'terminate';
  7205. $(document).trigger('ack.jingle', [self.sid, ack]);
  7206. },
  7207. function (stanza) {
  7208. var error = ($(stanza).find('error').length) ? {
  7209. code: $(stanza).find('error').attr('code'),
  7210. reason: $(stanza).find('error :first')[0].tagName,
  7211. }:{};
  7212. $(document).trigger('ack.jingle', [self.sid, error]);
  7213. },
  7214. 10000);
  7215. if (this.statsinterval !== null) {
  7216. window.clearInterval(this.statsinterval);
  7217. this.statsinterval = null;
  7218. }
  7219. };
  7220. /**
  7221. * Handles a Jingle source-add message for this Jingle session.
  7222. * @param elem An array of Jingle "content" elements.
  7223. */
  7224. JingleSessionPC.prototype.addSource = function (elem) {
  7225. var self = this;
  7226. // FIXME: dirty waiting
  7227. if (!this.peerconnection.localDescription)
  7228. {
  7229. logger.warn("addSource - localDescription not ready yet")
  7230. setTimeout(function()
  7231. {
  7232. self.addSource(elem);
  7233. },
  7234. 200
  7235. );
  7236. return;
  7237. }
  7238. logger.log('addssrc', new Date().getTime());
  7239. logger.log('ice', this.peerconnection.iceConnectionState);
  7240. this.readSsrcInfo(elem);
  7241. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  7242. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  7243. $(elem).each(function (idx, content) {
  7244. var name = $(content).attr('name');
  7245. var lines = '';
  7246. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  7247. var semantics = this.getAttribute('semantics');
  7248. var ssrcs = $(this).find('>source').map(function () {
  7249. return this.getAttribute('ssrc');
  7250. }).get();
  7251. if (ssrcs.length) {
  7252. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  7253. }
  7254. });
  7255. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  7256. tmp.each(function () {
  7257. var ssrc = $(this).attr('ssrc');
  7258. if(mySdp.containsSSRC(ssrc)){
  7259. /**
  7260. * This happens when multiple participants change their streams at the same time and
  7261. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  7262. * addssrc are scheduled for update IQ. See
  7263. */
  7264. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  7265. return;
  7266. }
  7267. if (sdp.containsSSRC(ssrc)) {
  7268. logger.warn("Source-add request for existing SSRC: " + ssrc);
  7269. return;
  7270. }
  7271. $(this).find('>parameter').each(function () {
  7272. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  7273. if ($(this).attr('value') && $(this).attr('value').length)
  7274. lines += ':' + $(this).attr('value');
  7275. lines += '\r\n';
  7276. });
  7277. });
  7278. sdp.media.forEach(function(media, idx) {
  7279. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  7280. return;
  7281. sdp.media[idx] += lines;
  7282. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  7283. self.addssrc[idx] += lines;
  7284. });
  7285. sdp.raw = sdp.session + sdp.media.join('');
  7286. });
  7287. this.modifySourcesQueue.push(function() {
  7288. // When a source is added and if this is FF, a new channel is allocated
  7289. // for receiving the added source. We need to diffuse the SSRC of this
  7290. // new recvonly channel to the rest of the peers.
  7291. logger.log('modify sources done');
  7292. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7293. logger.log("SDPs", mySdp, newSdp);
  7294. self.notifyMySSRCUpdate(mySdp, newSdp);
  7295. });
  7296. };
  7297. /**
  7298. * Handles a Jingle source-remove message for this Jingle session.
  7299. * @param elem An array of Jingle "content" elements.
  7300. */
  7301. JingleSessionPC.prototype.removeSource = function (elem) {
  7302. var self = this;
  7303. // FIXME: dirty waiting
  7304. if (!this.peerconnection.localDescription) {
  7305. logger.warn("removeSource - localDescription not ready yet");
  7306. setTimeout(function() {
  7307. self.removeSource(elem);
  7308. },
  7309. 200
  7310. );
  7311. return;
  7312. }
  7313. logger.log('removessrc', new Date().getTime());
  7314. logger.log('ice', this.peerconnection.iceConnectionState);
  7315. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  7316. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  7317. $(elem).each(function (idx, content) {
  7318. var name = $(content).attr('name');
  7319. var lines = '';
  7320. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  7321. var semantics = this.getAttribute('semantics');
  7322. var ssrcs = $(this).find('>source').map(function () {
  7323. return this.getAttribute('ssrc');
  7324. }).get();
  7325. if (ssrcs.length) {
  7326. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  7327. }
  7328. });
  7329. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  7330. tmp.each(function () {
  7331. var ssrc = $(this).attr('ssrc');
  7332. // This should never happen, but can be useful for bug detection
  7333. if(mySdp.containsSSRC(ssrc)){
  7334. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  7335. return;
  7336. }
  7337. $(this).find('>parameter').each(function () {
  7338. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  7339. if ($(this).attr('value') && $(this).attr('value').length)
  7340. lines += ':' + $(this).attr('value');
  7341. lines += '\r\n';
  7342. });
  7343. });
  7344. sdp.media.forEach(function(media, idx) {
  7345. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  7346. return;
  7347. sdp.media[idx] += lines;
  7348. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  7349. self.removessrc[idx] += lines;
  7350. });
  7351. sdp.raw = sdp.session + sdp.media.join('');
  7352. });
  7353. this.modifySourcesQueue.push(function() {
  7354. // When a source is removed and if this is FF, the recvonly channel that
  7355. // receives the remote stream is deactivated . We need to diffuse the
  7356. // recvonly SSRC removal to the rest of the peers.
  7357. logger.log('modify sources done');
  7358. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7359. logger.log("SDPs", mySdp, newSdp);
  7360. self.notifyMySSRCUpdate(mySdp, newSdp);
  7361. });
  7362. };
  7363. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  7364. var self = this;
  7365. if (this.peerconnection.signalingState == 'closed') return;
  7366. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  7367. || this.switchstreams || this.addingStreams)){
  7368. // There is nothing to do since scheduled job might have been executed by another succeeding call
  7369. this.setLocalDescription();
  7370. if(successCallback){
  7371. successCallback();
  7372. }
  7373. queueCallback();
  7374. return;
  7375. }
  7376. // Reset switch streams flags
  7377. this.switchstreams = false;
  7378. this.addingStreams = false;
  7379. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  7380. // add sources
  7381. this.addssrc.forEach(function(lines, idx) {
  7382. sdp.media[idx] += lines;
  7383. });
  7384. this.addssrc = [];
  7385. // remove sources
  7386. this.removessrc.forEach(function(lines, idx) {
  7387. lines = lines.split('\r\n');
  7388. lines.pop(); // remove empty last element;
  7389. lines.forEach(function(line) {
  7390. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  7391. });
  7392. });
  7393. this.removessrc = [];
  7394. sdp.raw = sdp.session + sdp.media.join('');
  7395. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  7396. function() {
  7397. if(self.signalingState == 'closed') {
  7398. logger.error("createAnswer attempt on closed state");
  7399. queueCallback("createAnswer attempt on closed state");
  7400. return;
  7401. }
  7402. self.peerconnection.createAnswer(
  7403. function(modifiedAnswer) {
  7404. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  7405. if (self.pendingop !== null) {
  7406. var sdp = new SDP(modifiedAnswer.sdp);
  7407. if (sdp.media.length > 1) {
  7408. switch(self.pendingop) {
  7409. case 'mute':
  7410. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  7411. break;
  7412. case 'unmute':
  7413. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  7414. break;
  7415. }
  7416. sdp.raw = sdp.session + sdp.media.join('');
  7417. modifiedAnswer.sdp = sdp.raw;
  7418. }
  7419. self.pendingop = null;
  7420. }
  7421. // FIXME: pushing down an answer while ice connection state
  7422. // is still checking is bad...
  7423. //logger.log(self.peerconnection.iceConnectionState);
  7424. // trying to work around another chrome bug
  7425. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  7426. self.peerconnection.setLocalDescription(modifiedAnswer,
  7427. function() {
  7428. //logger.log('modified setLocalDescription ok');
  7429. self.setLocalDescription();
  7430. if(successCallback){
  7431. successCallback();
  7432. }
  7433. queueCallback();
  7434. },
  7435. function(error) {
  7436. logger.error('modified setLocalDescription failed', error);
  7437. queueCallback(error);
  7438. }
  7439. );
  7440. },
  7441. function(error) {
  7442. logger.error('modified answer failed', error);
  7443. queueCallback(error);
  7444. }
  7445. );
  7446. },
  7447. function(error) {
  7448. logger.error('modify failed', error);
  7449. queueCallback(error);
  7450. }
  7451. );
  7452. };
  7453. /**
  7454. * Switches video streams.
  7455. * @param newStream new stream that will be used as video of this session.
  7456. * @param oldStream old video stream of this session.
  7457. * @param successCallback callback executed after successful stream switch.
  7458. * @param isAudio whether the streams are audio (if true) or video (if false).
  7459. */
  7460. JingleSessionPC.prototype.switchStreams =
  7461. function (newStream, oldStream, successCallback, isAudio) {
  7462. var self = this;
  7463. var sender, newTrack;
  7464. var senderKind = isAudio ? 'audio' : 'video';
  7465. // Remember SDP to figure out added/removed SSRCs
  7466. var oldSdp = null;
  7467. if (self.peerconnection) {
  7468. if (self.peerconnection.localDescription) {
  7469. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  7470. }
  7471. if (RTCBrowserType.getBrowserType() ===
  7472. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  7473. // On Firefox we don't replace MediaStreams as this messes up the
  7474. // m-lines (which can't be removed in Plan Unified) and brings a lot
  7475. // of complications. Instead, we use the RTPSender and replace just
  7476. // the track.
  7477. // Find the right sender (for audio or video)
  7478. self.peerconnection.peerconnection.getSenders().some(function (s) {
  7479. if (s.track && s.track.kind === senderKind) {
  7480. sender = s;
  7481. return true;
  7482. }
  7483. });
  7484. if (sender) {
  7485. // We assume that our streams have a single track, either audio
  7486. // or video.
  7487. newTrack = isAudio ? newStream.getAudioTracks()[0] :
  7488. newStream.getVideoTracks()[0];
  7489. sender.replaceTrack(newTrack)
  7490. .then(function() {
  7491. console.log("Replaced a track, isAudio=" + isAudio);
  7492. })
  7493. .catch(function(err) {
  7494. console.log("Failed to replace a track: " + err);
  7495. });
  7496. } else {
  7497. console.log("Cannot switch tracks: no RTPSender.");
  7498. }
  7499. } else {
  7500. self.peerconnection.removeStream(oldStream, true);
  7501. if (newStream) {
  7502. self.peerconnection.addStream(newStream);
  7503. }
  7504. }
  7505. }
  7506. // Conference is not active
  7507. if (!oldSdp) {
  7508. successCallback();
  7509. return;
  7510. }
  7511. self.switchstreams = true;
  7512. self.modifySourcesQueue.push(function() {
  7513. logger.log('modify sources done');
  7514. successCallback();
  7515. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7516. logger.log("SDPs", oldSdp, newSdp);
  7517. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7518. });
  7519. };
  7520. /**
  7521. * Adds streams.
  7522. * @param stream new stream that will be added.
  7523. * @param success_callback callback executed after successful stream addition.
  7524. */
  7525. JingleSessionPC.prototype.addStream = function (stream, callback) {
  7526. var self = this;
  7527. // Remember SDP to figure out added/removed SSRCs
  7528. var oldSdp = null;
  7529. if(this.peerconnection) {
  7530. if(this.peerconnection.localDescription) {
  7531. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  7532. }
  7533. if(stream)
  7534. this.peerconnection.addStream(stream);
  7535. }
  7536. // Conference is not active
  7537. if(!oldSdp || !this.peerconnection) {
  7538. callback();
  7539. return;
  7540. }
  7541. this.addingStreams = true;
  7542. this.modifySourcesQueue.push(function() {
  7543. logger.log('modify sources done');
  7544. callback();
  7545. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7546. logger.log("SDPs", oldSdp, newSdp);
  7547. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7548. });
  7549. }
  7550. /**
  7551. * Remove streams.
  7552. * @param stream stream that will be removed.
  7553. * @param success_callback callback executed after successful stream addition.
  7554. */
  7555. JingleSessionPC.prototype.removeStream = function (stream, callback) {
  7556. var self = this;
  7557. // Remember SDP to figure out added/removed SSRCs
  7558. var oldSdp = null;
  7559. if(this.peerconnection) {
  7560. if(this.peerconnection.localDescription) {
  7561. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  7562. }
  7563. if (RTCBrowserType.getBrowserType() ===
  7564. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  7565. var sender = null;
  7566. // On Firefox we don't replace MediaStreams as this messes up the
  7567. // m-lines (which can't be removed in Plan Unified) and brings a lot
  7568. // of complications. Instead, we use the RTPSender and replace just
  7569. // the track.
  7570. var track = null;
  7571. if(stream.getAudioTracks() && stream.getAudioTracks().length) {
  7572. track = stream.getAudioTracks()[0];
  7573. } else if(stream.getVideoTracks() && stream.getVideoTracks().length)
  7574. {
  7575. track = stream.getVideoTracks()[0];
  7576. }
  7577. if(!track) {
  7578. console.log("Cannot switch tracks: no tracks.");
  7579. return;
  7580. }
  7581. // Find the right sender (for audio or video)
  7582. self.peerconnection.peerconnection.getSenders().some(function (s) {
  7583. if (s.track === track) {
  7584. sender = s;
  7585. return true;
  7586. }
  7587. });
  7588. if (sender) {
  7589. self.peerconnection.peerconnection.removeTrack(sender);
  7590. // .then(function() {
  7591. // console.log("Replaced a track, isAudio=" + isAudio);
  7592. // })
  7593. // .catch(function(err) {
  7594. // console.log("Failed to replace a track: " + err);
  7595. // });
  7596. } else {
  7597. console.log("Cannot switch tracks: no RTPSender.");
  7598. }
  7599. } else if(stream)
  7600. this.peerconnection.removeStream(stream);
  7601. }
  7602. // Conference is not active
  7603. if(!oldSdp || !this.peerconnection) {
  7604. callback();
  7605. return;
  7606. }
  7607. this.addingStreams = true;
  7608. this.modifySourcesQueue.push(function() {
  7609. logger.log('modify sources done');
  7610. callback();
  7611. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7612. logger.log("SDPs", oldSdp, newSdp);
  7613. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7614. });
  7615. }
  7616. /**
  7617. * Figures out added/removed ssrcs and send update IQs.
  7618. * @param old_sdp SDP object for old description.
  7619. * @param new_sdp SDP object for new description.
  7620. */
  7621. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  7622. if (!(this.peerconnection.signalingState == 'stable' &&
  7623. this.peerconnection.iceConnectionState == 'connected')){
  7624. logger.log("Too early to send updates");
  7625. return;
  7626. }
  7627. // send source-remove IQ.
  7628. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  7629. var remove = $iq({to: this.peerjid, type: 'set'})
  7630. .c('jingle', {
  7631. xmlns: 'urn:xmpp:jingle:1',
  7632. action: 'source-remove',
  7633. initiator: this.initiator,
  7634. sid: this.sid
  7635. }
  7636. );
  7637. var removed = sdpDiffer.toJingle(remove);
  7638. if (removed && remove) {
  7639. logger.info("Sending source-remove", remove);
  7640. this.connection.sendIQ(remove,
  7641. function (res) {
  7642. logger.info('got remove result', res);
  7643. },
  7644. function (err) {
  7645. logger.error('got remove error', err);
  7646. }
  7647. );
  7648. } else {
  7649. logger.log('removal not necessary');
  7650. }
  7651. // send source-add IQ.
  7652. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  7653. var add = $iq({to: this.peerjid, type: 'set'})
  7654. .c('jingle', {
  7655. xmlns: 'urn:xmpp:jingle:1',
  7656. action: 'source-add',
  7657. initiator: this.initiator,
  7658. sid: this.sid
  7659. }
  7660. );
  7661. var added = sdpDiffer.toJingle(add);
  7662. if (added && add) {
  7663. logger.info("Sending source-add", add);
  7664. this.connection.sendIQ(add,
  7665. function (res) {
  7666. logger.info('got add result', res);
  7667. },
  7668. function (err) {
  7669. logger.error('got add error', err);
  7670. }
  7671. );
  7672. } else {
  7673. logger.log('addition not necessary');
  7674. }
  7675. };
  7676. /**
  7677. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  7678. *
  7679. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  7680. * tracks; otherwise, <tt>false</tt>
  7681. * @param callback a function to be invoked with <tt>mute</tt> after all video
  7682. * tracks have been enabled/disabled. The function may, optionally, return
  7683. * another function which is to be invoked after the whole mute/unmute operation
  7684. * has completed successfully.
  7685. * @param options an object which specifies optional arguments such as the
  7686. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  7687. * specifies whether the method was initiated in response to a user command (in
  7688. * contrast to an automatic decision made by the application logic)
  7689. */
  7690. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  7691. var byUser;
  7692. if (options) {
  7693. byUser = options.byUser;
  7694. if (typeof byUser === 'undefined') {
  7695. byUser = true;
  7696. }
  7697. } else {
  7698. byUser = true;
  7699. }
  7700. // The user's command to mute the (local) video takes precedence over any
  7701. // automatic decision made by the application logic.
  7702. if (byUser) {
  7703. this.videoMuteByUser = mute;
  7704. } else if (this.videoMuteByUser) {
  7705. return;
  7706. }
  7707. this.hardMuteVideo(mute);
  7708. var self = this;
  7709. var oldSdp = null;
  7710. if(self.peerconnection) {
  7711. if(self.peerconnection.localDescription) {
  7712. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  7713. }
  7714. }
  7715. this.modifySourcesQueue.push(function() {
  7716. logger.log('modify sources done');
  7717. callback(mute);
  7718. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7719. logger.log("SDPs", oldSdp, newSdp);
  7720. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7721. });
  7722. };
  7723. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  7724. this.pendingop = muted ? 'mute' : 'unmute';
  7725. };
  7726. JingleSessionPC.prototype.sendMute = function (muted, content) {
  7727. var info = $iq({to: this.peerjid,
  7728. type: 'set'})
  7729. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7730. action: 'session-info',
  7731. initiator: this.initiator,
  7732. sid: this.sid });
  7733. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  7734. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  7735. if (content) {
  7736. info.attrs({'name': content});
  7737. }
  7738. this.connection.send(info);
  7739. };
  7740. JingleSessionPC.prototype.sendRinging = function () {
  7741. var info = $iq({to: this.peerjid,
  7742. type: 'set'})
  7743. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7744. action: 'session-info',
  7745. initiator: this.initiator,
  7746. sid: this.sid });
  7747. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  7748. this.connection.send(info);
  7749. };
  7750. JingleSessionPC.prototype.getStats = function (interval) {
  7751. var self = this;
  7752. var recv = {audio: 0, video: 0};
  7753. var lost = {audio: 0, video: 0};
  7754. var lastrecv = {audio: 0, video: 0};
  7755. var lastlost = {audio: 0, video: 0};
  7756. var loss = {audio: 0, video: 0};
  7757. var delta = {audio: 0, video: 0};
  7758. this.statsinterval = window.setInterval(function () {
  7759. if (self && self.peerconnection && self.peerconnection.getStats) {
  7760. self.peerconnection.getStats(function (stats) {
  7761. var results = stats.result();
  7762. // TODO: there are so much statistics you can get from this..
  7763. for (var i = 0; i < results.length; ++i) {
  7764. if (results[i].type == 'ssrc') {
  7765. var packetsrecv = results[i].stat('packetsReceived');
  7766. var packetslost = results[i].stat('packetsLost');
  7767. if (packetsrecv && packetslost) {
  7768. packetsrecv = parseInt(packetsrecv, 10);
  7769. packetslost = parseInt(packetslost, 10);
  7770. if (results[i].stat('googFrameRateReceived')) {
  7771. lastlost.video = lost.video;
  7772. lastrecv.video = recv.video;
  7773. recv.video = packetsrecv;
  7774. lost.video = packetslost;
  7775. } else {
  7776. lastlost.audio = lost.audio;
  7777. lastrecv.audio = recv.audio;
  7778. recv.audio = packetsrecv;
  7779. lost.audio = packetslost;
  7780. }
  7781. }
  7782. }
  7783. }
  7784. delta.audio = recv.audio - lastrecv.audio;
  7785. delta.video = recv.video - lastrecv.video;
  7786. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  7787. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  7788. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  7789. });
  7790. }
  7791. }, interval || 3000);
  7792. return this.statsinterval;
  7793. };
  7794. JingleSessionPC.onJingleError = function (session, error)
  7795. {
  7796. logger.error("Jingle error", error);
  7797. }
  7798. JingleSessionPC.onJingleFatalError = function (session, error)
  7799. {
  7800. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7801. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  7802. }
  7803. JingleSessionPC.prototype.setLocalDescription = function () {
  7804. var self = this;
  7805. var newssrcs = [];
  7806. if(!this.peerconnection.localDescription)
  7807. return;
  7808. var session = transform.parse(this.peerconnection.localDescription.sdp);
  7809. var i;
  7810. session.media.forEach(function (media) {
  7811. if (media.ssrcs && media.ssrcs.length > 0) {
  7812. // TODO(gp) maybe exclude FID streams?
  7813. media.ssrcs.forEach(function (ssrc) {
  7814. if (ssrc.attribute !== 'cname') {
  7815. return;
  7816. }
  7817. newssrcs.push({
  7818. 'ssrc': ssrc.id,
  7819. 'type': media.type
  7820. });
  7821. // FIXME allows for only one SSRC per media type
  7822. self.localStreamsSSRC[media.type] = ssrc.id;
  7823. });
  7824. }
  7825. });
  7826. logger.log('new ssrcs', newssrcs);
  7827. // Bind us as local SSRCs owner
  7828. if (newssrcs.length > 0) {
  7829. for (i = 0; i < newssrcs.length; i++) {
  7830. var ssrc = newssrcs[i].ssrc;
  7831. var myJid = self.me;
  7832. self.ssrcOwners[ssrc] = myJid;
  7833. }
  7834. }
  7835. }
  7836. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7837. JingleSessionPC.prototype.sendKeyframe = function () {
  7838. var pc = this.peerconnection;
  7839. logger.log('sendkeyframe', pc.iceConnectionState);
  7840. if (pc.iceConnectionState !== 'connected') return; // safe...
  7841. var self = this;
  7842. pc.setRemoteDescription(
  7843. pc.remoteDescription,
  7844. function () {
  7845. pc.createAnswer(
  7846. function (modifiedAnswer) {
  7847. pc.setLocalDescription(
  7848. modifiedAnswer,
  7849. function () {
  7850. // noop
  7851. },
  7852. function (error) {
  7853. logger.log('triggerKeyframe setLocalDescription failed', error);
  7854. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  7855. }
  7856. );
  7857. },
  7858. function (error) {
  7859. logger.log('triggerKeyframe createAnswer failed', error);
  7860. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  7861. }
  7862. );
  7863. },
  7864. function (error) {
  7865. logger.log('triggerKeyframe setRemoteDescription failed', error);
  7866. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  7867. }
  7868. );
  7869. }
  7870. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  7871. var self = this;
  7872. var thessrc;
  7873. var streamId = RTC.getStreamID(data.stream);
  7874. // look up an associated JID for a stream id
  7875. if (!streamId) {
  7876. logger.error("No stream ID for", data.stream);
  7877. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  7878. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  7879. var ssrclines = this.peerconnection.remoteDescription?
  7880. SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:') : [];
  7881. ssrclines = ssrclines.filter(function (line) {
  7882. // NOTE(gp) previously we filtered on the mslabel, but that property
  7883. // is not always present.
  7884. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  7885. if (RTCBrowserType.isTemasysPluginUsed()) {
  7886. return ((line.indexOf('mslabel:' + streamId) !== -1));
  7887. } else {
  7888. return ((line.indexOf('msid:' + streamId) !== -1));
  7889. }
  7890. });
  7891. if (ssrclines.length) {
  7892. thessrc = ssrclines[0].substring(7).split(' ')[0];
  7893. if (!self.ssrcOwners[thessrc]) {
  7894. logger.error("No SSRC owner known for: " + thessrc);
  7895. return;
  7896. }
  7897. data.peerjid = self.ssrcOwners[thessrc];
  7898. logger.log('associated jid', self.ssrcOwners[thessrc]);
  7899. } else {
  7900. logger.error("No SSRC lines for ", streamId);
  7901. }
  7902. }
  7903. this.room.remoteStreamAdded(data, this.sid, thessrc);
  7904. var isVideo = data.stream.getVideoTracks().length > 0;
  7905. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7906. if (isVideo &&
  7907. data.peerjid && this.peerjid === data.peerjid &&
  7908. data.stream.getVideoTracks().length === 0 &&
  7909. RTC.localVideo.getTracks().length > 0) {
  7910. window.setTimeout(function () {
  7911. self.sendKeyframe();
  7912. }, 3000);
  7913. }
  7914. }
  7915. /**
  7916. * Returns the ice connection state for the peer connection.
  7917. * @returns the ice connection state for the peer connection.
  7918. */
  7919. JingleSessionPC.prototype.getIceConnectionState = function () {
  7920. return this.peerconnection.iceConnectionState;
  7921. }
  7922. module.exports = JingleSessionPC;
  7923. }).call(this,"/modules/xmpp/JingleSessionPC.js")
  7924. },{"../../service/xmpp/XMPPEvents":85,"../RTC/RTC":16,"../RTC/RTCBrowserType":17,"./JingleSession":27,"./SDP":29,"./SDPDiffer":30,"./SDPUtil":31,"./TraceablePeerConnection":32,"async":42,"jitsi-meet-logger":47,"sdp-transform":75}],29:[function(require,module,exports){
  7925. (function (__filename){
  7926. /* jshint -W117 */
  7927. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7928. var SDPUtil = require("./SDPUtil");
  7929. // SDP STUFF
  7930. function SDP(sdp) {
  7931. /**
  7932. * Whether or not to remove TCP ice candidates when translating from/to jingle.
  7933. * @type {boolean}
  7934. */
  7935. this.removeTcpCandidates = false;
  7936. /**
  7937. * Whether or not to remove UDP ice candidates when translating from/to jingle.
  7938. * @type {boolean}
  7939. */
  7940. this.removeUdpCandidates = false;
  7941. this.media = sdp.split('\r\nm=');
  7942. for (var i = 1; i < this.media.length; i++) {
  7943. this.media[i] = 'm=' + this.media[i];
  7944. if (i != this.media.length - 1) {
  7945. this.media[i] += '\r\n';
  7946. }
  7947. }
  7948. this.session = this.media.shift() + '\r\n';
  7949. this.raw = this.session + this.media.join('');
  7950. }
  7951. /**
  7952. * Returns map of MediaChannel mapped per channel idx.
  7953. */
  7954. SDP.prototype.getMediaSsrcMap = function() {
  7955. var self = this;
  7956. var media_ssrcs = {};
  7957. var tmp;
  7958. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  7959. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  7960. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  7961. var media = {
  7962. mediaindex: mediaindex,
  7963. mid: mid,
  7964. ssrcs: {},
  7965. ssrcGroups: []
  7966. };
  7967. media_ssrcs[mediaindex] = media;
  7968. tmp.forEach(function (line) {
  7969. var linessrc = line.substring(7).split(' ')[0];
  7970. // allocate new ChannelSsrc
  7971. if(!media.ssrcs[linessrc]) {
  7972. media.ssrcs[linessrc] = {
  7973. ssrc: linessrc,
  7974. lines: []
  7975. };
  7976. }
  7977. media.ssrcs[linessrc].lines.push(line);
  7978. });
  7979. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  7980. tmp.forEach(function(line){
  7981. var idx = line.indexOf(' ');
  7982. var semantics = line.substr(0, idx).substr(13);
  7983. var ssrcs = line.substr(14 + semantics.length).split(' ');
  7984. if (ssrcs.length) {
  7985. media.ssrcGroups.push({
  7986. semantics: semantics,
  7987. ssrcs: ssrcs
  7988. });
  7989. }
  7990. });
  7991. }
  7992. return media_ssrcs;
  7993. };
  7994. /**
  7995. * Returns <tt>true</tt> if this SDP contains given SSRC.
  7996. * @param ssrc the ssrc to check.
  7997. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  7998. */
  7999. SDP.prototype.containsSSRC = function (ssrc) {
  8000. // FIXME this code is really strange - improve it if you can
  8001. var medias = this.getMediaSsrcMap();
  8002. var result = false;
  8003. Object.keys(medias).forEach(function (mediaindex) {
  8004. if (result)
  8005. return;
  8006. if (medias[mediaindex].ssrcs[ssrc]) {
  8007. result = true;
  8008. }
  8009. });
  8010. return result;
  8011. };
  8012. // remove iSAC and CN from SDP
  8013. SDP.prototype.mangle = function () {
  8014. var i, j, mline, lines, rtpmap, newdesc;
  8015. for (i = 0; i < this.media.length; i++) {
  8016. lines = this.media[i].split('\r\n');
  8017. lines.pop(); // remove empty last element
  8018. mline = SDPUtil.parse_mline(lines.shift());
  8019. if (mline.media != 'audio')
  8020. continue;
  8021. newdesc = '';
  8022. mline.fmt.length = 0;
  8023. for (j = 0; j < lines.length; j++) {
  8024. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  8025. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  8026. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  8027. continue;
  8028. mline.fmt.push(rtpmap.id);
  8029. newdesc += lines[j] + '\r\n';
  8030. } else {
  8031. newdesc += lines[j] + '\r\n';
  8032. }
  8033. }
  8034. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  8035. this.media[i] += newdesc;
  8036. }
  8037. this.raw = this.session + this.media.join('');
  8038. };
  8039. // remove lines matching prefix from session section
  8040. SDP.prototype.removeSessionLines = function(prefix) {
  8041. var self = this;
  8042. var lines = SDPUtil.find_lines(this.session, prefix);
  8043. lines.forEach(function(line) {
  8044. self.session = self.session.replace(line + '\r\n', '');
  8045. });
  8046. this.raw = this.session + this.media.join('');
  8047. return lines;
  8048. }
  8049. // remove lines matching prefix from a media section specified by mediaindex
  8050. // TODO: non-numeric mediaindex could match mid
  8051. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  8052. var self = this;
  8053. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  8054. lines.forEach(function(line) {
  8055. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  8056. });
  8057. this.raw = this.session + this.media.join('');
  8058. return lines;
  8059. }
  8060. // add content's to a jingle element
  8061. SDP.prototype.toJingle = function (elem, thecreator) {
  8062. // logger.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  8063. var self = this;
  8064. var i, j, k, mline, ssrc, rtpmap, tmp, lines;
  8065. // new bundle plan
  8066. if (SDPUtil.find_line(this.session, 'a=group:')) {
  8067. lines = SDPUtil.find_lines(this.session, 'a=group:');
  8068. for (i = 0; i < lines.length; i++) {
  8069. tmp = lines[i].split(' ');
  8070. var semantics = tmp.shift().substr(8);
  8071. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  8072. for (j = 0; j < tmp.length; j++) {
  8073. elem.c('content', {name: tmp[j]}).up();
  8074. }
  8075. elem.up();
  8076. }
  8077. }
  8078. for (i = 0; i < this.media.length; i++) {
  8079. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  8080. if (!(mline.media === 'audio' ||
  8081. mline.media === 'video' ||
  8082. mline.media === 'application'))
  8083. {
  8084. continue;
  8085. }
  8086. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  8087. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  8088. } else {
  8089. ssrc = false;
  8090. }
  8091. elem.c('content', {creator: thecreator, name: mline.media});
  8092. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  8093. // prefer identifier from a=mid if present
  8094. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  8095. elem.attrs({ name: mid });
  8096. }
  8097. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length) {
  8098. elem.c('description',
  8099. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  8100. media: mline.media });
  8101. if (ssrc) {
  8102. elem.attrs({ssrc: ssrc});
  8103. }
  8104. for (j = 0; j < mline.fmt.length; j++) {
  8105. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  8106. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  8107. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  8108. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  8109. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  8110. for (k = 0; k < tmp.length; k++) {
  8111. elem.c('parameter', tmp[k]).up();
  8112. }
  8113. }
  8114. this.rtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  8115. elem.up();
  8116. }
  8117. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  8118. elem.c('encryption', {required: 1});
  8119. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  8120. crypto.forEach(function(line) {
  8121. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  8122. });
  8123. elem.up(); // end of encryption
  8124. }
  8125. if (ssrc) {
  8126. // new style mapping
  8127. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8128. // FIXME: group by ssrc and support multiple different ssrcs
  8129. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  8130. if(ssrclines.length > 0) {
  8131. ssrclines.forEach(function (line) {
  8132. var idx = line.indexOf(' ');
  8133. var linessrc = line.substr(0, idx).substr(7);
  8134. if (linessrc != ssrc) {
  8135. elem.up();
  8136. ssrc = linessrc;
  8137. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8138. }
  8139. var kv = line.substr(idx + 1);
  8140. elem.c('parameter');
  8141. if (kv.indexOf(':') == -1) {
  8142. elem.attrs({ name: kv });
  8143. } else {
  8144. var k = kv.split(':', 2)[0];
  8145. elem.attrs({ name: k });
  8146. var v = kv.split(':', 2)[1];
  8147. v = SDPUtil.filter_special_chars(v);
  8148. elem.attrs({ value: v });
  8149. }
  8150. elem.up();
  8151. });
  8152. } else {
  8153. elem.up();
  8154. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8155. elem.c('parameter');
  8156. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  8157. elem.up();
  8158. var msid = null;
  8159. if(mline.media == "audio")
  8160. {
  8161. msid = APP.RTC.localAudio._getId();
  8162. }
  8163. else
  8164. {
  8165. msid = APP.RTC.localVideo._getId();
  8166. }
  8167. if(msid != null)
  8168. {
  8169. msid = SDPUtil.filter_special_chars(msid);
  8170. elem.c('parameter');
  8171. elem.attrs({name: "msid", value:msid});
  8172. elem.up();
  8173. elem.c('parameter');
  8174. elem.attrs({name: "mslabel", value:msid});
  8175. elem.up();
  8176. elem.c('parameter');
  8177. elem.attrs({name: "label", value:msid});
  8178. elem.up();
  8179. }
  8180. }
  8181. elem.up();
  8182. // XEP-0339 handle ssrc-group attributes
  8183. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  8184. ssrc_group_lines.forEach(function(line) {
  8185. var idx = line.indexOf(' ');
  8186. var semantics = line.substr(0, idx).substr(13);
  8187. var ssrcs = line.substr(14 + semantics.length).split(' ');
  8188. if (ssrcs.length) {
  8189. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8190. ssrcs.forEach(function(ssrc) {
  8191. elem.c('source', { ssrc: ssrc })
  8192. .up();
  8193. });
  8194. elem.up();
  8195. }
  8196. });
  8197. }
  8198. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  8199. elem.c('rtcp-mux').up();
  8200. }
  8201. // XEP-0293 -- map a=rtcp-fb:*
  8202. this.rtcpFbToJingle(i, elem, '*');
  8203. // XEP-0294
  8204. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  8205. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  8206. for (j = 0; j < lines.length; j++) {
  8207. tmp = SDPUtil.parse_extmap(lines[j]);
  8208. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  8209. uri: tmp.uri,
  8210. id: tmp.value });
  8211. if (tmp.hasOwnProperty('direction')) {
  8212. switch (tmp.direction) {
  8213. case 'sendonly':
  8214. elem.attrs({senders: 'responder'});
  8215. break;
  8216. case 'recvonly':
  8217. elem.attrs({senders: 'initiator'});
  8218. break;
  8219. case 'sendrecv':
  8220. elem.attrs({senders: 'both'});
  8221. break;
  8222. case 'inactive':
  8223. elem.attrs({senders: 'none'});
  8224. break;
  8225. }
  8226. }
  8227. // TODO: handle params
  8228. elem.up();
  8229. }
  8230. }
  8231. elem.up(); // end of description
  8232. }
  8233. // map ice-ufrag/pwd, dtls fingerprint, candidates
  8234. this.transportToJingle(i, elem);
  8235. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  8236. elem.attrs({senders: 'both'});
  8237. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  8238. elem.attrs({senders: 'initiator'});
  8239. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  8240. elem.attrs({senders: 'responder'});
  8241. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  8242. elem.attrs({senders: 'none'});
  8243. }
  8244. if (mline.port == '0') {
  8245. // estos hack to reject an m-line
  8246. elem.attrs({senders: 'rejected'});
  8247. }
  8248. elem.up(); // end of content
  8249. }
  8250. elem.up();
  8251. return elem;
  8252. };
  8253. SDP.prototype.transportToJingle = function (mediaindex, elem) {
  8254. var tmp, sctpmap, sctpAttrs, fingerprints;
  8255. var self = this;
  8256. elem.c('transport');
  8257. // XEP-0343 DTLS/SCTP
  8258. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  8259. {
  8260. sctpmap = SDPUtil.find_line(
  8261. this.media[mediaindex], 'a=sctpmap:', self.session);
  8262. if (sctpmap)
  8263. {
  8264. sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  8265. elem.c('sctpmap',
  8266. {
  8267. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  8268. number: sctpAttrs[0], /* SCTP port */
  8269. protocol: sctpAttrs[1] /* protocol */
  8270. });
  8271. // Optional stream count attribute
  8272. if (sctpAttrs.length > 2)
  8273. elem.attrs({ streams: sctpAttrs[2]});
  8274. elem.up();
  8275. }
  8276. }
  8277. // XEP-0320
  8278. fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  8279. fingerprints.forEach(function(line) {
  8280. tmp = SDPUtil.parse_fingerprint(line);
  8281. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  8282. elem.c('fingerprint').t(tmp.fingerprint);
  8283. delete tmp.fingerprint;
  8284. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  8285. if (line) {
  8286. tmp.setup = line.substr(8);
  8287. }
  8288. elem.attrs(tmp);
  8289. elem.up(); // end of fingerprint
  8290. });
  8291. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  8292. if (tmp) {
  8293. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  8294. elem.attrs(tmp);
  8295. // XEP-0176
  8296. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  8297. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  8298. lines.forEach(function (line) {
  8299. var candidate = SDPUtil.candidateToJingle(line);
  8300. var protocol = (candidate &&
  8301. typeof candidate.protocol === 'string')
  8302. ? candidate.protocol.toLowerCase() : '';
  8303. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  8304. (self.removeUdpCandidates && protocol === 'udp')) {
  8305. return;
  8306. }
  8307. elem.c('candidate', candidate).up();
  8308. });
  8309. }
  8310. }
  8311. elem.up(); // end of transport
  8312. }
  8313. SDP.prototype.rtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  8314. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  8315. lines.forEach(function (line) {
  8316. var tmp = SDPUtil.parse_rtcpfb(line);
  8317. if (tmp.type == 'trr-int') {
  8318. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  8319. elem.up();
  8320. } else {
  8321. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  8322. if (tmp.params.length > 0) {
  8323. elem.attrs({'subtype': tmp.params[0]});
  8324. }
  8325. elem.up();
  8326. }
  8327. });
  8328. };
  8329. SDP.prototype.rtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  8330. var media = '';
  8331. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  8332. if (tmp.length) {
  8333. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  8334. if (tmp.attr('value')) {
  8335. media += tmp.attr('value');
  8336. } else {
  8337. media += '0';
  8338. }
  8339. media += '\r\n';
  8340. }
  8341. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  8342. tmp.each(function () {
  8343. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  8344. if ($(this).attr('subtype')) {
  8345. media += ' ' + $(this).attr('subtype');
  8346. }
  8347. media += '\r\n';
  8348. });
  8349. return media;
  8350. };
  8351. // construct an SDP from a jingle stanza
  8352. SDP.prototype.fromJingle = function (jingle) {
  8353. var self = this;
  8354. this.raw = 'v=0\r\n' +
  8355. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  8356. 's=-\r\n' +
  8357. 't=0 0\r\n';
  8358. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  8359. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  8360. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  8361. var contents = $(group).find('>content').map(function (idx, content) {
  8362. return content.getAttribute('name');
  8363. }).get();
  8364. if (contents.length > 0) {
  8365. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  8366. }
  8367. });
  8368. }
  8369. this.session = this.raw;
  8370. jingle.find('>content').each(function () {
  8371. var m = self.jingle2media($(this));
  8372. self.media.push(m);
  8373. });
  8374. // reconstruct msid-semantic -- apparently not necessary
  8375. /*
  8376. var msid = SDPUtil.parse_ssrc(this.raw);
  8377. if (msid.hasOwnProperty('mslabel')) {
  8378. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  8379. }
  8380. */
  8381. this.raw = this.session + this.media.join('');
  8382. };
  8383. // translate a jingle content element into an an SDP media part
  8384. SDP.prototype.jingle2media = function (content) {
  8385. var media = '',
  8386. desc = content.find('description'),
  8387. ssrc = desc.attr('ssrc'),
  8388. self = this,
  8389. tmp;
  8390. var sctp = content.find(
  8391. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  8392. tmp = { media: desc.attr('media') };
  8393. tmp.port = '1';
  8394. if (content.attr('senders') == 'rejected') {
  8395. // estos hack to reject an m-line.
  8396. tmp.port = '0';
  8397. }
  8398. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  8399. if (sctp.length)
  8400. tmp.proto = 'DTLS/SCTP';
  8401. else
  8402. tmp.proto = 'RTP/SAVPF';
  8403. } else {
  8404. tmp.proto = 'RTP/AVPF';
  8405. }
  8406. if (!sctp.length) {
  8407. tmp.fmt = desc.find('payload-type').map(
  8408. function () { return this.getAttribute('id'); }).get();
  8409. media += SDPUtil.build_mline(tmp) + '\r\n';
  8410. } else {
  8411. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  8412. media += 'a=sctpmap:' + sctp.attr('number') +
  8413. ' ' + sctp.attr('protocol');
  8414. var streamCount = sctp.attr('streams');
  8415. if (streamCount)
  8416. media += ' ' + streamCount + '\r\n';
  8417. else
  8418. media += '\r\n';
  8419. }
  8420. media += 'c=IN IP4 0.0.0.0\r\n';
  8421. if (!sctp.length)
  8422. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  8423. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  8424. if (tmp.length) {
  8425. if (tmp.attr('ufrag')) {
  8426. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  8427. }
  8428. if (tmp.attr('pwd')) {
  8429. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  8430. }
  8431. tmp.find('>fingerprint').each(function () {
  8432. // FIXME: check namespace at some point
  8433. media += 'a=fingerprint:' + this.getAttribute('hash');
  8434. media += ' ' + $(this).text();
  8435. media += '\r\n';
  8436. if (this.getAttribute('setup')) {
  8437. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  8438. }
  8439. });
  8440. }
  8441. switch (content.attr('senders')) {
  8442. case 'initiator':
  8443. media += 'a=sendonly\r\n';
  8444. break;
  8445. case 'responder':
  8446. media += 'a=recvonly\r\n';
  8447. break;
  8448. case 'none':
  8449. media += 'a=inactive\r\n';
  8450. break;
  8451. case 'both':
  8452. media += 'a=sendrecv\r\n';
  8453. break;
  8454. }
  8455. media += 'a=mid:' + content.attr('name') + '\r\n';
  8456. // <description><rtcp-mux/></description>
  8457. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  8458. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  8459. if (desc.find('rtcp-mux').length) {
  8460. media += 'a=rtcp-mux\r\n';
  8461. }
  8462. if (desc.find('encryption').length) {
  8463. desc.find('encryption>crypto').each(function () {
  8464. media += 'a=crypto:' + this.getAttribute('tag');
  8465. media += ' ' + this.getAttribute('crypto-suite');
  8466. media += ' ' + this.getAttribute('key-params');
  8467. if (this.getAttribute('session-params')) {
  8468. media += ' ' + this.getAttribute('session-params');
  8469. }
  8470. media += '\r\n';
  8471. });
  8472. }
  8473. desc.find('payload-type').each(function () {
  8474. media += SDPUtil.build_rtpmap(this) + '\r\n';
  8475. if ($(this).find('>parameter').length) {
  8476. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  8477. media += $(this).find('parameter').map(function () {
  8478. return (this.getAttribute('name')
  8479. ? (this.getAttribute('name') + '=') : '') +
  8480. this.getAttribute('value');
  8481. }).get().join('; ');
  8482. media += '\r\n';
  8483. }
  8484. // xep-0293
  8485. media += self.rtcpFbFromJingle($(this), this.getAttribute('id'));
  8486. });
  8487. // xep-0293
  8488. media += self.rtcpFbFromJingle(desc, '*');
  8489. // xep-0294
  8490. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  8491. tmp.each(function () {
  8492. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  8493. });
  8494. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  8495. var protocol = this.getAttribute('protocol');
  8496. protocol = (typeof protocol === 'string') ? protocol.toLowerCase(): '';
  8497. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  8498. (self.removeUdpCandidates && protocol === 'udp')) {
  8499. return;
  8500. }
  8501. media += SDPUtil.candidateFromJingle(this);
  8502. });
  8503. // XEP-0339 handle ssrc-group attributes
  8504. content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8505. var semantics = this.getAttribute('semantics');
  8506. var ssrcs = $(this).find('>source').map(function() {
  8507. return this.getAttribute('ssrc');
  8508. }).get();
  8509. if (ssrcs.length) {
  8510. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8511. }
  8512. });
  8513. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  8514. tmp.each(function () {
  8515. var ssrc = this.getAttribute('ssrc');
  8516. $(this).find('>parameter').each(function () {
  8517. var name = this.getAttribute('name');
  8518. var value = this.getAttribute('value');
  8519. value = SDPUtil.filter_special_chars(value);
  8520. media += 'a=ssrc:' + ssrc + ' ' + name;
  8521. if (value && value.length)
  8522. media += ':' + value;
  8523. media += '\r\n';
  8524. });
  8525. });
  8526. return media;
  8527. };
  8528. module.exports = SDP;
  8529. }).call(this,"/modules/xmpp/SDP.js")
  8530. },{"./SDPUtil":31,"jitsi-meet-logger":47}],30:[function(require,module,exports){
  8531. var SDPUtil = require("./SDPUtil");
  8532. function SDPDiffer(mySDP, otherSDP)
  8533. {
  8534. this.mySDP = mySDP;
  8535. this.otherSDP = otherSDP;
  8536. }
  8537. /**
  8538. * Returns map of MediaChannel that contains media contained in
  8539. * 'mySDP', but not contained in 'otherSdp'. Mapped by channel idx.
  8540. */
  8541. SDPDiffer.prototype.getNewMedia = function() {
  8542. // this could be useful in Array.prototype.
  8543. function arrayEquals(array) {
  8544. // if the other array is a falsy value, return
  8545. if (!array)
  8546. return false;
  8547. // compare lengths - can save a lot of time
  8548. if (this.length != array.length)
  8549. return false;
  8550. for (var i = 0, l=this.length; i < l; i++) {
  8551. // Check if we have nested arrays
  8552. if (this[i] instanceof Array && array[i] instanceof Array) {
  8553. // recurse into the nested arrays
  8554. if (!this[i].equals(array[i]))
  8555. return false;
  8556. }
  8557. else if (this[i] != array[i]) {
  8558. // Warning - two different object instances will never be
  8559. // equal: {x:20} != {x:20}
  8560. return false;
  8561. }
  8562. }
  8563. return true;
  8564. }
  8565. var myMedias = this.mySDP.getMediaSsrcMap();
  8566. var othersMedias = this.otherSDP.getMediaSsrcMap();
  8567. var newMedia = {};
  8568. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  8569. var myMedia = myMedias[othersMediaIdx];
  8570. var othersMedia = othersMedias[othersMediaIdx];
  8571. if(!myMedia && othersMedia) {
  8572. // Add whole channel
  8573. newMedia[othersMediaIdx] = othersMedia;
  8574. return;
  8575. }
  8576. // Look for new ssrcs across the channel
  8577. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  8578. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  8579. // Allocate channel if we've found ssrc that doesn't exist in
  8580. // our channel
  8581. if(!newMedia[othersMediaIdx]){
  8582. newMedia[othersMediaIdx] = {
  8583. mediaindex: othersMedia.mediaindex,
  8584. mid: othersMedia.mid,
  8585. ssrcs: {},
  8586. ssrcGroups: []
  8587. };
  8588. }
  8589. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  8590. }
  8591. });
  8592. // Look for new ssrc groups across the channels
  8593. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  8594. // try to match the other ssrc-group with an ssrc-group of ours
  8595. var matched = false;
  8596. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  8597. var mySsrcGroup = myMedia.ssrcGroups[i];
  8598. if (otherSsrcGroup.semantics == mySsrcGroup.semantics &&
  8599. arrayEquals.apply(otherSsrcGroup.ssrcs,
  8600. [mySsrcGroup.ssrcs])) {
  8601. matched = true;
  8602. break;
  8603. }
  8604. }
  8605. if (!matched) {
  8606. // Allocate channel if we've found an ssrc-group that doesn't
  8607. // exist in our channel
  8608. if(!newMedia[othersMediaIdx]){
  8609. newMedia[othersMediaIdx] = {
  8610. mediaindex: othersMedia.mediaindex,
  8611. mid: othersMedia.mid,
  8612. ssrcs: {},
  8613. ssrcGroups: []
  8614. };
  8615. }
  8616. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  8617. }
  8618. });
  8619. });
  8620. return newMedia;
  8621. };
  8622. /**
  8623. * TODO: document!
  8624. */
  8625. SDPDiffer.prototype.toJingle = function(modify) {
  8626. var sdpMediaSsrcs = this.getNewMedia();
  8627. var modified = false;
  8628. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  8629. modified = true;
  8630. var media = sdpMediaSsrcs[mediaindex];
  8631. modify.c('content', {name: media.mid});
  8632. modify.c('description',
  8633. {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  8634. // FIXME: not completely sure this operates on blocks and / or handles
  8635. // different ssrcs correctly
  8636. // generate sources from lines
  8637. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  8638. var mediaSsrc = media.ssrcs[ssrcNum];
  8639. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8640. modify.attrs({ssrc: mediaSsrc.ssrc});
  8641. // iterate over ssrc lines
  8642. mediaSsrc.lines.forEach(function (line) {
  8643. var idx = line.indexOf(' ');
  8644. var kv = line.substr(idx + 1);
  8645. modify.c('parameter');
  8646. if (kv.indexOf(':') == -1) {
  8647. modify.attrs({ name: kv });
  8648. } else {
  8649. var nv = kv.split(':', 2);
  8650. var name = nv[0];
  8651. var value = SDPUtil.filter_special_chars(nv[1]);
  8652. modify.attrs({ name: name });
  8653. modify.attrs({ value: value });
  8654. }
  8655. modify.up(); // end of parameter
  8656. });
  8657. modify.up(); // end of source
  8658. });
  8659. // generate source groups from lines
  8660. media.ssrcGroups.forEach(function(ssrcGroup) {
  8661. if (ssrcGroup.ssrcs.length) {
  8662. modify.c('ssrc-group', {
  8663. semantics: ssrcGroup.semantics,
  8664. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  8665. });
  8666. ssrcGroup.ssrcs.forEach(function (ssrc) {
  8667. modify.c('source', { ssrc: ssrc })
  8668. .up(); // end of source
  8669. });
  8670. modify.up(); // end of ssrc-group
  8671. }
  8672. });
  8673. modify.up(); // end of description
  8674. modify.up(); // end of content
  8675. });
  8676. return modified;
  8677. };
  8678. module.exports = SDPDiffer;
  8679. },{"./SDPUtil":31}],31:[function(require,module,exports){
  8680. (function (__filename){
  8681. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8682. var RTCBrowserType = require("../RTC/RTCBrowserType");
  8683. SDPUtil = {
  8684. filter_special_chars: function (text) {
  8685. return text.replace(/[\\\/\{,\}\+]/g, "");
  8686. },
  8687. iceparams: function (mediadesc, sessiondesc) {
  8688. var data = null;
  8689. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  8690. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  8691. data = {
  8692. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  8693. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  8694. };
  8695. }
  8696. return data;
  8697. },
  8698. parse_iceufrag: function (line) {
  8699. return line.substring(12);
  8700. },
  8701. build_iceufrag: function (frag) {
  8702. return 'a=ice-ufrag:' + frag;
  8703. },
  8704. parse_icepwd: function (line) {
  8705. return line.substring(10);
  8706. },
  8707. build_icepwd: function (pwd) {
  8708. return 'a=ice-pwd:' + pwd;
  8709. },
  8710. parse_mid: function (line) {
  8711. return line.substring(6);
  8712. },
  8713. parse_mline: function (line) {
  8714. var parts = line.substring(2).split(' '),
  8715. data = {};
  8716. data.media = parts.shift();
  8717. data.port = parts.shift();
  8718. data.proto = parts.shift();
  8719. if (parts[parts.length - 1] === '') { // trailing whitespace
  8720. parts.pop();
  8721. }
  8722. data.fmt = parts;
  8723. return data;
  8724. },
  8725. build_mline: function (mline) {
  8726. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  8727. },
  8728. parse_rtpmap: function (line) {
  8729. var parts = line.substring(9).split(' '),
  8730. data = {};
  8731. data.id = parts.shift();
  8732. parts = parts[0].split('/');
  8733. data.name = parts.shift();
  8734. data.clockrate = parts.shift();
  8735. data.channels = parts.length ? parts.shift() : '1';
  8736. return data;
  8737. },
  8738. /**
  8739. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  8740. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  8741. * @returns [SCTP port number, protocol, streams]
  8742. */
  8743. parse_sctpmap: function (line)
  8744. {
  8745. var parts = line.substring(10).split(' ');
  8746. var sctpPort = parts[0];
  8747. var protocol = parts[1];
  8748. // Stream count is optional
  8749. var streamCount = parts.length > 2 ? parts[2] : null;
  8750. return [sctpPort, protocol, streamCount];// SCTP port
  8751. },
  8752. build_rtpmap: function (el) {
  8753. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  8754. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  8755. line += '/' + el.getAttribute('channels');
  8756. }
  8757. return line;
  8758. },
  8759. parse_crypto: function (line) {
  8760. var parts = line.substring(9).split(' '),
  8761. data = {};
  8762. data.tag = parts.shift();
  8763. data['crypto-suite'] = parts.shift();
  8764. data['key-params'] = parts.shift();
  8765. if (parts.length) {
  8766. data['session-params'] = parts.join(' ');
  8767. }
  8768. return data;
  8769. },
  8770. parse_fingerprint: function (line) { // RFC 4572
  8771. var parts = line.substring(14).split(' '),
  8772. data = {};
  8773. data.hash = parts.shift();
  8774. data.fingerprint = parts.shift();
  8775. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  8776. return data;
  8777. },
  8778. parse_fmtp: function (line) {
  8779. var parts = line.split(' '),
  8780. i, key, value,
  8781. data = [];
  8782. parts.shift();
  8783. parts = parts.join(' ').split(';');
  8784. for (i = 0; i < parts.length; i++) {
  8785. key = parts[i].split('=')[0];
  8786. while (key.length && key[0] == ' ') {
  8787. key = key.substring(1);
  8788. }
  8789. value = parts[i].split('=')[1];
  8790. if (key && value) {
  8791. data.push({name: key, value: value});
  8792. } else if (key) {
  8793. // rfc 4733 (DTMF) style stuff
  8794. data.push({name: '', value: key});
  8795. }
  8796. }
  8797. return data;
  8798. },
  8799. parse_icecandidate: function (line) {
  8800. var candidate = {},
  8801. elems = line.split(' ');
  8802. candidate.foundation = elems[0].substring(12);
  8803. candidate.component = elems[1];
  8804. candidate.protocol = elems[2].toLowerCase();
  8805. candidate.priority = elems[3];
  8806. candidate.ip = elems[4];
  8807. candidate.port = elems[5];
  8808. // elems[6] => "typ"
  8809. candidate.type = elems[7];
  8810. candidate.generation = 0; // default value, may be overwritten below
  8811. for (var i = 8; i < elems.length; i += 2) {
  8812. switch (elems[i]) {
  8813. case 'raddr':
  8814. candidate['rel-addr'] = elems[i + 1];
  8815. break;
  8816. case 'rport':
  8817. candidate['rel-port'] = elems[i + 1];
  8818. break;
  8819. case 'generation':
  8820. candidate.generation = elems[i + 1];
  8821. break;
  8822. case 'tcptype':
  8823. candidate.tcptype = elems[i + 1];
  8824. break;
  8825. default: // TODO
  8826. logger.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  8827. }
  8828. }
  8829. candidate.network = '1';
  8830. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  8831. return candidate;
  8832. },
  8833. build_icecandidate: function (cand) {
  8834. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  8835. line += ' ';
  8836. switch (cand.type) {
  8837. case 'srflx':
  8838. case 'prflx':
  8839. case 'relay':
  8840. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  8841. line += 'raddr';
  8842. line += ' ';
  8843. line += cand['rel-addr'];
  8844. line += ' ';
  8845. line += 'rport';
  8846. line += ' ';
  8847. line += cand['rel-port'];
  8848. line += ' ';
  8849. }
  8850. break;
  8851. }
  8852. if (cand.hasOwnAttribute('tcptype')) {
  8853. line += 'tcptype';
  8854. line += ' ';
  8855. line += cand.tcptype;
  8856. line += ' ';
  8857. }
  8858. line += 'generation';
  8859. line += ' ';
  8860. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  8861. return line;
  8862. },
  8863. parse_ssrc: function (desc) {
  8864. // proprietary mapping of a=ssrc lines
  8865. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  8866. // and parse according to that
  8867. var lines = desc.split('\r\n'),
  8868. data = {};
  8869. for (var i = 0; i < lines.length; i++) {
  8870. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  8871. var idx = lines[i].indexOf(' ');
  8872. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  8873. }
  8874. }
  8875. return data;
  8876. },
  8877. parse_rtcpfb: function (line) {
  8878. var parts = line.substr(10).split(' ');
  8879. var data = {};
  8880. data.pt = parts.shift();
  8881. data.type = parts.shift();
  8882. data.params = parts;
  8883. return data;
  8884. },
  8885. parse_extmap: function (line) {
  8886. var parts = line.substr(9).split(' ');
  8887. var data = {};
  8888. data.value = parts.shift();
  8889. if (data.value.indexOf('/') != -1) {
  8890. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  8891. data.value = data.value.substr(0, data.value.indexOf('/'));
  8892. } else {
  8893. data.direction = 'both';
  8894. }
  8895. data.uri = parts.shift();
  8896. data.params = parts;
  8897. return data;
  8898. },
  8899. find_line: function (haystack, needle, sessionpart) {
  8900. var lines = haystack.split('\r\n');
  8901. for (var i = 0; i < lines.length; i++) {
  8902. if (lines[i].substring(0, needle.length) == needle) {
  8903. return lines[i];
  8904. }
  8905. }
  8906. if (!sessionpart) {
  8907. return false;
  8908. }
  8909. // search session part
  8910. lines = sessionpart.split('\r\n');
  8911. for (var j = 0; j < lines.length; j++) {
  8912. if (lines[j].substring(0, needle.length) == needle) {
  8913. return lines[j];
  8914. }
  8915. }
  8916. return false;
  8917. },
  8918. find_lines: function (haystack, needle, sessionpart) {
  8919. var lines = haystack.split('\r\n'),
  8920. needles = [];
  8921. for (var i = 0; i < lines.length; i++) {
  8922. if (lines[i].substring(0, needle.length) == needle)
  8923. needles.push(lines[i]);
  8924. }
  8925. if (needles.length || !sessionpart) {
  8926. return needles;
  8927. }
  8928. // search session part
  8929. lines = sessionpart.split('\r\n');
  8930. for (var j = 0; j < lines.length; j++) {
  8931. if (lines[j].substring(0, needle.length) == needle) {
  8932. needles.push(lines[j]);
  8933. }
  8934. }
  8935. return needles;
  8936. },
  8937. candidateToJingle: function (line) {
  8938. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  8939. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  8940. if (line.indexOf('candidate:') === 0) {
  8941. line = 'a=' + line;
  8942. } else if (line.substring(0, 12) != 'a=candidate:') {
  8943. logger.log('parseCandidate called with a line that is not a candidate line');
  8944. logger.log(line);
  8945. return null;
  8946. }
  8947. if (line.substring(line.length - 2) == '\r\n') // chomp it
  8948. line = line.substring(0, line.length - 2);
  8949. var candidate = {},
  8950. elems = line.split(' '),
  8951. i;
  8952. if (elems[6] != 'typ') {
  8953. logger.log('did not find typ in the right place');
  8954. logger.log(line);
  8955. return null;
  8956. }
  8957. candidate.foundation = elems[0].substring(12);
  8958. candidate.component = elems[1];
  8959. candidate.protocol = elems[2].toLowerCase();
  8960. candidate.priority = elems[3];
  8961. candidate.ip = elems[4];
  8962. candidate.port = elems[5];
  8963. // elems[6] => "typ"
  8964. candidate.type = elems[7];
  8965. candidate.generation = '0'; // default, may be overwritten below
  8966. for (i = 8; i < elems.length; i += 2) {
  8967. switch (elems[i]) {
  8968. case 'raddr':
  8969. candidate['rel-addr'] = elems[i + 1];
  8970. break;
  8971. case 'rport':
  8972. candidate['rel-port'] = elems[i + 1];
  8973. break;
  8974. case 'generation':
  8975. candidate.generation = elems[i + 1];
  8976. break;
  8977. case 'tcptype':
  8978. candidate.tcptype = elems[i + 1];
  8979. break;
  8980. default: // TODO
  8981. logger.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  8982. }
  8983. }
  8984. candidate.network = '1';
  8985. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  8986. return candidate;
  8987. },
  8988. candidateFromJingle: function (cand) {
  8989. var line = 'a=candidate:';
  8990. line += cand.getAttribute('foundation');
  8991. line += ' ';
  8992. line += cand.getAttribute('component');
  8993. line += ' ';
  8994. var protocol = cand.getAttribute('protocol');
  8995. // use tcp candidates for FF
  8996. if (RTCBrowserType.isFirefox() && protocol.toLowerCase() == 'ssltcp') {
  8997. protocol = 'tcp';
  8998. }
  8999. line += protocol; //.toUpperCase(); // chrome M23 doesn't like this
  9000. line += ' ';
  9001. line += cand.getAttribute('priority');
  9002. line += ' ';
  9003. line += cand.getAttribute('ip');
  9004. line += ' ';
  9005. line += cand.getAttribute('port');
  9006. line += ' ';
  9007. line += 'typ';
  9008. line += ' ' + cand.getAttribute('type');
  9009. line += ' ';
  9010. switch (cand.getAttribute('type')) {
  9011. case 'srflx':
  9012. case 'prflx':
  9013. case 'relay':
  9014. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  9015. line += 'raddr';
  9016. line += ' ';
  9017. line += cand.getAttribute('rel-addr');
  9018. line += ' ';
  9019. line += 'rport';
  9020. line += ' ';
  9021. line += cand.getAttribute('rel-port');
  9022. line += ' ';
  9023. }
  9024. break;
  9025. }
  9026. if (protocol.toLowerCase() == 'tcp') {
  9027. line += 'tcptype';
  9028. line += ' ';
  9029. line += cand.getAttribute('tcptype');
  9030. line += ' ';
  9031. }
  9032. line += 'generation';
  9033. line += ' ';
  9034. line += cand.getAttribute('generation') || '0';
  9035. return line + '\r\n';
  9036. }
  9037. };
  9038. module.exports = SDPUtil;
  9039. }).call(this,"/modules/xmpp/SDPUtil.js")
  9040. },{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":47}],32:[function(require,module,exports){
  9041. (function (__filename){
  9042. /* global $ */
  9043. var RTC = require('../RTC/RTC');
  9044. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9045. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  9046. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9047. function TraceablePeerConnection(ice_config, constraints, session) {
  9048. var self = this;
  9049. this.session = session;
  9050. var RTCPeerConnectionType = null;
  9051. if (RTCBrowserType.isFirefox()) {
  9052. RTCPeerConnectionType = mozRTCPeerConnection;
  9053. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  9054. RTCPeerConnectionType = RTCPeerConnection;
  9055. } else {
  9056. RTCPeerConnectionType = webkitRTCPeerConnection;
  9057. }
  9058. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  9059. this.updateLog = [];
  9060. this.stats = {};
  9061. this.statsinterval = null;
  9062. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  9063. var Interop = require('sdp-interop').Interop;
  9064. this.interop = new Interop();
  9065. var Simulcast = require('sdp-simulcast');
  9066. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  9067. // override as desired
  9068. this.trace = function (what, info) {
  9069. /*logger.warn('WTRACE', what, info);
  9070. if (info && RTCBrowserType.isIExplorer()) {
  9071. if (info.length > 1024) {
  9072. logger.warn('WTRACE', what, info.substr(1024));
  9073. }
  9074. if (info.length > 2048) {
  9075. logger.warn('WTRACE', what, info.substr(2048));
  9076. }
  9077. }*/
  9078. self.updateLog.push({
  9079. time: new Date(),
  9080. type: what,
  9081. value: info || ""
  9082. });
  9083. };
  9084. this.onicecandidate = null;
  9085. this.peerconnection.onicecandidate = function (event) {
  9086. // FIXME: this causes stack overflow with Temasys Plugin
  9087. if (!RTCBrowserType.isTemasysPluginUsed())
  9088. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  9089. if (self.onicecandidate !== null) {
  9090. self.onicecandidate(event);
  9091. }
  9092. };
  9093. this.onaddstream = null;
  9094. this.peerconnection.onaddstream = function (event) {
  9095. self.trace('onaddstream', event.stream.id);
  9096. if (self.onaddstream !== null) {
  9097. self.onaddstream(event);
  9098. }
  9099. };
  9100. this.onremovestream = null;
  9101. this.peerconnection.onremovestream = function (event) {
  9102. self.trace('onremovestream', event.stream.id);
  9103. if (self.onremovestream !== null) {
  9104. self.onremovestream(event);
  9105. }
  9106. };
  9107. this.onsignalingstatechange = null;
  9108. this.peerconnection.onsignalingstatechange = function (event) {
  9109. self.trace('onsignalingstatechange', self.signalingState);
  9110. if (self.onsignalingstatechange !== null) {
  9111. self.onsignalingstatechange(event);
  9112. }
  9113. };
  9114. this.oniceconnectionstatechange = null;
  9115. this.peerconnection.oniceconnectionstatechange = function (event) {
  9116. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  9117. if (self.oniceconnectionstatechange !== null) {
  9118. self.oniceconnectionstatechange(event);
  9119. }
  9120. };
  9121. this.onnegotiationneeded = null;
  9122. this.peerconnection.onnegotiationneeded = function (event) {
  9123. self.trace('onnegotiationneeded');
  9124. if (self.onnegotiationneeded !== null) {
  9125. self.onnegotiationneeded(event);
  9126. }
  9127. };
  9128. self.ondatachannel = null;
  9129. this.peerconnection.ondatachannel = function (event) {
  9130. self.trace('ondatachannel', event);
  9131. if (self.ondatachannel !== null) {
  9132. self.ondatachannel(event);
  9133. }
  9134. };
  9135. // XXX: do all non-firefox browsers which we support also support this?
  9136. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  9137. this.statsinterval = window.setInterval(function() {
  9138. self.peerconnection.getStats(function(stats) {
  9139. var results = stats.result();
  9140. var now = new Date();
  9141. for (var i = 0; i < results.length; ++i) {
  9142. results[i].names().forEach(function (name) {
  9143. var id = results[i].id + '-' + name;
  9144. if (!self.stats[id]) {
  9145. self.stats[id] = {
  9146. startTime: now,
  9147. endTime: now,
  9148. values: [],
  9149. times: []
  9150. };
  9151. }
  9152. self.stats[id].values.push(results[i].stat(name));
  9153. self.stats[id].times.push(now.getTime());
  9154. if (self.stats[id].values.length > self.maxstats) {
  9155. self.stats[id].values.shift();
  9156. self.stats[id].times.shift();
  9157. }
  9158. self.stats[id].endTime = now;
  9159. });
  9160. }
  9161. });
  9162. }, 1000);
  9163. }
  9164. }
  9165. /**
  9166. * Returns a string representation of a SessionDescription object.
  9167. */
  9168. var dumpSDP = function(description) {
  9169. if (typeof description === 'undefined' || description == null) {
  9170. return '';
  9171. }
  9172. return 'type: ' + description.type + '\r\n' + description.sdp;
  9173. };
  9174. var insertRecvOnlySSRC = function (desc) {
  9175. if (typeof desc !== 'object' || desc === null ||
  9176. typeof desc.sdp !== 'string') {
  9177. console.warn('An empty description was passed as an argument.');
  9178. return desc;
  9179. }
  9180. var transform = require('sdp-transform');
  9181. var RandomUtil = require('../util/RandomUtil');
  9182. var session = transform.parse(desc.sdp);
  9183. if (!Array.isArray(session.media))
  9184. {
  9185. return;
  9186. }
  9187. var modded = false;
  9188. session.media.forEach(function (bLine) {
  9189. if (bLine.direction != 'recvonly')
  9190. {
  9191. return;
  9192. }
  9193. modded = true;
  9194. if (!Array.isArray(bLine.ssrcs) || bLine.ssrcs.length === 0)
  9195. {
  9196. var ssrc = RandomUtil.randomInt(1, 0xffffffff);
  9197. bLine.ssrcs = [{
  9198. id: ssrc,
  9199. attribute: 'cname',
  9200. value: ['recvonly-', ssrc].join('')
  9201. }];
  9202. }
  9203. });
  9204. return (!modded) ? desc : new RTCSessionDescription({
  9205. type: desc.type,
  9206. sdp: transform.write(session),
  9207. });
  9208. };
  9209. /**
  9210. * Takes a SessionDescription object and returns a "normalized" version.
  9211. * Currently it only takes care of ordering the a=ssrc lines.
  9212. */
  9213. var normalizePlanB = function(desc) {
  9214. if (typeof desc !== 'object' || desc === null ||
  9215. typeof desc.sdp !== 'string') {
  9216. logger.warn('An empty description was passed as an argument.');
  9217. return desc;
  9218. }
  9219. var transform = require('sdp-transform');
  9220. var session = transform.parse(desc.sdp);
  9221. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  9222. Array.isArray(session.media)) {
  9223. session.media.forEach(function (mLine) {
  9224. // Chrome appears to be picky about the order in which a=ssrc lines
  9225. // are listed in an m-line when rtx is enabled (and thus there are
  9226. // a=ssrc-group lines with FID semantics). Specifically if we have
  9227. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  9228. // the "a=ssrc:S1" lines, SRD fails.
  9229. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  9230. // first.
  9231. var firstSsrcs = [];
  9232. var newSsrcLines = [];
  9233. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  9234. mLine.ssrcGroups.forEach(function (group) {
  9235. if (typeof group.semantics !== 'undefined' &&
  9236. group.semantics === 'FID') {
  9237. if (typeof group.ssrcs !== 'undefined') {
  9238. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  9239. }
  9240. }
  9241. });
  9242. }
  9243. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  9244. var i;
  9245. for (i = 0; i<mLine.ssrcs.length; i++){
  9246. if (typeof mLine.ssrcs[i] === 'object'
  9247. && typeof mLine.ssrcs[i].id !== 'undefined'
  9248. && !$.inArray(mLine.ssrcs[i].id, firstSsrcs)) {
  9249. newSsrcLines.push(mLine.ssrcs[i]);
  9250. delete mLine.ssrcs[i];
  9251. }
  9252. }
  9253. for (i = 0; i<mLine.ssrcs.length; i++){
  9254. if (typeof mLine.ssrcs[i] !== 'undefined') {
  9255. newSsrcLines.push(mLine.ssrcs[i]);
  9256. }
  9257. }
  9258. mLine.ssrcs = newSsrcLines;
  9259. }
  9260. });
  9261. }
  9262. var resStr = transform.write(session);
  9263. return new RTCSessionDescription({
  9264. type: desc.type,
  9265. sdp: resStr
  9266. });
  9267. };
  9268. var getters = {
  9269. signalingState: function () {
  9270. return this.peerconnection.signalingState;
  9271. },
  9272. iceConnectionState: function () {
  9273. return this.peerconnection.iceConnectionState;
  9274. },
  9275. localDescription: function() {
  9276. var desc = this.peerconnection.localDescription;
  9277. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  9278. // if we're running on FF, transform to Plan B first.
  9279. if (RTCBrowserType.usesUnifiedPlan()) {
  9280. desc = this.interop.toPlanB(desc);
  9281. this.trace('getLocalDescription::postTransform (Plan B)',
  9282. dumpSDP(desc));
  9283. }
  9284. return desc;
  9285. },
  9286. remoteDescription: function() {
  9287. var desc = this.peerconnection.remoteDescription;
  9288. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  9289. // if we're running on FF, transform to Plan B first.
  9290. if (RTCBrowserType.usesUnifiedPlan()) {
  9291. desc = this.interop.toPlanB(desc);
  9292. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  9293. }
  9294. return desc;
  9295. }
  9296. };
  9297. Object.keys(getters).forEach(function (prop) {
  9298. Object.defineProperty(
  9299. TraceablePeerConnection.prototype,
  9300. prop, {
  9301. get: getters[prop]
  9302. }
  9303. );
  9304. });
  9305. TraceablePeerConnection.prototype.addStream = function (stream) {
  9306. this.trace('addStream', stream.id);
  9307. try
  9308. {
  9309. this.peerconnection.addStream(stream);
  9310. }
  9311. catch (e)
  9312. {
  9313. logger.error(e);
  9314. }
  9315. };
  9316. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  9317. this.trace('removeStream', stream.id);
  9318. if(stopStreams) {
  9319. RTC.stopMediaStream(stream);
  9320. }
  9321. try {
  9322. // FF doesn't support this yet.
  9323. if (this.peerconnection.removeStream)
  9324. this.peerconnection.removeStream(stream);
  9325. } catch (e) {
  9326. logger.error(e);
  9327. }
  9328. };
  9329. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  9330. this.trace('createDataChannel', label, opts);
  9331. return this.peerconnection.createDataChannel(label, opts);
  9332. };
  9333. TraceablePeerConnection.prototype.setLocalDescription
  9334. = function (description, successCallback, failureCallback) {
  9335. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  9336. // if we're running on FF, transform to Plan A first.
  9337. if (RTCBrowserType.usesUnifiedPlan()) {
  9338. description = this.interop.toUnifiedPlan(description);
  9339. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  9340. }
  9341. var self = this;
  9342. this.peerconnection.setLocalDescription(description,
  9343. function () {
  9344. self.trace('setLocalDescriptionOnSuccess');
  9345. successCallback();
  9346. },
  9347. function (err) {
  9348. self.trace('setLocalDescriptionOnFailure', err);
  9349. failureCallback(err);
  9350. }
  9351. );
  9352. /*
  9353. if (this.statsinterval === null && this.maxstats > 0) {
  9354. // start gathering stats
  9355. }
  9356. */
  9357. };
  9358. TraceablePeerConnection.prototype.setRemoteDescription
  9359. = function (description, successCallback, failureCallback) {
  9360. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  9361. // TODO the focus should squeze or explode the remote simulcast
  9362. description = this.simulcast.mungeRemoteDescription(description);
  9363. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  9364. // if we're running on FF, transform to Plan A first.
  9365. if (RTCBrowserType.usesUnifiedPlan()) {
  9366. description = this.interop.toUnifiedPlan(description);
  9367. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  9368. }
  9369. if (RTCBrowserType.usesPlanB()) {
  9370. description = normalizePlanB(description);
  9371. }
  9372. var self = this;
  9373. this.peerconnection.setRemoteDescription(description,
  9374. function () {
  9375. self.trace('setRemoteDescriptionOnSuccess');
  9376. successCallback();
  9377. },
  9378. function (err) {
  9379. self.trace('setRemoteDescriptionOnFailure', err);
  9380. failureCallback(err);
  9381. }
  9382. );
  9383. /*
  9384. if (this.statsinterval === null && this.maxstats > 0) {
  9385. // start gathering stats
  9386. }
  9387. */
  9388. };
  9389. TraceablePeerConnection.prototype.close = function () {
  9390. this.trace('stop');
  9391. if (this.statsinterval !== null) {
  9392. window.clearInterval(this.statsinterval);
  9393. this.statsinterval = null;
  9394. }
  9395. this.peerconnection.close();
  9396. };
  9397. TraceablePeerConnection.prototype.createOffer
  9398. = function (successCallback, failureCallback, constraints) {
  9399. var self = this;
  9400. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  9401. this.peerconnection.createOffer(
  9402. function (offer) {
  9403. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  9404. // NOTE this is not tested because in meet the focus generates the
  9405. // offer.
  9406. // if we're running on FF, transform to Plan B first.
  9407. if (RTCBrowserType.usesUnifiedPlan()) {
  9408. offer = self.interop.toPlanB(offer);
  9409. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  9410. }
  9411. if (RTCBrowserType.isChrome())
  9412. {
  9413. offer = insertRecvOnlySSRC(offer);
  9414. self.trace('createOfferOnSuccess::mungeLocalVideoSSRC', dumpSDP(offer));
  9415. }
  9416. if (!self.session.room.options.disableSimulcast && self.simulcast.isSupported()) {
  9417. offer = self.simulcast.mungeLocalDescription(offer);
  9418. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  9419. }
  9420. successCallback(offer);
  9421. },
  9422. function(err) {
  9423. self.trace('createOfferOnFailure', err);
  9424. failureCallback(err);
  9425. },
  9426. constraints
  9427. );
  9428. };
  9429. TraceablePeerConnection.prototype.createAnswer
  9430. = function (successCallback, failureCallback, constraints) {
  9431. var self = this;
  9432. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  9433. this.peerconnection.createAnswer(
  9434. function (answer) {
  9435. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  9436. // if we're running on FF, transform to Plan A first.
  9437. if (RTCBrowserType.usesUnifiedPlan()) {
  9438. answer = self.interop.toPlanB(answer);
  9439. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  9440. }
  9441. if (RTCBrowserType.isChrome())
  9442. {
  9443. answer = insertRecvOnlySSRC(answer);
  9444. self.trace('createAnswerOnSuccess::mungeLocalVideoSSRC', dumpSDP(answer));
  9445. }
  9446. if (!self.session.room.options.disableSimulcast && self.simulcast.isSupported()) {
  9447. answer = self.simulcast.mungeLocalDescription(answer);
  9448. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  9449. }
  9450. successCallback(answer);
  9451. },
  9452. function(err) {
  9453. self.trace('createAnswerOnFailure', err);
  9454. failureCallback(err);
  9455. },
  9456. constraints
  9457. );
  9458. };
  9459. TraceablePeerConnection.prototype.addIceCandidate
  9460. = function (candidate, successCallback, failureCallback) {
  9461. //var self = this;
  9462. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  9463. this.peerconnection.addIceCandidate(candidate);
  9464. /* maybe later
  9465. this.peerconnection.addIceCandidate(candidate,
  9466. function () {
  9467. self.trace('addIceCandidateOnSuccess');
  9468. successCallback();
  9469. },
  9470. function (err) {
  9471. self.trace('addIceCandidateOnFailure', err);
  9472. failureCallback(err);
  9473. }
  9474. );
  9475. */
  9476. };
  9477. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  9478. // TODO: Is this the correct way to handle Opera, Temasys?
  9479. if (RTCBrowserType.isFirefox()) {
  9480. // ignore for now...
  9481. if(!errback)
  9482. errback = function () {};
  9483. this.peerconnection.getStats(null, callback, errback);
  9484. } else {
  9485. this.peerconnection.getStats(callback);
  9486. }
  9487. };
  9488. module.exports = TraceablePeerConnection;
  9489. }).call(this,"/modules/xmpp/TraceablePeerConnection.js")
  9490. },{"../../service/xmpp/XMPPEvents":85,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"../util/RandomUtil":25,"jitsi-meet-logger":47,"sdp-interop":65,"sdp-simulcast":72,"sdp-transform":75}],33:[function(require,module,exports){
  9491. (function (__filename){
  9492. /* global $, $iq, Promise, Strophe */
  9493. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9494. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9495. var Settings = require("../settings/Settings");
  9496. var AuthenticationEvents
  9497. = require("../../service/authentication/AuthenticationEvents");
  9498. function createExpBackoffTimer(step) {
  9499. var count = 1;
  9500. return function (reset) {
  9501. // Reset call
  9502. if (reset) {
  9503. count = 1;
  9504. return;
  9505. }
  9506. // Calculate next timeout
  9507. var timeout = Math.pow(2, count - 1);
  9508. count += 1;
  9509. return timeout * step;
  9510. };
  9511. }
  9512. function Moderator(roomName, xmpp, emitter) {
  9513. this.roomName = roomName;
  9514. this.xmppService = xmpp;
  9515. this.getNextTimeout = createExpBackoffTimer(1000);
  9516. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  9517. // External authentication stuff
  9518. this.externalAuthEnabled = false;
  9519. this.settings = new Settings(roomName);
  9520. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  9521. // it will be enabled automatically if focus detects the component through
  9522. // service discovery.
  9523. this.sipGatewayEnabled = this.xmppService.options.hosts &&
  9524. this.xmppService.options.hosts.call_control !== undefined;
  9525. this.eventEmitter = emitter;
  9526. this.connection = this.xmppService.connection;
  9527. this.focusUserJid;
  9528. //FIXME:
  9529. // Message listener that talks to POPUP window
  9530. function listener(event) {
  9531. if (event.data && event.data.sessionId) {
  9532. if (event.origin !== window.location.origin) {
  9533. logger.warn("Ignoring sessionId from different origin: " +
  9534. event.origin);
  9535. return;
  9536. }
  9537. localStorage.setItem('sessionId', event.data.sessionId);
  9538. // After popup is closed we will authenticate
  9539. }
  9540. }
  9541. // Register
  9542. if (window.addEventListener) {
  9543. window.addEventListener("message", listener, false);
  9544. } else {
  9545. window.attachEvent("onmessage", listener);
  9546. }
  9547. }
  9548. Moderator.prototype.isExternalAuthEnabled = function () {
  9549. return this.externalAuthEnabled;
  9550. };
  9551. Moderator.prototype.isSipGatewayEnabled = function () {
  9552. return this.sipGatewayEnabled;
  9553. };
  9554. Moderator.prototype.onMucMemberLeft = function (jid) {
  9555. logger.info("Someone left is it focus ? " + jid);
  9556. var resource = Strophe.getResourceFromJid(jid);
  9557. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  9558. logger.info(
  9559. "Focus has left the room - leaving conference");
  9560. //hangUp();
  9561. // We'd rather reload to have everything re-initialized
  9562. //FIXME: show some message before reload
  9563. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  9564. }
  9565. };
  9566. Moderator.prototype.setFocusUserJid = function (focusJid) {
  9567. if (!this.focusUserJid) {
  9568. this.focusUserJid = focusJid;
  9569. logger.info("Focus jid set to: " + this.focusUserJid);
  9570. }
  9571. };
  9572. Moderator.prototype.getFocusUserJid = function () {
  9573. return this.focusUserJid;
  9574. };
  9575. Moderator.prototype.getFocusComponent = function () {
  9576. // Get focus component address
  9577. var focusComponent = this.xmppService.options.hosts.focus;
  9578. // If not specified use default: 'focus.domain'
  9579. if (!focusComponent) {
  9580. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  9581. }
  9582. return focusComponent;
  9583. };
  9584. Moderator.prototype.createConferenceIq = function () {
  9585. // Generate create conference IQ
  9586. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  9587. // Session Id used for authentication
  9588. var sessionId = localStorage.getItem('sessionId');
  9589. var machineUID = this.settings.getSettings().uid;
  9590. logger.info(
  9591. "Session ID: " + sessionId + " machine UID: " + machineUID);
  9592. elem.c('conference', {
  9593. xmlns: 'http://jitsi.org/protocol/focus',
  9594. room: this.roomName,
  9595. 'machine-uid': machineUID
  9596. });
  9597. if (sessionId) {
  9598. elem.attrs({ 'session-id': sessionId});
  9599. }
  9600. if (this.xmppService.options.hosts.bridge !== undefined) {
  9601. elem.c(
  9602. 'property', {
  9603. name: 'bridge',
  9604. value: this.xmppService.options.hosts.bridge
  9605. }).up();
  9606. }
  9607. if (this.xmppService.options.enforcedBridge !== undefined) {
  9608. elem.c(
  9609. 'property', {
  9610. name: 'enforcedBridge',
  9611. value: this.xmppService.options.enforcedBridge
  9612. }).up();
  9613. }
  9614. // Tell the focus we have Jigasi configured
  9615. if (this.xmppService.options.hosts.call_control !== undefined) {
  9616. elem.c(
  9617. 'property', {
  9618. name: 'call_control',
  9619. value: this.xmppService.options.hosts.call_control
  9620. }).up();
  9621. }
  9622. if (this.xmppService.options.channelLastN !== undefined) {
  9623. elem.c(
  9624. 'property', {
  9625. name: 'channelLastN',
  9626. value: this.xmppService.options.channelLastN
  9627. }).up();
  9628. }
  9629. if (this.xmppService.options.adaptiveLastN !== undefined) {
  9630. elem.c(
  9631. 'property', {
  9632. name: 'adaptiveLastN',
  9633. value: this.xmppService.options.adaptiveLastN
  9634. }).up();
  9635. }
  9636. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  9637. elem.c(
  9638. 'property', {
  9639. name: 'adaptiveSimulcast',
  9640. value: this.xmppService.options.adaptiveSimulcast
  9641. }).up();
  9642. }
  9643. if (this.xmppService.options.openSctp !== undefined) {
  9644. elem.c(
  9645. 'property', {
  9646. name: 'openSctp',
  9647. value: this.xmppService.options.openSctp
  9648. }).up();
  9649. }
  9650. if (this.xmppService.options.startAudioMuted !== undefined)
  9651. {
  9652. elem.c(
  9653. 'property', {
  9654. name: 'startAudioMuted',
  9655. value: this.xmppService.options.startAudioMuted
  9656. }).up();
  9657. }
  9658. if (this.xmppService.options.startVideoMuted !== undefined)
  9659. {
  9660. elem.c(
  9661. 'property', {
  9662. name: 'startVideoMuted',
  9663. value: this.xmppService.options.startVideoMuted
  9664. }).up();
  9665. }
  9666. elem.c(
  9667. 'property', {
  9668. name: 'simulcastMode',
  9669. value: 'rewriting'
  9670. }).up();
  9671. elem.up();
  9672. return elem;
  9673. };
  9674. Moderator.prototype.parseSessionId = function (resultIq) {
  9675. var sessionId = $(resultIq).find('conference').attr('session-id');
  9676. if (sessionId) {
  9677. logger.info('Received sessionId: ' + sessionId);
  9678. localStorage.setItem('sessionId', sessionId);
  9679. }
  9680. };
  9681. Moderator.prototype.parseConfigOptions = function (resultIq) {
  9682. this.setFocusUserJid(
  9683. $(resultIq).find('conference').attr('focusjid'));
  9684. var authenticationEnabled
  9685. = $(resultIq).find(
  9686. '>conference>property' +
  9687. '[name=\'authentication\'][value=\'true\']').length > 0;
  9688. logger.info("Authentication enabled: " + authenticationEnabled);
  9689. this.externalAuthEnabled = $(resultIq).find(
  9690. '>conference>property' +
  9691. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  9692. console.info(
  9693. 'External authentication enabled: ' + this.externalAuthEnabled);
  9694. if (!this.externalAuthEnabled) {
  9695. // We expect to receive sessionId in 'internal' authentication mode
  9696. this.parseSessionId(resultIq);
  9697. }
  9698. var authIdentity = $(resultIq).find('>conference').attr('identity');
  9699. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  9700. authenticationEnabled, authIdentity);
  9701. // Check if focus has auto-detected Jigasi component(this will be also
  9702. // included if we have passed our host from the config)
  9703. if ($(resultIq).find(
  9704. '>conference>property' +
  9705. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  9706. this.sipGatewayEnabled = true;
  9707. }
  9708. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  9709. };
  9710. // FIXME = we need to show the fact that we're waiting for the focus
  9711. // to the user(or that focus is not available)
  9712. Moderator.prototype.allocateConferenceFocus = function (callback) {
  9713. // Try to use focus user JID from the config
  9714. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  9715. // Send create conference IQ
  9716. var iq = this.createConferenceIq();
  9717. var self = this;
  9718. this.connection.sendIQ(
  9719. iq,
  9720. function (result) {
  9721. // Setup config options
  9722. self.parseConfigOptions(result);
  9723. if ('true' === $(result).find('conference').attr('ready')) {
  9724. // Reset both timers
  9725. self.getNextTimeout(true);
  9726. self.getNextErrorTimeout(true);
  9727. // Exec callback
  9728. callback();
  9729. } else {
  9730. var waitMs = self.getNextTimeout();
  9731. logger.info("Waiting for the focus... " + waitMs);
  9732. // Reset error timeout
  9733. self.getNextErrorTimeout(true);
  9734. window.setTimeout(
  9735. function () {
  9736. self.allocateConferenceFocus(callback);
  9737. }, waitMs);
  9738. }
  9739. },
  9740. function (error) {
  9741. // Invalid session ? remove and try again
  9742. // without session ID to get a new one
  9743. var invalidSession
  9744. = $(error).find('>error>session-invalid').length;
  9745. if (invalidSession) {
  9746. logger.info("Session expired! - removing");
  9747. localStorage.removeItem("sessionId");
  9748. }
  9749. if ($(error).find('>error>graceful-shutdown').length) {
  9750. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  9751. return;
  9752. }
  9753. // Check for error returned by the reservation system
  9754. var reservationErr = $(error).find('>error>reservation-error');
  9755. if (reservationErr.length) {
  9756. // Trigger error event
  9757. var errorCode = reservationErr.attr('error-code');
  9758. var errorMsg;
  9759. if ($(error).find('>error>text')) {
  9760. errorMsg = $(error).find('>error>text').text();
  9761. }
  9762. self.eventEmitter.emit(
  9763. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  9764. return;
  9765. }
  9766. // Not authorized to create new room
  9767. if ($(error).find('>error>not-authorized').length) {
  9768. logger.warn("Unauthorized to start the conference", error);
  9769. var toDomain
  9770. = Strophe.getDomainFromJid(error.getAttribute('to'));
  9771. if (toDomain !==
  9772. this.xmppService.options.hosts.anonymousdomain) {
  9773. //FIXME: "is external" should come either from
  9774. // the focus or config.js
  9775. self.externalAuthEnabled = true;
  9776. }
  9777. self.eventEmitter.emit(
  9778. XMPPEvents.AUTHENTICATION_REQUIRED,
  9779. function () {
  9780. self.allocateConferenceFocus(
  9781. callback);
  9782. });
  9783. return;
  9784. }
  9785. var waitMs = self.getNextErrorTimeout();
  9786. logger.error("Focus error, retry after " + waitMs, error);
  9787. // Show message
  9788. var focusComponent = self.getFocusComponent();
  9789. var retrySec = waitMs / 1000;
  9790. //FIXME: message is duplicated ?
  9791. // Do not show in case of session invalid
  9792. // which means just a retry
  9793. if (!invalidSession) {
  9794. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  9795. focusComponent, retrySec);
  9796. }
  9797. // Reset response timeout
  9798. self.getNextTimeout(true);
  9799. window.setTimeout(
  9800. function () {
  9801. self.allocateConferenceFocus(callback);
  9802. }, waitMs);
  9803. }
  9804. );
  9805. };
  9806. Moderator.prototype.authenticate = function () {
  9807. var self = this;
  9808. return new Promise(function (resolve, reject) {
  9809. self.connection.sendIQ(
  9810. self.createConferenceIq(),
  9811. function (result) {
  9812. self.parseSessionId(result);
  9813. resolve();
  9814. }, function (error) {
  9815. var code = $(error).find('>error').attr('code');
  9816. reject(error, code);
  9817. }
  9818. );
  9819. });
  9820. };
  9821. Moderator.prototype.getLoginUrl = function (urlCallback, failureCallback) {
  9822. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9823. iq.c('login-url', {
  9824. xmlns: 'http://jitsi.org/protocol/focus',
  9825. room: this.roomName,
  9826. 'machine-uid': this.settings.getSettings().uid
  9827. });
  9828. this.connection.sendIQ(
  9829. iq,
  9830. function (result) {
  9831. var url = $(result).find('login-url').attr('url');
  9832. url = url = decodeURIComponent(url);
  9833. if (url) {
  9834. logger.info("Got auth url: " + url);
  9835. urlCallback(url);
  9836. } else {
  9837. logger.error(
  9838. "Failed to get auth url from the focus", result);
  9839. failureCallback(result);
  9840. }
  9841. },
  9842. function (error) {
  9843. logger.error("Get auth url error", error);
  9844. failureCallback(error);
  9845. }
  9846. );
  9847. };
  9848. Moderator.prototype.getPopupLoginUrl = function (urlCallback, failureCallback) {
  9849. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9850. iq.c('login-url', {
  9851. xmlns: 'http://jitsi.org/protocol/focus',
  9852. room: this.roomName,
  9853. 'machine-uid': this.settings.getSettings().uid,
  9854. popup: true
  9855. });
  9856. this.connection.sendIQ(
  9857. iq,
  9858. function (result) {
  9859. var url = $(result).find('login-url').attr('url');
  9860. url = url = decodeURIComponent(url);
  9861. if (url) {
  9862. logger.info("Got POPUP auth url: " + url);
  9863. urlCallback(url);
  9864. } else {
  9865. logger.error(
  9866. "Failed to get POPUP auth url from the focus", result);
  9867. failureCallback(result);
  9868. }
  9869. },
  9870. function (error) {
  9871. logger.error('Get POPUP auth url error', error);
  9872. failureCallback(error);
  9873. }
  9874. );
  9875. };
  9876. Moderator.prototype.logout = function (callback) {
  9877. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  9878. var sessionId = localStorage.getItem('sessionId');
  9879. if (!sessionId) {
  9880. callback();
  9881. return;
  9882. }
  9883. iq.c('logout', {
  9884. xmlns: 'http://jitsi.org/protocol/focus',
  9885. 'session-id': sessionId
  9886. });
  9887. this.connection.sendIQ(
  9888. iq,
  9889. function (result) {
  9890. var logoutUrl = $(result).find('logout').attr('logout-url');
  9891. if (logoutUrl) {
  9892. logoutUrl = decodeURIComponent(logoutUrl);
  9893. }
  9894. logger.info("Log out OK, url: " + logoutUrl, result);
  9895. localStorage.removeItem('sessionId');
  9896. callback(logoutUrl);
  9897. },
  9898. function (error) {
  9899. logger.error("Logout error", error);
  9900. }
  9901. );
  9902. };
  9903. module.exports = Moderator;
  9904. }).call(this,"/modules/xmpp/moderator.js")
  9905. },{"../../service/authentication/AuthenticationEvents":81,"../../service/xmpp/XMPPEvents":85,"../settings/Settings":21,"jitsi-meet-logger":47}],34:[function(require,module,exports){
  9906. (function (__filename){
  9907. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  9908. Toolbar, Util, Promise */
  9909. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9910. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9911. function Recording(type, eventEmitter, connection, focusMucJid, jirecon,
  9912. roomjid) {
  9913. this.eventEmitter = eventEmitter;
  9914. this.connection = connection;
  9915. this.state = "off";
  9916. this.focusMucJid = focusMucJid;
  9917. this.jirecon = jirecon;
  9918. this.url = null;
  9919. this.type = type;
  9920. this._isSupported = ((type === Recording.types.JIBRI)
  9921. || (type === Recording.types.JIRECON && !this.jirecon))? false : true;
  9922. /**
  9923. * The ID of the jirecon recording session. Jirecon generates it when we
  9924. * initially start recording, and it needs to be used in subsequent requests
  9925. * to jirecon.
  9926. */
  9927. this.jireconRid = null;
  9928. this.roomjid = roomjid;
  9929. }
  9930. Recording.types = {
  9931. COLIBRI: "colibri",
  9932. JIRECON: "jirecon",
  9933. JIBRI: "jibri"
  9934. };
  9935. Recording.prototype.handleJibriPresence = function (jibri) {
  9936. var attributes = jibri.attributes;
  9937. if(!attributes)
  9938. return;
  9939. this._isSupported =
  9940. (attributes.status && attributes.status !== "undefined");
  9941. if(this._isSupported) {
  9942. this.url = attributes.url || null;
  9943. this.state = attributes.status || "off";
  9944. }
  9945. this.eventEmitter.emit(XMPPEvents.RECORDING_STATE_CHANGED);
  9946. };
  9947. Recording.prototype.setRecordingJibri = function (state, callback, errCallback,
  9948. options) {
  9949. if (state == this.state){
  9950. errCallback(new Error("Invalid state!"));
  9951. }
  9952. options = options || {};
  9953. // FIXME jibri does not accept IQ without 'url' attribute set ?
  9954. var iq = $iq({to: this.focusMucJid, type: 'set'})
  9955. .c('jibri', {
  9956. "xmlns": 'http://jitsi.org/protocol/jibri',
  9957. "action": (state === 'on') ? 'start' : 'stop',
  9958. "streamid": options.streamId,
  9959. "follow-entity": options.followEntity
  9960. }).up();
  9961. logger.log('Set jibri recording: '+state, iq.nodeTree);
  9962. console.log(iq.nodeTree);
  9963. this.connection.sendIQ(
  9964. iq,
  9965. function (result) {
  9966. callback($(result).find('jibri').attr('state'),
  9967. $(result).find('jibri').attr('url'));
  9968. },
  9969. function (error) {
  9970. logger.log('Failed to start recording, error: ', error);
  9971. errCallback(error);
  9972. });
  9973. };
  9974. Recording.prototype.setRecordingJirecon =
  9975. function (state, callback, errCallback, options) {
  9976. if (state == this.state){
  9977. errCallback(new Error("Invalid state!"));
  9978. }
  9979. var iq = $iq({to: this.jirecon, type: 'set'})
  9980. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  9981. action: (state === 'on') ? 'start' : 'stop',
  9982. mucjid: this.roomjid});
  9983. if (state === 'off'){
  9984. iq.attrs({rid: this.jireconRid});
  9985. }
  9986. console.log('Start recording');
  9987. var self = this;
  9988. this.connection.sendIQ(
  9989. iq,
  9990. function (result) {
  9991. // TODO wait for an IQ with the real status, since this is
  9992. // provisional?
  9993. self.jireconRid = $(result).find('recording').attr('rid');
  9994. console.log('Recording ' +
  9995. ((state === 'on') ? 'started' : 'stopped') +
  9996. '(jirecon)' + result);
  9997. self.state = state;
  9998. if (state === 'off'){
  9999. self.jireconRid = null;
  10000. }
  10001. callback(state);
  10002. },
  10003. function (error) {
  10004. console.log('Failed to start recording, error: ', error);
  10005. errCallback(error);
  10006. });
  10007. };
  10008. // Sends a COLIBRI message which enables or disables (according to 'state')
  10009. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  10010. // with the new recording state, according to the IQ.
  10011. Recording.prototype.setRecordingColibri =
  10012. function (state, callback, errCallback, options) {
  10013. var elem = $iq({to: this.focusMucJid, type: 'set'});
  10014. elem.c('conference', {
  10015. xmlns: 'http://jitsi.org/protocol/colibri'
  10016. });
  10017. elem.c('recording', {state: state, token: options.token});
  10018. var self = this;
  10019. this.connection.sendIQ(elem,
  10020. function (result) {
  10021. console.log('Set recording "', state, '". Result:', result);
  10022. var recordingElem = $(result).find('>conference>recording');
  10023. var newState = recordingElem.attr('state');
  10024. self.state = newState;
  10025. callback(newState);
  10026. if (newState === 'pending') {
  10027. self.connection.addHandler(function(iq){
  10028. var state = $(iq).find('recording').attr('state');
  10029. if (state) {
  10030. self.state = newState;
  10031. callback(state);
  10032. }
  10033. }, 'http://jitsi.org/protocol/colibri', 'iq', null, null, null);
  10034. }
  10035. },
  10036. function (error) {
  10037. console.warn(error);
  10038. errCallback(error);
  10039. }
  10040. );
  10041. };
  10042. Recording.prototype.setRecording =
  10043. function (state, callback, errCallback, options) {
  10044. switch(this.type){
  10045. case Recording.types.JIRECON:
  10046. this.setRecordingJirecon(state, callback, errCallback, options);
  10047. break;
  10048. case Recording.types.COLIBRI:
  10049. this.setRecordingColibri(state, callback, errCallback, options);
  10050. break;
  10051. case Recording.types.JIBRI:
  10052. this.setRecordingJibri(state, callback, errCallback, options);
  10053. break;
  10054. default:
  10055. console.error("Unknown recording type!");
  10056. return;
  10057. }
  10058. };
  10059. /**
  10060. *Starts/stops the recording
  10061. * @param token token for authentication
  10062. * @param statusChangeHandler {function} receives the new status as argument.
  10063. */
  10064. Recording.prototype.toggleRecording = function (options, statusChangeHandler) {
  10065. if ((!options.token && this.type === Recording.types.COLIBRI) ||
  10066. (!options.streamId && this.type === Recording.types.JIBRI)){
  10067. statusChangeHandler("error", new Error("No token passed!"));
  10068. logger.error("No token passed!");
  10069. return;
  10070. }
  10071. var oldState = this.state;
  10072. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  10073. var self = this;
  10074. this.setRecording(newState,
  10075. function (state, url) {
  10076. logger.log("New recording state: ", state);
  10077. if (state && state !== oldState) {
  10078. self.state = state;
  10079. self.url = url;
  10080. statusChangeHandler(state);
  10081. } else {
  10082. statusChangeHandler("error", new Error("Status not changed!"));
  10083. }
  10084. }, function (error) {
  10085. statusChangeHandler("error", error);
  10086. }, options);
  10087. };
  10088. /**
  10089. * Returns true if the recording is supproted and false if not.
  10090. */
  10091. Recording.prototype.isSupported = function () {
  10092. return this._isSupported;
  10093. };
  10094. /**
  10095. * Returns null if the recording is not supported, "on" if the recording started
  10096. * and "off" if the recording is not started.
  10097. */
  10098. Recording.prototype.getState = function () {
  10099. return this.state;
  10100. };
  10101. /**
  10102. * Returns the url of the recorded video.
  10103. */
  10104. Recording.prototype.getURL = function () {
  10105. return this.url;
  10106. };
  10107. module.exports = Recording;
  10108. }).call(this,"/modules/xmpp/recording.js")
  10109. },{"../../service/xmpp/XMPPEvents":85,"jitsi-meet-logger":47}],35:[function(require,module,exports){
  10110. (function (__filename){
  10111. /* jshint -W117 */
  10112. /* a simple MUC connection plugin
  10113. * can only handle a single MUC room
  10114. */
  10115. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10116. var ChatRoom = require("./ChatRoom");
  10117. module.exports = function(XMPP) {
  10118. Strophe.addConnectionPlugin('emuc', {
  10119. connection: null,
  10120. rooms: {},//map with the rooms
  10121. init: function (conn) {
  10122. this.connection = conn;
  10123. // add handlers (just once)
  10124. this.connection.addHandler(this.onPresence.bind(this), null,
  10125. 'presence', null, null, null, null);
  10126. this.connection.addHandler(this.onPresenceUnavailable.bind(this),
  10127. null, 'presence', 'unavailable', null);
  10128. this.connection.addHandler(this.onPresenceError.bind(this), null,
  10129. 'presence', 'error', null);
  10130. this.connection.addHandler(this.onMessage.bind(this), null,
  10131. 'message', null, null);
  10132. this.connection.addHandler(this.onMute.bind(this),
  10133. 'http://jitsi.org/jitmeet/audio', 'iq', 'set',null,null);
  10134. },
  10135. createRoom: function (jid, password, options) {
  10136. var roomJid = Strophe.getBareJidFromJid(jid);
  10137. if (this.rooms[roomJid]) {
  10138. logger.error("You are already in the room!");
  10139. return;
  10140. }
  10141. this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, options);
  10142. return this.rooms[roomJid];
  10143. },
  10144. doLeave: function (jid) {
  10145. this.rooms[jid].doLeave();
  10146. delete this.rooms[jid];
  10147. },
  10148. onPresence: function (pres) {
  10149. var from = pres.getAttribute('from');
  10150. // What is this for? A workaround for something?
  10151. if (pres.getAttribute('type')) {
  10152. return true;
  10153. }
  10154. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10155. if(!room)
  10156. return;
  10157. // Parse status.
  10158. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  10159. room.createNonAnonymousRoom();
  10160. }
  10161. room.onPresence(pres);
  10162. return true;
  10163. },
  10164. onPresenceUnavailable: function (pres) {
  10165. var from = pres.getAttribute('from');
  10166. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10167. if(!room)
  10168. return;
  10169. room.onPresenceUnavailable(pres, from);
  10170. return true;
  10171. },
  10172. onPresenceError: function (pres) {
  10173. var from = pres.getAttribute('from');
  10174. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10175. if(!room)
  10176. return;
  10177. room.onPresenceError(pres, from);
  10178. return true;
  10179. },
  10180. onMessage: function (msg) {
  10181. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  10182. var from = msg.getAttribute('from');
  10183. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10184. if(!room)
  10185. return;
  10186. room.onMessage(msg, from);
  10187. return true;
  10188. },
  10189. setJingleSession: function (from, session) {
  10190. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10191. if(!room)
  10192. return;
  10193. room.setJingleSession(session);
  10194. },
  10195. onMute: function(iq) {
  10196. var from = iq.getAttribute('from');
  10197. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10198. if(!room)
  10199. return;
  10200. room.onMute(iq);
  10201. return true;
  10202. }
  10203. });
  10204. };
  10205. }).call(this,"/modules/xmpp/strophe.emuc.js")
  10206. },{"./ChatRoom":26,"jitsi-meet-logger":47}],36:[function(require,module,exports){
  10207. (function (__filename){
  10208. /* jshint -W117 */
  10209. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10210. var JingleSession = require("./JingleSessionPC");
  10211. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10212. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10213. module.exports = function(XMPP, eventEmitter) {
  10214. Strophe.addConnectionPlugin('jingle', {
  10215. connection: null,
  10216. sessions: {},
  10217. jid2session: {},
  10218. ice_config: {iceServers: []},
  10219. media_constraints: {
  10220. mandatory: {
  10221. 'OfferToReceiveAudio': true,
  10222. 'OfferToReceiveVideo': true
  10223. }
  10224. // MozDontOfferDataChannel: true when this is firefox
  10225. },
  10226. init: function (conn) {
  10227. this.connection = conn;
  10228. if (this.connection.disco) {
  10229. // http://xmpp.org/extensions/xep-0167.html#support
  10230. // http://xmpp.org/extensions/xep-0176.html#support
  10231. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  10232. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  10233. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  10234. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  10235. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  10236. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  10237. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  10238. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  10239. || RTCBrowserType.isTemasysPluginUsed()) {
  10240. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  10241. }
  10242. // this is dealt with by SDP O/A so we don't need to announce this
  10243. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  10244. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  10245. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  10246. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  10247. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  10248. }
  10249. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  10250. },
  10251. onJingle: function (iq) {
  10252. var sid = $(iq).find('jingle').attr('sid');
  10253. var action = $(iq).find('jingle').attr('action');
  10254. var fromJid = iq.getAttribute('from');
  10255. // send ack first
  10256. var ack = $iq({type: 'result',
  10257. to: fromJid,
  10258. id: iq.getAttribute('id')
  10259. });
  10260. logger.log('on jingle ' + action + ' from ' + fromJid, iq);
  10261. var sess = this.sessions[sid];
  10262. if ('session-initiate' != action) {
  10263. if (sess === null) {
  10264. ack.type = 'error';
  10265. ack.c('error', {type: 'cancel'})
  10266. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  10267. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  10268. this.connection.send(ack);
  10269. return true;
  10270. }
  10271. // local jid is not checked
  10272. if (fromJid != sess.peerjid) {
  10273. logger.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  10274. ack.type = 'error';
  10275. ack.c('error', {type: 'cancel'})
  10276. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  10277. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  10278. this.connection.send(ack);
  10279. return true;
  10280. }
  10281. } else if (sess !== undefined) {
  10282. // existing session with same session id
  10283. // this might be out-of-order if the sess.peerjid is the same as from
  10284. ack.type = 'error';
  10285. ack.c('error', {type: 'cancel'})
  10286. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  10287. logger.warn('duplicate session id', sid);
  10288. this.connection.send(ack);
  10289. return true;
  10290. }
  10291. // FIXME: check for a defined action
  10292. this.connection.send(ack);
  10293. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  10294. switch (action) {
  10295. case 'session-initiate':
  10296. console.log("(TIME) received session-initiate:\t",
  10297. window.performance.now());
  10298. var startMuted = $(iq).find('jingle>startmuted');
  10299. if (startMuted && startMuted.length > 0) {
  10300. var audioMuted = startMuted.attr("audio");
  10301. var videoMuted = startMuted.attr("video");
  10302. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  10303. audioMuted === "true", videoMuted === "true");
  10304. }
  10305. sess = new JingleSession(
  10306. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  10307. this.connection, XMPP);
  10308. // configure session
  10309. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  10310. this.connection.emuc.setJingleSession(fromBareJid, sess);
  10311. sess.media_constraints = this.media_constraints;
  10312. sess.ice_config = this.ice_config;
  10313. sess.initialize(fromJid, false);
  10314. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  10315. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  10316. sess.setOffer($(iq).find('>jingle'));
  10317. this.sessions[sess.sid] = sess;
  10318. this.jid2session[sess.peerjid] = sess;
  10319. // the callback should either
  10320. // .sendAnswer and .accept
  10321. // or .sendTerminate -- not necessarily synchronous
  10322. sess.sendAnswer();
  10323. sess.accept();
  10324. break;
  10325. case 'session-accept':
  10326. sess.setAnswer($(iq).find('>jingle'));
  10327. sess.accept();
  10328. break;
  10329. case 'session-terminate':
  10330. // If this is not the focus sending the terminate, we have
  10331. // nothing more to do here.
  10332. if (Object.keys(this.sessions).length < 1
  10333. || !(this.sessions[Object.keys(this.sessions)[0]]
  10334. instanceof JingleSession))
  10335. {
  10336. break;
  10337. }
  10338. logger.log('terminating...', sess.sid);
  10339. sess.terminate();
  10340. this.terminate(sess.sid);
  10341. if ($(iq).find('>jingle>reason').length) {
  10342. $(document).trigger('callterminated.jingle', [
  10343. sess.sid,
  10344. sess.peerjid,
  10345. $(iq).find('>jingle>reason>:first')[0].tagName,
  10346. $(iq).find('>jingle>reason>text').text()
  10347. ]);
  10348. } else {
  10349. $(document).trigger('callterminated.jingle',
  10350. [sess.sid, sess.peerjid]);
  10351. }
  10352. break;
  10353. case 'transport-info':
  10354. sess.addIceCandidate($(iq).find('>jingle>content'));
  10355. break;
  10356. case 'session-info':
  10357. var affected;
  10358. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  10359. $(document).trigger('ringing.jingle', [sess.sid]);
  10360. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  10361. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  10362. $(document).trigger('mute.jingle', [sess.sid, affected]);
  10363. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  10364. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  10365. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  10366. }
  10367. break;
  10368. case 'addsource': // FIXME: proprietary, un-jingleish
  10369. case 'source-add': // FIXME: proprietary
  10370. sess.addSource($(iq).find('>jingle>content'));
  10371. break;
  10372. case 'removesource': // FIXME: proprietary, un-jingleish
  10373. case 'source-remove': // FIXME: proprietary
  10374. sess.removeSource($(iq).find('>jingle>content'));
  10375. break;
  10376. default:
  10377. logger.warn('jingle action not implemented', action);
  10378. break;
  10379. }
  10380. return true;
  10381. },
  10382. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  10383. if (sid === null || sid === undefined) {
  10384. for (sid in this.sessions) {
  10385. if (this.sessions[sid].state != 'ended') {
  10386. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  10387. this.sessions[sid].terminate();
  10388. }
  10389. delete this.jid2session[this.sessions[sid].peerjid];
  10390. delete this.sessions[sid];
  10391. }
  10392. } else if (this.sessions.hasOwnProperty(sid)) {
  10393. if (this.sessions[sid].state != 'ended') {
  10394. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  10395. this.sessions[sid].terminate();
  10396. }
  10397. delete this.jid2session[this.sessions[sid].peerjid];
  10398. delete this.sessions[sid];
  10399. }
  10400. },
  10401. getStunAndTurnCredentials: function () {
  10402. // get stun and turn configuration from server via xep-0215
  10403. // uses time-limited credentials as described in
  10404. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  10405. //
  10406. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  10407. // for a prosody module which implements this
  10408. //
  10409. // currently, this doesn't work with updateIce and therefore credentials with a long
  10410. // validity have to be fetched before creating the peerconnection
  10411. // TODO: implement refresh via updateIce as described in
  10412. // https://code.google.com/p/webrtc/issues/detail?id=1650
  10413. var self = this;
  10414. this.connection.sendIQ(
  10415. $iq({type: 'get', to: this.connection.domain})
  10416. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  10417. function (res) {
  10418. var iceservers = [];
  10419. $(res).find('>services>service').each(function (idx, el) {
  10420. el = $(el);
  10421. var dict = {};
  10422. var type = el.attr('type');
  10423. switch (type) {
  10424. case 'stun':
  10425. dict.url = 'stun:' + el.attr('host');
  10426. if (el.attr('port')) {
  10427. dict.url += ':' + el.attr('port');
  10428. }
  10429. iceservers.push(dict);
  10430. break;
  10431. case 'turn':
  10432. case 'turns':
  10433. dict.url = type + ':';
  10434. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  10435. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  10436. dict.url += el.attr('username') + '@';
  10437. } else {
  10438. dict.username = el.attr('username'); // only works in M28
  10439. }
  10440. }
  10441. dict.url += el.attr('host');
  10442. if (el.attr('port') && el.attr('port') != '3478') {
  10443. dict.url += ':' + el.attr('port');
  10444. }
  10445. if (el.attr('transport') && el.attr('transport') != 'udp') {
  10446. dict.url += '?transport=' + el.attr('transport');
  10447. }
  10448. if (el.attr('password')) {
  10449. dict.credential = el.attr('password');
  10450. }
  10451. iceservers.push(dict);
  10452. break;
  10453. }
  10454. });
  10455. self.ice_config.iceServers = iceservers;
  10456. },
  10457. function (err) {
  10458. logger.warn('getting turn credentials failed', err);
  10459. logger.warn('is mod_turncredentials or similar installed?');
  10460. }
  10461. );
  10462. // implement push?
  10463. },
  10464. /**
  10465. * Returns the data saved in 'updateLog' in a format to be logged.
  10466. */
  10467. getLog: function () {
  10468. var data = {};
  10469. var self = this;
  10470. Object.keys(this.sessions).forEach(function (sid) {
  10471. var session = self.sessions[sid];
  10472. if (session.peerconnection && session.peerconnection.updateLog) {
  10473. // FIXME: should probably be a .dump call
  10474. data["jingle_" + session.sid] = {
  10475. updateLog: session.peerconnection.updateLog,
  10476. stats: session.peerconnection.stats,
  10477. url: window.location.href
  10478. };
  10479. }
  10480. });
  10481. return data;
  10482. }
  10483. });
  10484. };
  10485. }).call(this,"/modules/xmpp/strophe.jingle.js")
  10486. },{"../../service/xmpp/XMPPEvents":85,"../RTC/RTCBrowserType":17,"./JingleSessionPC":28,"jitsi-meet-logger":47}],37:[function(require,module,exports){
  10487. /* global Strophe */
  10488. module.exports = function () {
  10489. Strophe.addConnectionPlugin('logger', {
  10490. // logs raw stanzas and makes them available for download as JSON
  10491. connection: null,
  10492. log: [],
  10493. init: function (conn) {
  10494. this.connection = conn;
  10495. this.connection.rawInput = this.log_incoming.bind(this);
  10496. this.connection.rawOutput = this.log_outgoing.bind(this);
  10497. },
  10498. log_incoming: function (stanza) {
  10499. this.log.push([new Date().getTime(), 'incoming', stanza]);
  10500. },
  10501. log_outgoing: function (stanza) {
  10502. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  10503. }
  10504. });
  10505. };
  10506. },{}],38:[function(require,module,exports){
  10507. (function (__filename){
  10508. /* global $, $iq, Strophe */
  10509. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10510. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10511. /**
  10512. * Ping every 10 sec
  10513. */
  10514. var PING_INTERVAL = 10000;
  10515. /**
  10516. * Ping timeout error after 15 sec of waiting.
  10517. */
  10518. var PING_TIMEOUT = 15000;
  10519. /**
  10520. * Will close the connection after 3 consecutive ping errors.
  10521. */
  10522. var PING_THRESHOLD = 3;
  10523. /**
  10524. * XEP-0199 ping plugin.
  10525. *
  10526. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  10527. */
  10528. module.exports = function (XMPP, eventEmitter) {
  10529. Strophe.addConnectionPlugin('ping', {
  10530. connection: null,
  10531. failedPings: 0,
  10532. /**
  10533. * Initializes the plugin. Method called by Strophe.
  10534. * @param connection Strophe connection instance.
  10535. */
  10536. init: function (connection) {
  10537. this.connection = connection;
  10538. Strophe.addNamespace('PING', "urn:xmpp:ping");
  10539. },
  10540. /**
  10541. * Sends "ping" to given <tt>jid</tt>
  10542. * @param jid the JID to which ping request will be sent.
  10543. * @param success callback called on success.
  10544. * @param error callback called on error.
  10545. * @param timeout ms how long are we going to wait for the response. On
  10546. * timeout <tt>error<//t> callback is called with undefined error
  10547. * argument.
  10548. */
  10549. ping: function (jid, success, error, timeout) {
  10550. var iq = $iq({type: 'get', to: jid});
  10551. iq.c('ping', {xmlns: Strophe.NS.PING});
  10552. this.connection.sendIQ(iq, success, error, timeout);
  10553. },
  10554. /**
  10555. * Checks if given <tt>jid</tt> has XEP-0199 ping support.
  10556. * @param jid the JID to be checked for ping support.
  10557. * @param callback function with boolean argument which will be
  10558. * <tt>true</tt> if XEP-0199 ping is supported by given <tt>jid</tt>
  10559. */
  10560. hasPingSupport: function (jid, callback) {
  10561. this.connection.disco.info(
  10562. jid, null,
  10563. function (result) {
  10564. var ping = $(result).find('>>feature[var="urn:xmpp:ping"]');
  10565. callback(ping.length > 0);
  10566. },
  10567. function (error) {
  10568. logger.error("Ping feature discovery error", error);
  10569. callback(false);
  10570. }
  10571. );
  10572. },
  10573. /**
  10574. * Starts to send ping in given interval to specified remote JID.
  10575. * This plugin supports only one such task and <tt>stopInterval</tt>
  10576. * must be called before starting a new one.
  10577. * @param remoteJid remote JID to which ping requests will be sent to.
  10578. * @param interval task interval in ms.
  10579. */
  10580. startInterval: function (remoteJid, interval) {
  10581. if (this.intervalId) {
  10582. logger.error("Ping task scheduled already");
  10583. return;
  10584. }
  10585. if (!interval)
  10586. interval = PING_INTERVAL;
  10587. var self = this;
  10588. this.intervalId = window.setInterval(function () {
  10589. self.ping(remoteJid,
  10590. function (result) {
  10591. // Ping OK
  10592. self.failedPings = 0;
  10593. },
  10594. function (error) {
  10595. self.failedPings += 1;
  10596. logger.error(
  10597. "Ping " + (error ? "error" : "timeout"), error);
  10598. if (self.failedPings >= PING_THRESHOLD) {
  10599. self.connection.disconnect();
  10600. }
  10601. }, PING_TIMEOUT);
  10602. }, interval);
  10603. logger.info("XMPP pings will be sent every " + interval + " ms");
  10604. },
  10605. /**
  10606. * Stops current "ping" interval task.
  10607. */
  10608. stopInterval: function () {
  10609. if (this.intervalId) {
  10610. window.clearInterval(this.intervalId);
  10611. this.intervalId = null;
  10612. this.failedPings = 0;
  10613. logger.info("Ping interval cleared");
  10614. }
  10615. }
  10616. });
  10617. };
  10618. }).call(this,"/modules/xmpp/strophe.ping.js")
  10619. },{"../../service/xmpp/XMPPEvents":85,"jitsi-meet-logger":47}],39:[function(require,module,exports){
  10620. (function (__filename){
  10621. /* jshint -W117 */
  10622. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10623. module.exports = function() {
  10624. Strophe.addConnectionPlugin('rayo',
  10625. {
  10626. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  10627. connection: null,
  10628. init: function (conn) {
  10629. this.connection = conn;
  10630. if (this.connection.disco) {
  10631. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  10632. }
  10633. this.connection.addHandler(
  10634. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set',
  10635. null, null);
  10636. },
  10637. onRayo: function (iq) {
  10638. logger.info("Rayo IQ", iq);
  10639. },
  10640. dial: function (to, from, roomName, roomPass, focusMucJid) {
  10641. var self = this;
  10642. return new Promise(function (resolve, reject) {
  10643. if(!focusMucJid) {
  10644. reject(new Error("Internal error!"));
  10645. return;
  10646. }
  10647. var req = $iq(
  10648. {
  10649. type: 'set',
  10650. to: focusMucJid
  10651. }
  10652. );
  10653. req.c('dial',
  10654. {
  10655. xmlns: self.RAYO_XMLNS,
  10656. to: to,
  10657. from: from
  10658. });
  10659. req.c('header',
  10660. {
  10661. name: 'JvbRoomName',
  10662. value: roomName
  10663. }).up();
  10664. if (roomPass !== null && roomPass.length) {
  10665. req.c('header',
  10666. {
  10667. name: 'JvbRoomPassword',
  10668. value: roomPass
  10669. }).up();
  10670. }
  10671. self.connection.sendIQ(
  10672. req,
  10673. function (result) {
  10674. logger.info('Dial result ', result);
  10675. var resource = $(result).find('ref').attr('uri');
  10676. self.call_resource =
  10677. resource.substr('xmpp:'.length);
  10678. logger.info(
  10679. "Received call resource: " +
  10680. self.call_resource);
  10681. resolve();
  10682. },
  10683. function (error) {
  10684. logger.info('Dial error ', error);
  10685. reject(error);
  10686. }
  10687. );
  10688. });
  10689. },
  10690. hangup: function () {
  10691. var self = this;
  10692. return new Promise(function (resolve, reject) {
  10693. if (!self.call_resource) {
  10694. reject(new Error("No call in progress"));
  10695. logger.warn("No call in progress");
  10696. return;
  10697. }
  10698. var req = $iq(
  10699. {
  10700. type: 'set',
  10701. to: self.call_resource
  10702. }
  10703. );
  10704. req.c('hangup',
  10705. {
  10706. xmlns: self.RAYO_XMLNS
  10707. });
  10708. self.connection.sendIQ(
  10709. req,
  10710. function (result) {
  10711. logger.info('Hangup result ', result);
  10712. self.call_resource = null;
  10713. resolve();
  10714. },
  10715. function (error) {
  10716. logger.info('Hangup error ', error);
  10717. self.call_resource = null;
  10718. reject(new Error('Hangup error '));
  10719. }
  10720. );
  10721. });
  10722. }
  10723. }
  10724. );
  10725. };
  10726. }).call(this,"/modules/xmpp/strophe.rayo.js")
  10727. },{"jitsi-meet-logger":47}],40:[function(require,module,exports){
  10728. (function (__filename){
  10729. /* global Strophe */
  10730. /**
  10731. * Strophe logger implementation. Logs from level WARN and above.
  10732. */
  10733. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10734. module.exports = function () {
  10735. Strophe.log = function (level, msg) {
  10736. switch (level) {
  10737. case Strophe.LogLevel.WARN:
  10738. logger.warn("Strophe: " + msg);
  10739. break;
  10740. case Strophe.LogLevel.ERROR:
  10741. case Strophe.LogLevel.FATAL:
  10742. logger.error("Strophe: " + msg);
  10743. break;
  10744. }
  10745. };
  10746. Strophe.getStatusString = function (status) {
  10747. switch (status) {
  10748. case Strophe.Status.ERROR:
  10749. return "ERROR";
  10750. case Strophe.Status.CONNECTING:
  10751. return "CONNECTING";
  10752. case Strophe.Status.CONNFAIL:
  10753. return "CONNFAIL";
  10754. case Strophe.Status.AUTHENTICATING:
  10755. return "AUTHENTICATING";
  10756. case Strophe.Status.AUTHFAIL:
  10757. return "AUTHFAIL";
  10758. case Strophe.Status.CONNECTED:
  10759. return "CONNECTED";
  10760. case Strophe.Status.DISCONNECTED:
  10761. return "DISCONNECTED";
  10762. case Strophe.Status.DISCONNECTING:
  10763. return "DISCONNECTING";
  10764. case Strophe.Status.ATTACHED:
  10765. return "ATTACHED";
  10766. default:
  10767. return "unknown";
  10768. }
  10769. };
  10770. };
  10771. }).call(this,"/modules/xmpp/strophe.util.js")
  10772. },{"jitsi-meet-logger":47}],41:[function(require,module,exports){
  10773. (function (__filename){
  10774. /* global $, APP, config, Strophe*/
  10775. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10776. var EventEmitter = require("events");
  10777. var Pako = require("pako");
  10778. var RTCEvents = require("../../service/RTC/RTCEvents");
  10779. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10780. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  10781. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  10782. var RTC = require("../RTC/RTC");
  10783. var authenticatedUser = false;
  10784. function createConnection(bosh) {
  10785. bosh = bosh || '/http-bind';
  10786. // Append token as URL param
  10787. if (this.token) {
  10788. bosh += bosh.indexOf('?') == -1 ?
  10789. '?token=' + this.token : '&token=' + this.token;
  10790. }
  10791. return new Strophe.Connection(bosh);
  10792. };
  10793. //!!!!!!!!!! FIXME: ...
  10794. function initStrophePlugins(XMPP)
  10795. {
  10796. require("./strophe.emuc")(XMPP);
  10797. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  10798. // require("./strophe.moderate")(XMPP, eventEmitter);
  10799. require("./strophe.util")();
  10800. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  10801. require("./strophe.rayo")();
  10802. require("./strophe.logger")();
  10803. }
  10804. //!!!!!!!!!! FIXME: ...
  10805. ///**
  10806. // * If given <tt>localStream</tt> is video one this method will advertise it's
  10807. // * video type in MUC presence.
  10808. // * @param localStream new or modified <tt>LocalStream</tt>.
  10809. // */
  10810. //function broadcastLocalVideoType(localStream) {
  10811. // if (localStream.videoType)
  10812. // XMPP.addToPresence('videoType', localStream.videoType);
  10813. //}
  10814. //
  10815. //function registerListeners() {
  10816. // RTC.addStreamListener(
  10817. // broadcastLocalVideoType,
  10818. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  10819. // );
  10820. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  10821. // XMPP.addToPresence("devices", devices);
  10822. // });
  10823. //}
  10824. function XMPP(options) {
  10825. this.eventEmitter = new EventEmitter();
  10826. this.connection = null;
  10827. this.disconnectInProgress = false;
  10828. this.forceMuted = false;
  10829. this.options = options;
  10830. initStrophePlugins(this);
  10831. // registerListeners();
  10832. this.connection = createConnection(options.bosh);
  10833. }
  10834. XMPP.prototype.getConnection = function(){ return connection; };
  10835. XMPP.prototype._connect = function (jid, password) {
  10836. var self = this;
  10837. // connection.connect() starts the connection process.
  10838. //
  10839. // As the connection process proceeds, the user supplied callback will
  10840. // be triggered multiple times with status updates. The callback should
  10841. // take two arguments - the status code and the error condition.
  10842. //
  10843. // The status code will be one of the values in the Strophe.Status
  10844. // constants. The error condition will be one of the conditions defined
  10845. // in RFC 3920 or the condition ‘strophe-parsererror’.
  10846. //
  10847. // The Parameters wait, hold and route are optional and only relevant
  10848. // for BOSH connections. Please see XEP 124 for a more detailed
  10849. // explanation of the optional parameters.
  10850. //
  10851. // Connection status constants for use by the connection handler
  10852. // callback.
  10853. //
  10854. // Status.ERROR - An error has occurred (websockets specific)
  10855. // Status.CONNECTING - The connection is currently being made
  10856. // Status.CONNFAIL - The connection attempt failed
  10857. // Status.AUTHENTICATING - The connection is authenticating
  10858. // Status.AUTHFAIL - The authentication attempt failed
  10859. // Status.CONNECTED - The connection has succeeded
  10860. // Status.DISCONNECTED - The connection has been terminated
  10861. // Status.DISCONNECTING - The connection is currently being terminated
  10862. // Status.ATTACHED - The connection has been attached
  10863. var anonymousConnectionFailed = false;
  10864. var connectionFailed = false;
  10865. var lastErrorMsg;
  10866. this.connection.connect(jid, password, function (status, msg) {
  10867. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  10868. (msg ? "[" + msg + "]" : "") + "\t:" + window.performance.now());
  10869. if (status === Strophe.Status.CONNECTED) {
  10870. if (self.options.useStunTurn) {
  10871. self.connection.jingle.getStunAndTurnCredentials();
  10872. }
  10873. logger.info("My Jabber ID: " + self.connection.jid);
  10874. // Schedule ping ?
  10875. var pingJid = self.connection.domain;
  10876. self.connection.ping.hasPingSupport(
  10877. pingJid,
  10878. function (hasPing) {
  10879. if (hasPing)
  10880. self.connection.ping.startInterval(pingJid);
  10881. else
  10882. logger.warn("Ping NOT supported by " + pingJid);
  10883. }
  10884. );
  10885. if (password)
  10886. authenticatedUser = true;
  10887. if (self.connection && self.connection.connected &&
  10888. Strophe.getResourceFromJid(self.connection.jid)) {
  10889. // .connected is true while connecting?
  10890. // self.connection.send($pres());
  10891. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  10892. Strophe.getResourceFromJid(self.connection.jid));
  10893. }
  10894. } else if (status === Strophe.Status.CONNFAIL) {
  10895. if (msg === 'x-strophe-bad-non-anon-jid') {
  10896. anonymousConnectionFailed = true;
  10897. }
  10898. else
  10899. {
  10900. connectionFailed = true;
  10901. }
  10902. lastErrorMsg = msg;
  10903. } else if (status === Strophe.Status.DISCONNECTED) {
  10904. // Stop ping interval
  10905. self.connection.ping.stopInterval();
  10906. self.disconnectInProgress = false;
  10907. if (anonymousConnectionFailed) {
  10908. // prompt user for username and password
  10909. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10910. JitsiConnectionErrors.PASSWORD_REQUIRED);
  10911. } else if(connectionFailed) {
  10912. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10913. JitsiConnectionErrors.OTHER_ERROR,
  10914. msg ? msg : lastErrorMsg);
  10915. } else {
  10916. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  10917. msg ? msg : lastErrorMsg);
  10918. }
  10919. } else if (status === Strophe.Status.AUTHFAIL) {
  10920. // wrong password or username, prompt user
  10921. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10922. JitsiConnectionErrors.PASSWORD_REQUIRED);
  10923. }
  10924. });
  10925. }
  10926. XMPP.prototype.connect = function (jid, password) {
  10927. if(!jid) {
  10928. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  10929. // Force authenticated domain if room is appended with '?login=true'
  10930. if (this.options.hosts.anonymousdomain &&
  10931. window.location.search.indexOf("login=true") !== -1) {
  10932. configDomain = this.options.hosts.domain;
  10933. }
  10934. jid = configDomain || window.location.hostname;
  10935. }
  10936. return this._connect(jid, password);
  10937. };
  10938. XMPP.prototype.createRoom = function (roomName, options) {
  10939. var roomjid = roomName + '@' + this.options.hosts.muc;
  10940. if (options.useNicks) {
  10941. if (options.nick) {
  10942. roomjid += '/' + options.nick;
  10943. } else {
  10944. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  10945. }
  10946. } else {
  10947. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  10948. if(!authenticatedUser)
  10949. tmpJid = tmpJid.substr(0, 8);
  10950. roomjid += '/' + tmpJid;
  10951. }
  10952. return this.connection.emuc.createRoom(roomjid, null, options);
  10953. }
  10954. XMPP.prototype.addListener = function(type, listener) {
  10955. this.eventEmitter.on(type, listener);
  10956. };
  10957. XMPP.prototype.removeListener = function (type, listener) {
  10958. this.eventEmitter.removeListener(type, listener);
  10959. };
  10960. //FIXME: this should work with the room
  10961. XMPP.prototype.leaveRoom = function (jid) {
  10962. var handler = this.connection.jingle.jid2session[jid];
  10963. if (handler && handler.peerconnection) {
  10964. // FIXME: probably removing streams is not required and close() should
  10965. // be enough
  10966. if (RTC.localAudio) {
  10967. handler.peerconnection.removeStream(
  10968. RTC.localAudio.getOriginalStream(), true);
  10969. }
  10970. if (RTC.localVideo) {
  10971. handler.peerconnection.removeStream(
  10972. RTC.localVideo.getOriginalStream(), true);
  10973. }
  10974. handler.peerconnection.close();
  10975. }
  10976. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  10977. this.connection.emuc.doLeave(jid);
  10978. };
  10979. /**
  10980. * Sends 'data' as a log message to the focus. Returns true iff a message
  10981. * was sent.
  10982. * @param data
  10983. * @returns {boolean} true iff a message was sent.
  10984. */
  10985. XMPP.prototype.sendLogs = function (data) {
  10986. if(!this.connection.emuc.focusMucJid)
  10987. return false;
  10988. var deflate = true;
  10989. var content = JSON.stringify(data);
  10990. if (deflate) {
  10991. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  10992. }
  10993. content = Base64.encode(content);
  10994. // XEP-0337-ish
  10995. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  10996. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  10997. id: 'PeerConnectionStats'});
  10998. message.c('message').t(content).up();
  10999. if (deflate) {
  11000. message.c('tag', {name: "deflated", value: "true"}).up();
  11001. }
  11002. message.up();
  11003. this.connection.send(message);
  11004. return true;
  11005. };
  11006. // Gets the logs from strophe.jingle.
  11007. XMPP.prototype.getJingleLog = function () {
  11008. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  11009. };
  11010. // Gets the logs from strophe.
  11011. XMPP.prototype.getXmppLog = function () {
  11012. return this.connection.logger ? this.connection.logger.log : null;
  11013. };
  11014. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  11015. this.connection.rayo.dial(to, from, roomName,roomPass);
  11016. };
  11017. XMPP.prototype.setMute = function (jid, mute) {
  11018. this.connection.moderate.setMute(jid, mute);
  11019. };
  11020. XMPP.prototype.eject = function (jid) {
  11021. this.connection.moderate.eject(jid);
  11022. };
  11023. XMPP.prototype.getSessions = function () {
  11024. return this.connection.jingle.sessions;
  11025. };
  11026. XMPP.prototype.disconnect = function () {
  11027. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  11028. {
  11029. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  11030. return;
  11031. }
  11032. this.disconnectInProgress = true;
  11033. this.connection.disconnect();
  11034. };
  11035. module.exports = XMPP;
  11036. }).call(this,"/modules/xmpp/xmpp.js")
  11037. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":79,"../../service/xmpp/XMPPEvents":85,"../RTC/RTC":16,"./strophe.emuc":35,"./strophe.jingle":36,"./strophe.logger":37,"./strophe.ping":38,"./strophe.rayo":39,"./strophe.util":40,"events":43,"jitsi-meet-logger":47,"pako":48}],42:[function(require,module,exports){
  11038. (function (process){
  11039. /*!
  11040. * async
  11041. * https://github.com/caolan/async
  11042. *
  11043. * Copyright 2010-2014 Caolan McMahon
  11044. * Released under the MIT license
  11045. */
  11046. /*jshint onevar: false, indent:4 */
  11047. /*global setImmediate: false, setTimeout: false, console: false */
  11048. (function () {
  11049. var async = {};
  11050. // global on the server, window in the browser
  11051. var root, previous_async;
  11052. root = this;
  11053. if (root != null) {
  11054. previous_async = root.async;
  11055. }
  11056. async.noConflict = function () {
  11057. root.async = previous_async;
  11058. return async;
  11059. };
  11060. function only_once(fn) {
  11061. var called = false;
  11062. return function() {
  11063. if (called) throw new Error("Callback was already called.");
  11064. called = true;
  11065. fn.apply(root, arguments);
  11066. }
  11067. }
  11068. //// cross-browser compatiblity functions ////
  11069. var _toString = Object.prototype.toString;
  11070. var _isArray = Array.isArray || function (obj) {
  11071. return _toString.call(obj) === '[object Array]';
  11072. };
  11073. var _each = function (arr, iterator) {
  11074. if (arr.forEach) {
  11075. return arr.forEach(iterator);
  11076. }
  11077. for (var i = 0; i < arr.length; i += 1) {
  11078. iterator(arr[i], i, arr);
  11079. }
  11080. };
  11081. var _map = function (arr, iterator) {
  11082. if (arr.map) {
  11083. return arr.map(iterator);
  11084. }
  11085. var results = [];
  11086. _each(arr, function (x, i, a) {
  11087. results.push(iterator(x, i, a));
  11088. });
  11089. return results;
  11090. };
  11091. var _reduce = function (arr, iterator, memo) {
  11092. if (arr.reduce) {
  11093. return arr.reduce(iterator, memo);
  11094. }
  11095. _each(arr, function (x, i, a) {
  11096. memo = iterator(memo, x, i, a);
  11097. });
  11098. return memo;
  11099. };
  11100. var _keys = function (obj) {
  11101. if (Object.keys) {
  11102. return Object.keys(obj);
  11103. }
  11104. var keys = [];
  11105. for (var k in obj) {
  11106. if (obj.hasOwnProperty(k)) {
  11107. keys.push(k);
  11108. }
  11109. }
  11110. return keys;
  11111. };
  11112. //// exported async module functions ////
  11113. //// nextTick implementation with browser-compatible fallback ////
  11114. if (typeof process === 'undefined' || !(process.nextTick)) {
  11115. if (typeof setImmediate === 'function') {
  11116. async.nextTick = function (fn) {
  11117. // not a direct alias for IE10 compatibility
  11118. setImmediate(fn);
  11119. };
  11120. async.setImmediate = async.nextTick;
  11121. }
  11122. else {
  11123. async.nextTick = function (fn) {
  11124. setTimeout(fn, 0);
  11125. };
  11126. async.setImmediate = async.nextTick;
  11127. }
  11128. }
  11129. else {
  11130. async.nextTick = process.nextTick;
  11131. if (typeof setImmediate !== 'undefined') {
  11132. async.setImmediate = function (fn) {
  11133. // not a direct alias for IE10 compatibility
  11134. setImmediate(fn);
  11135. };
  11136. }
  11137. else {
  11138. async.setImmediate = async.nextTick;
  11139. }
  11140. }
  11141. async.each = function (arr, iterator, callback) {
  11142. callback = callback || function () {};
  11143. if (!arr.length) {
  11144. return callback();
  11145. }
  11146. var completed = 0;
  11147. _each(arr, function (x) {
  11148. iterator(x, only_once(done) );
  11149. });
  11150. function done(err) {
  11151. if (err) {
  11152. callback(err);
  11153. callback = function () {};
  11154. }
  11155. else {
  11156. completed += 1;
  11157. if (completed >= arr.length) {
  11158. callback();
  11159. }
  11160. }
  11161. }
  11162. };
  11163. async.forEach = async.each;
  11164. async.eachSeries = function (arr, iterator, callback) {
  11165. callback = callback || function () {};
  11166. if (!arr.length) {
  11167. return callback();
  11168. }
  11169. var completed = 0;
  11170. var iterate = function () {
  11171. iterator(arr[completed], function (err) {
  11172. if (err) {
  11173. callback(err);
  11174. callback = function () {};
  11175. }
  11176. else {
  11177. completed += 1;
  11178. if (completed >= arr.length) {
  11179. callback();
  11180. }
  11181. else {
  11182. iterate();
  11183. }
  11184. }
  11185. });
  11186. };
  11187. iterate();
  11188. };
  11189. async.forEachSeries = async.eachSeries;
  11190. async.eachLimit = function (arr, limit, iterator, callback) {
  11191. var fn = _eachLimit(limit);
  11192. fn.apply(null, [arr, iterator, callback]);
  11193. };
  11194. async.forEachLimit = async.eachLimit;
  11195. var _eachLimit = function (limit) {
  11196. return function (arr, iterator, callback) {
  11197. callback = callback || function () {};
  11198. if (!arr.length || limit <= 0) {
  11199. return callback();
  11200. }
  11201. var completed = 0;
  11202. var started = 0;
  11203. var running = 0;
  11204. (function replenish () {
  11205. if (completed >= arr.length) {
  11206. return callback();
  11207. }
  11208. while (running < limit && started < arr.length) {
  11209. started += 1;
  11210. running += 1;
  11211. iterator(arr[started - 1], function (err) {
  11212. if (err) {
  11213. callback(err);
  11214. callback = function () {};
  11215. }
  11216. else {
  11217. completed += 1;
  11218. running -= 1;
  11219. if (completed >= arr.length) {
  11220. callback();
  11221. }
  11222. else {
  11223. replenish();
  11224. }
  11225. }
  11226. });
  11227. }
  11228. })();
  11229. };
  11230. };
  11231. var doParallel = function (fn) {
  11232. return function () {
  11233. var args = Array.prototype.slice.call(arguments);
  11234. return fn.apply(null, [async.each].concat(args));
  11235. };
  11236. };
  11237. var doParallelLimit = function(limit, fn) {
  11238. return function () {
  11239. var args = Array.prototype.slice.call(arguments);
  11240. return fn.apply(null, [_eachLimit(limit)].concat(args));
  11241. };
  11242. };
  11243. var doSeries = function (fn) {
  11244. return function () {
  11245. var args = Array.prototype.slice.call(arguments);
  11246. return fn.apply(null, [async.eachSeries].concat(args));
  11247. };
  11248. };
  11249. var _asyncMap = function (eachfn, arr, iterator, callback) {
  11250. arr = _map(arr, function (x, i) {
  11251. return {index: i, value: x};
  11252. });
  11253. if (!callback) {
  11254. eachfn(arr, function (x, callback) {
  11255. iterator(x.value, function (err) {
  11256. callback(err);
  11257. });
  11258. });
  11259. } else {
  11260. var results = [];
  11261. eachfn(arr, function (x, callback) {
  11262. iterator(x.value, function (err, v) {
  11263. results[x.index] = v;
  11264. callback(err);
  11265. });
  11266. }, function (err) {
  11267. callback(err, results);
  11268. });
  11269. }
  11270. };
  11271. async.map = doParallel(_asyncMap);
  11272. async.mapSeries = doSeries(_asyncMap);
  11273. async.mapLimit = function (arr, limit, iterator, callback) {
  11274. return _mapLimit(limit)(arr, iterator, callback);
  11275. };
  11276. var _mapLimit = function(limit) {
  11277. return doParallelLimit(limit, _asyncMap);
  11278. };
  11279. // reduce only has a series version, as doing reduce in parallel won't
  11280. // work in many situations.
  11281. async.reduce = function (arr, memo, iterator, callback) {
  11282. async.eachSeries(arr, function (x, callback) {
  11283. iterator(memo, x, function (err, v) {
  11284. memo = v;
  11285. callback(err);
  11286. });
  11287. }, function (err) {
  11288. callback(err, memo);
  11289. });
  11290. };
  11291. // inject alias
  11292. async.inject = async.reduce;
  11293. // foldl alias
  11294. async.foldl = async.reduce;
  11295. async.reduceRight = function (arr, memo, iterator, callback) {
  11296. var reversed = _map(arr, function (x) {
  11297. return x;
  11298. }).reverse();
  11299. async.reduce(reversed, memo, iterator, callback);
  11300. };
  11301. // foldr alias
  11302. async.foldr = async.reduceRight;
  11303. var _filter = function (eachfn, arr, iterator, callback) {
  11304. var results = [];
  11305. arr = _map(arr, function (x, i) {
  11306. return {index: i, value: x};
  11307. });
  11308. eachfn(arr, function (x, callback) {
  11309. iterator(x.value, function (v) {
  11310. if (v) {
  11311. results.push(x);
  11312. }
  11313. callback();
  11314. });
  11315. }, function (err) {
  11316. callback(_map(results.sort(function (a, b) {
  11317. return a.index - b.index;
  11318. }), function (x) {
  11319. return x.value;
  11320. }));
  11321. });
  11322. };
  11323. async.filter = doParallel(_filter);
  11324. async.filterSeries = doSeries(_filter);
  11325. // select alias
  11326. async.select = async.filter;
  11327. async.selectSeries = async.filterSeries;
  11328. var _reject = function (eachfn, arr, iterator, callback) {
  11329. var results = [];
  11330. arr = _map(arr, function (x, i) {
  11331. return {index: i, value: x};
  11332. });
  11333. eachfn(arr, function (x, callback) {
  11334. iterator(x.value, function (v) {
  11335. if (!v) {
  11336. results.push(x);
  11337. }
  11338. callback();
  11339. });
  11340. }, function (err) {
  11341. callback(_map(results.sort(function (a, b) {
  11342. return a.index - b.index;
  11343. }), function (x) {
  11344. return x.value;
  11345. }));
  11346. });
  11347. };
  11348. async.reject = doParallel(_reject);
  11349. async.rejectSeries = doSeries(_reject);
  11350. var _detect = function (eachfn, arr, iterator, main_callback) {
  11351. eachfn(arr, function (x, callback) {
  11352. iterator(x, function (result) {
  11353. if (result) {
  11354. main_callback(x);
  11355. main_callback = function () {};
  11356. }
  11357. else {
  11358. callback();
  11359. }
  11360. });
  11361. }, function (err) {
  11362. main_callback();
  11363. });
  11364. };
  11365. async.detect = doParallel(_detect);
  11366. async.detectSeries = doSeries(_detect);
  11367. async.some = function (arr, iterator, main_callback) {
  11368. async.each(arr, function (x, callback) {
  11369. iterator(x, function (v) {
  11370. if (v) {
  11371. main_callback(true);
  11372. main_callback = function () {};
  11373. }
  11374. callback();
  11375. });
  11376. }, function (err) {
  11377. main_callback(false);
  11378. });
  11379. };
  11380. // any alias
  11381. async.any = async.some;
  11382. async.every = function (arr, iterator, main_callback) {
  11383. async.each(arr, function (x, callback) {
  11384. iterator(x, function (v) {
  11385. if (!v) {
  11386. main_callback(false);
  11387. main_callback = function () {};
  11388. }
  11389. callback();
  11390. });
  11391. }, function (err) {
  11392. main_callback(true);
  11393. });
  11394. };
  11395. // all alias
  11396. async.all = async.every;
  11397. async.sortBy = function (arr, iterator, callback) {
  11398. async.map(arr, function (x, callback) {
  11399. iterator(x, function (err, criteria) {
  11400. if (err) {
  11401. callback(err);
  11402. }
  11403. else {
  11404. callback(null, {value: x, criteria: criteria});
  11405. }
  11406. });
  11407. }, function (err, results) {
  11408. if (err) {
  11409. return callback(err);
  11410. }
  11411. else {
  11412. var fn = function (left, right) {
  11413. var a = left.criteria, b = right.criteria;
  11414. return a < b ? -1 : a > b ? 1 : 0;
  11415. };
  11416. callback(null, _map(results.sort(fn), function (x) {
  11417. return x.value;
  11418. }));
  11419. }
  11420. });
  11421. };
  11422. async.auto = function (tasks, callback) {
  11423. callback = callback || function () {};
  11424. var keys = _keys(tasks);
  11425. var remainingTasks = keys.length
  11426. if (!remainingTasks) {
  11427. return callback();
  11428. }
  11429. var results = {};
  11430. var listeners = [];
  11431. var addListener = function (fn) {
  11432. listeners.unshift(fn);
  11433. };
  11434. var removeListener = function (fn) {
  11435. for (var i = 0; i < listeners.length; i += 1) {
  11436. if (listeners[i] === fn) {
  11437. listeners.splice(i, 1);
  11438. return;
  11439. }
  11440. }
  11441. };
  11442. var taskComplete = function () {
  11443. remainingTasks--
  11444. _each(listeners.slice(0), function (fn) {
  11445. fn();
  11446. });
  11447. };
  11448. addListener(function () {
  11449. if (!remainingTasks) {
  11450. var theCallback = callback;
  11451. // prevent final callback from calling itself if it errors
  11452. callback = function () {};
  11453. theCallback(null, results);
  11454. }
  11455. });
  11456. _each(keys, function (k) {
  11457. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  11458. var taskCallback = function (err) {
  11459. var args = Array.prototype.slice.call(arguments, 1);
  11460. if (args.length <= 1) {
  11461. args = args[0];
  11462. }
  11463. if (err) {
  11464. var safeResults = {};
  11465. _each(_keys(results), function(rkey) {
  11466. safeResults[rkey] = results[rkey];
  11467. });
  11468. safeResults[k] = args;
  11469. callback(err, safeResults);
  11470. // stop subsequent errors hitting callback multiple times
  11471. callback = function () {};
  11472. }
  11473. else {
  11474. results[k] = args;
  11475. async.setImmediate(taskComplete);
  11476. }
  11477. };
  11478. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  11479. var ready = function () {
  11480. return _reduce(requires, function (a, x) {
  11481. return (a && results.hasOwnProperty(x));
  11482. }, true) && !results.hasOwnProperty(k);
  11483. };
  11484. if (ready()) {
  11485. task[task.length - 1](taskCallback, results);
  11486. }
  11487. else {
  11488. var listener = function () {
  11489. if (ready()) {
  11490. removeListener(listener);
  11491. task[task.length - 1](taskCallback, results);
  11492. }
  11493. };
  11494. addListener(listener);
  11495. }
  11496. });
  11497. };
  11498. async.retry = function(times, task, callback) {
  11499. var DEFAULT_TIMES = 5;
  11500. var attempts = [];
  11501. // Use defaults if times not passed
  11502. if (typeof times === 'function') {
  11503. callback = task;
  11504. task = times;
  11505. times = DEFAULT_TIMES;
  11506. }
  11507. // Make sure times is a number
  11508. times = parseInt(times, 10) || DEFAULT_TIMES;
  11509. var wrappedTask = function(wrappedCallback, wrappedResults) {
  11510. var retryAttempt = function(task, finalAttempt) {
  11511. return function(seriesCallback) {
  11512. task(function(err, result){
  11513. seriesCallback(!err || finalAttempt, {err: err, result: result});
  11514. }, wrappedResults);
  11515. };
  11516. };
  11517. while (times) {
  11518. attempts.push(retryAttempt(task, !(times-=1)));
  11519. }
  11520. async.series(attempts, function(done, data){
  11521. data = data[data.length - 1];
  11522. (wrappedCallback || callback)(data.err, data.result);
  11523. });
  11524. }
  11525. // If a callback is passed, run this as a controll flow
  11526. return callback ? wrappedTask() : wrappedTask
  11527. };
  11528. async.waterfall = function (tasks, callback) {
  11529. callback = callback || function () {};
  11530. if (!_isArray(tasks)) {
  11531. var err = new Error('First argument to waterfall must be an array of functions');
  11532. return callback(err);
  11533. }
  11534. if (!tasks.length) {
  11535. return callback();
  11536. }
  11537. var wrapIterator = function (iterator) {
  11538. return function (err) {
  11539. if (err) {
  11540. callback.apply(null, arguments);
  11541. callback = function () {};
  11542. }
  11543. else {
  11544. var args = Array.prototype.slice.call(arguments, 1);
  11545. var next = iterator.next();
  11546. if (next) {
  11547. args.push(wrapIterator(next));
  11548. }
  11549. else {
  11550. args.push(callback);
  11551. }
  11552. async.setImmediate(function () {
  11553. iterator.apply(null, args);
  11554. });
  11555. }
  11556. };
  11557. };
  11558. wrapIterator(async.iterator(tasks))();
  11559. };
  11560. var _parallel = function(eachfn, tasks, callback) {
  11561. callback = callback || function () {};
  11562. if (_isArray(tasks)) {
  11563. eachfn.map(tasks, function (fn, callback) {
  11564. if (fn) {
  11565. fn(function (err) {
  11566. var args = Array.prototype.slice.call(arguments, 1);
  11567. if (args.length <= 1) {
  11568. args = args[0];
  11569. }
  11570. callback.call(null, err, args);
  11571. });
  11572. }
  11573. }, callback);
  11574. }
  11575. else {
  11576. var results = {};
  11577. eachfn.each(_keys(tasks), function (k, callback) {
  11578. tasks[k](function (err) {
  11579. var args = Array.prototype.slice.call(arguments, 1);
  11580. if (args.length <= 1) {
  11581. args = args[0];
  11582. }
  11583. results[k] = args;
  11584. callback(err);
  11585. });
  11586. }, function (err) {
  11587. callback(err, results);
  11588. });
  11589. }
  11590. };
  11591. async.parallel = function (tasks, callback) {
  11592. _parallel({ map: async.map, each: async.each }, tasks, callback);
  11593. };
  11594. async.parallelLimit = function(tasks, limit, callback) {
  11595. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  11596. };
  11597. async.series = function (tasks, callback) {
  11598. callback = callback || function () {};
  11599. if (_isArray(tasks)) {
  11600. async.mapSeries(tasks, function (fn, callback) {
  11601. if (fn) {
  11602. fn(function (err) {
  11603. var args = Array.prototype.slice.call(arguments, 1);
  11604. if (args.length <= 1) {
  11605. args = args[0];
  11606. }
  11607. callback.call(null, err, args);
  11608. });
  11609. }
  11610. }, callback);
  11611. }
  11612. else {
  11613. var results = {};
  11614. async.eachSeries(_keys(tasks), function (k, callback) {
  11615. tasks[k](function (err) {
  11616. var args = Array.prototype.slice.call(arguments, 1);
  11617. if (args.length <= 1) {
  11618. args = args[0];
  11619. }
  11620. results[k] = args;
  11621. callback(err);
  11622. });
  11623. }, function (err) {
  11624. callback(err, results);
  11625. });
  11626. }
  11627. };
  11628. async.iterator = function (tasks) {
  11629. var makeCallback = function (index) {
  11630. var fn = function () {
  11631. if (tasks.length) {
  11632. tasks[index].apply(null, arguments);
  11633. }
  11634. return fn.next();
  11635. };
  11636. fn.next = function () {
  11637. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  11638. };
  11639. return fn;
  11640. };
  11641. return makeCallback(0);
  11642. };
  11643. async.apply = function (fn) {
  11644. var args = Array.prototype.slice.call(arguments, 1);
  11645. return function () {
  11646. return fn.apply(
  11647. null, args.concat(Array.prototype.slice.call(arguments))
  11648. );
  11649. };
  11650. };
  11651. var _concat = function (eachfn, arr, fn, callback) {
  11652. var r = [];
  11653. eachfn(arr, function (x, cb) {
  11654. fn(x, function (err, y) {
  11655. r = r.concat(y || []);
  11656. cb(err);
  11657. });
  11658. }, function (err) {
  11659. callback(err, r);
  11660. });
  11661. };
  11662. async.concat = doParallel(_concat);
  11663. async.concatSeries = doSeries(_concat);
  11664. async.whilst = function (test, iterator, callback) {
  11665. if (test()) {
  11666. iterator(function (err) {
  11667. if (err) {
  11668. return callback(err);
  11669. }
  11670. async.whilst(test, iterator, callback);
  11671. });
  11672. }
  11673. else {
  11674. callback();
  11675. }
  11676. };
  11677. async.doWhilst = function (iterator, test, callback) {
  11678. iterator(function (err) {
  11679. if (err) {
  11680. return callback(err);
  11681. }
  11682. var args = Array.prototype.slice.call(arguments, 1);
  11683. if (test.apply(null, args)) {
  11684. async.doWhilst(iterator, test, callback);
  11685. }
  11686. else {
  11687. callback();
  11688. }
  11689. });
  11690. };
  11691. async.until = function (test, iterator, callback) {
  11692. if (!test()) {
  11693. iterator(function (err) {
  11694. if (err) {
  11695. return callback(err);
  11696. }
  11697. async.until(test, iterator, callback);
  11698. });
  11699. }
  11700. else {
  11701. callback();
  11702. }
  11703. };
  11704. async.doUntil = function (iterator, test, callback) {
  11705. iterator(function (err) {
  11706. if (err) {
  11707. return callback(err);
  11708. }
  11709. var args = Array.prototype.slice.call(arguments, 1);
  11710. if (!test.apply(null, args)) {
  11711. async.doUntil(iterator, test, callback);
  11712. }
  11713. else {
  11714. callback();
  11715. }
  11716. });
  11717. };
  11718. async.queue = function (worker, concurrency) {
  11719. if (concurrency === undefined) {
  11720. concurrency = 1;
  11721. }
  11722. function _insert(q, data, pos, callback) {
  11723. if (!q.started){
  11724. q.started = true;
  11725. }
  11726. if (!_isArray(data)) {
  11727. data = [data];
  11728. }
  11729. if(data.length == 0) {
  11730. // call drain immediately if there are no tasks
  11731. return async.setImmediate(function() {
  11732. if (q.drain) {
  11733. q.drain();
  11734. }
  11735. });
  11736. }
  11737. _each(data, function(task) {
  11738. var item = {
  11739. data: task,
  11740. callback: typeof callback === 'function' ? callback : null
  11741. };
  11742. if (pos) {
  11743. q.tasks.unshift(item);
  11744. } else {
  11745. q.tasks.push(item);
  11746. }
  11747. if (q.saturated && q.tasks.length === q.concurrency) {
  11748. q.saturated();
  11749. }
  11750. async.setImmediate(q.process);
  11751. });
  11752. }
  11753. var workers = 0;
  11754. var q = {
  11755. tasks: [],
  11756. concurrency: concurrency,
  11757. saturated: null,
  11758. empty: null,
  11759. drain: null,
  11760. started: false,
  11761. paused: false,
  11762. push: function (data, callback) {
  11763. _insert(q, data, false, callback);
  11764. },
  11765. kill: function () {
  11766. q.drain = null;
  11767. q.tasks = [];
  11768. },
  11769. unshift: function (data, callback) {
  11770. _insert(q, data, true, callback);
  11771. },
  11772. process: function () {
  11773. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  11774. var task = q.tasks.shift();
  11775. if (q.empty && q.tasks.length === 0) {
  11776. q.empty();
  11777. }
  11778. workers += 1;
  11779. var next = function () {
  11780. workers -= 1;
  11781. if (task.callback) {
  11782. task.callback.apply(task, arguments);
  11783. }
  11784. if (q.drain && q.tasks.length + workers === 0) {
  11785. q.drain();
  11786. }
  11787. q.process();
  11788. };
  11789. var cb = only_once(next);
  11790. worker(task.data, cb);
  11791. }
  11792. },
  11793. length: function () {
  11794. return q.tasks.length;
  11795. },
  11796. running: function () {
  11797. return workers;
  11798. },
  11799. idle: function() {
  11800. return q.tasks.length + workers === 0;
  11801. },
  11802. pause: function () {
  11803. if (q.paused === true) { return; }
  11804. q.paused = true;
  11805. q.process();
  11806. },
  11807. resume: function () {
  11808. if (q.paused === false) { return; }
  11809. q.paused = false;
  11810. q.process();
  11811. }
  11812. };
  11813. return q;
  11814. };
  11815. async.priorityQueue = function (worker, concurrency) {
  11816. function _compareTasks(a, b){
  11817. return a.priority - b.priority;
  11818. };
  11819. function _binarySearch(sequence, item, compare) {
  11820. var beg = -1,
  11821. end = sequence.length - 1;
  11822. while (beg < end) {
  11823. var mid = beg + ((end - beg + 1) >>> 1);
  11824. if (compare(item, sequence[mid]) >= 0) {
  11825. beg = mid;
  11826. } else {
  11827. end = mid - 1;
  11828. }
  11829. }
  11830. return beg;
  11831. }
  11832. function _insert(q, data, priority, callback) {
  11833. if (!q.started){
  11834. q.started = true;
  11835. }
  11836. if (!_isArray(data)) {
  11837. data = [data];
  11838. }
  11839. if(data.length == 0) {
  11840. // call drain immediately if there are no tasks
  11841. return async.setImmediate(function() {
  11842. if (q.drain) {
  11843. q.drain();
  11844. }
  11845. });
  11846. }
  11847. _each(data, function(task) {
  11848. var item = {
  11849. data: task,
  11850. priority: priority,
  11851. callback: typeof callback === 'function' ? callback : null
  11852. };
  11853. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  11854. if (q.saturated && q.tasks.length === q.concurrency) {
  11855. q.saturated();
  11856. }
  11857. async.setImmediate(q.process);
  11858. });
  11859. }
  11860. // Start with a normal queue
  11861. var q = async.queue(worker, concurrency);
  11862. // Override push to accept second parameter representing priority
  11863. q.push = function (data, priority, callback) {
  11864. _insert(q, data, priority, callback);
  11865. };
  11866. // Remove unshift function
  11867. delete q.unshift;
  11868. return q;
  11869. };
  11870. async.cargo = function (worker, payload) {
  11871. var working = false,
  11872. tasks = [];
  11873. var cargo = {
  11874. tasks: tasks,
  11875. payload: payload,
  11876. saturated: null,
  11877. empty: null,
  11878. drain: null,
  11879. drained: true,
  11880. push: function (data, callback) {
  11881. if (!_isArray(data)) {
  11882. data = [data];
  11883. }
  11884. _each(data, function(task) {
  11885. tasks.push({
  11886. data: task,
  11887. callback: typeof callback === 'function' ? callback : null
  11888. });
  11889. cargo.drained = false;
  11890. if (cargo.saturated && tasks.length === payload) {
  11891. cargo.saturated();
  11892. }
  11893. });
  11894. async.setImmediate(cargo.process);
  11895. },
  11896. process: function process() {
  11897. if (working) return;
  11898. if (tasks.length === 0) {
  11899. if(cargo.drain && !cargo.drained) cargo.drain();
  11900. cargo.drained = true;
  11901. return;
  11902. }
  11903. var ts = typeof payload === 'number'
  11904. ? tasks.splice(0, payload)
  11905. : tasks.splice(0, tasks.length);
  11906. var ds = _map(ts, function (task) {
  11907. return task.data;
  11908. });
  11909. if(cargo.empty) cargo.empty();
  11910. working = true;
  11911. worker(ds, function () {
  11912. working = false;
  11913. var args = arguments;
  11914. _each(ts, function (data) {
  11915. if (data.callback) {
  11916. data.callback.apply(null, args);
  11917. }
  11918. });
  11919. process();
  11920. });
  11921. },
  11922. length: function () {
  11923. return tasks.length;
  11924. },
  11925. running: function () {
  11926. return working;
  11927. }
  11928. };
  11929. return cargo;
  11930. };
  11931. var _console_fn = function (name) {
  11932. return function (fn) {
  11933. var args = Array.prototype.slice.call(arguments, 1);
  11934. fn.apply(null, args.concat([function (err) {
  11935. var args = Array.prototype.slice.call(arguments, 1);
  11936. if (typeof console !== 'undefined') {
  11937. if (err) {
  11938. if (console.error) {
  11939. console.error(err);
  11940. }
  11941. }
  11942. else if (console[name]) {
  11943. _each(args, function (x) {
  11944. console[name](x);
  11945. });
  11946. }
  11947. }
  11948. }]));
  11949. };
  11950. };
  11951. async.log = _console_fn('log');
  11952. async.dir = _console_fn('dir');
  11953. /*async.info = _console_fn('info');
  11954. async.warn = _console_fn('warn');
  11955. async.error = _console_fn('error');*/
  11956. async.memoize = function (fn, hasher) {
  11957. var memo = {};
  11958. var queues = {};
  11959. hasher = hasher || function (x) {
  11960. return x;
  11961. };
  11962. var memoized = function () {
  11963. var args = Array.prototype.slice.call(arguments);
  11964. var callback = args.pop();
  11965. var key = hasher.apply(null, args);
  11966. if (key in memo) {
  11967. async.nextTick(function () {
  11968. callback.apply(null, memo[key]);
  11969. });
  11970. }
  11971. else if (key in queues) {
  11972. queues[key].push(callback);
  11973. }
  11974. else {
  11975. queues[key] = [callback];
  11976. fn.apply(null, args.concat([function () {
  11977. memo[key] = arguments;
  11978. var q = queues[key];
  11979. delete queues[key];
  11980. for (var i = 0, l = q.length; i < l; i++) {
  11981. q[i].apply(null, arguments);
  11982. }
  11983. }]));
  11984. }
  11985. };
  11986. memoized.memo = memo;
  11987. memoized.unmemoized = fn;
  11988. return memoized;
  11989. };
  11990. async.unmemoize = function (fn) {
  11991. return function () {
  11992. return (fn.unmemoized || fn).apply(null, arguments);
  11993. };
  11994. };
  11995. async.times = function (count, iterator, callback) {
  11996. var counter = [];
  11997. for (var i = 0; i < count; i++) {
  11998. counter.push(i);
  11999. }
  12000. return async.map(counter, iterator, callback);
  12001. };
  12002. async.timesSeries = function (count, iterator, callback) {
  12003. var counter = [];
  12004. for (var i = 0; i < count; i++) {
  12005. counter.push(i);
  12006. }
  12007. return async.mapSeries(counter, iterator, callback);
  12008. };
  12009. async.seq = function (/* functions... */) {
  12010. var fns = arguments;
  12011. return function () {
  12012. var that = this;
  12013. var args = Array.prototype.slice.call(arguments);
  12014. var callback = args.pop();
  12015. async.reduce(fns, args, function (newargs, fn, cb) {
  12016. fn.apply(that, newargs.concat([function () {
  12017. var err = arguments[0];
  12018. var nextargs = Array.prototype.slice.call(arguments, 1);
  12019. cb(err, nextargs);
  12020. }]))
  12021. },
  12022. function (err, results) {
  12023. callback.apply(that, [err].concat(results));
  12024. });
  12025. };
  12026. };
  12027. async.compose = function (/* functions... */) {
  12028. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  12029. };
  12030. var _applyEach = function (eachfn, fns /*args...*/) {
  12031. var go = function () {
  12032. var that = this;
  12033. var args = Array.prototype.slice.call(arguments);
  12034. var callback = args.pop();
  12035. return eachfn(fns, function (fn, cb) {
  12036. fn.apply(that, args.concat([cb]));
  12037. },
  12038. callback);
  12039. };
  12040. if (arguments.length > 2) {
  12041. var args = Array.prototype.slice.call(arguments, 2);
  12042. return go.apply(this, args);
  12043. }
  12044. else {
  12045. return go;
  12046. }
  12047. };
  12048. async.applyEach = doParallel(_applyEach);
  12049. async.applyEachSeries = doSeries(_applyEach);
  12050. async.forever = function (fn, callback) {
  12051. function next(err) {
  12052. if (err) {
  12053. if (callback) {
  12054. return callback(err);
  12055. }
  12056. throw err;
  12057. }
  12058. fn(next);
  12059. }
  12060. next();
  12061. };
  12062. // Node.js
  12063. if (typeof module !== 'undefined' && module.exports) {
  12064. module.exports = async;
  12065. }
  12066. // AMD / RequireJS
  12067. else if (typeof define !== 'undefined' && define.amd) {
  12068. define([], function () {
  12069. return async;
  12070. });
  12071. }
  12072. // included directly via <script> tag
  12073. else {
  12074. root.async = async;
  12075. }
  12076. }());
  12077. }).call(this,require('_process'))
  12078. },{"_process":44}],43:[function(require,module,exports){
  12079. // Copyright Joyent, Inc. and other Node contributors.
  12080. //
  12081. // Permission is hereby granted, free of charge, to any person obtaining a
  12082. // copy of this software and associated documentation files (the
  12083. // "Software"), to deal in the Software without restriction, including
  12084. // without limitation the rights to use, copy, modify, merge, publish,
  12085. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12086. // persons to whom the Software is furnished to do so, subject to the
  12087. // following conditions:
  12088. //
  12089. // The above copyright notice and this permission notice shall be included
  12090. // in all copies or substantial portions of the Software.
  12091. //
  12092. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12093. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12094. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12095. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12096. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12097. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12098. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12099. function EventEmitter() {
  12100. this._events = this._events || {};
  12101. this._maxListeners = this._maxListeners || undefined;
  12102. }
  12103. module.exports = EventEmitter;
  12104. // Backwards-compat with node 0.10.x
  12105. EventEmitter.EventEmitter = EventEmitter;
  12106. EventEmitter.prototype._events = undefined;
  12107. EventEmitter.prototype._maxListeners = undefined;
  12108. // By default EventEmitters will print a warning if more than 10 listeners are
  12109. // added to it. This is a useful default which helps finding memory leaks.
  12110. EventEmitter.defaultMaxListeners = 10;
  12111. // Obviously not all Emitters should be limited to 10. This function allows
  12112. // that to be increased. Set to zero for unlimited.
  12113. EventEmitter.prototype.setMaxListeners = function(n) {
  12114. if (!isNumber(n) || n < 0 || isNaN(n))
  12115. throw TypeError('n must be a positive number');
  12116. this._maxListeners = n;
  12117. return this;
  12118. };
  12119. EventEmitter.prototype.emit = function(type) {
  12120. var er, handler, len, args, i, listeners;
  12121. if (!this._events)
  12122. this._events = {};
  12123. // If there is no 'error' event listener then throw.
  12124. if (type === 'error') {
  12125. if (!this._events.error ||
  12126. (isObject(this._events.error) && !this._events.error.length)) {
  12127. er = arguments[1];
  12128. if (er instanceof Error) {
  12129. throw er; // Unhandled 'error' event
  12130. }
  12131. throw TypeError('Uncaught, unspecified "error" event.');
  12132. }
  12133. }
  12134. handler = this._events[type];
  12135. if (isUndefined(handler))
  12136. return false;
  12137. if (isFunction(handler)) {
  12138. switch (arguments.length) {
  12139. // fast cases
  12140. case 1:
  12141. handler.call(this);
  12142. break;
  12143. case 2:
  12144. handler.call(this, arguments[1]);
  12145. break;
  12146. case 3:
  12147. handler.call(this, arguments[1], arguments[2]);
  12148. break;
  12149. // slower
  12150. default:
  12151. len = arguments.length;
  12152. args = new Array(len - 1);
  12153. for (i = 1; i < len; i++)
  12154. args[i - 1] = arguments[i];
  12155. handler.apply(this, args);
  12156. }
  12157. } else if (isObject(handler)) {
  12158. len = arguments.length;
  12159. args = new Array(len - 1);
  12160. for (i = 1; i < len; i++)
  12161. args[i - 1] = arguments[i];
  12162. listeners = handler.slice();
  12163. len = listeners.length;
  12164. for (i = 0; i < len; i++)
  12165. listeners[i].apply(this, args);
  12166. }
  12167. return true;
  12168. };
  12169. EventEmitter.prototype.addListener = function(type, listener) {
  12170. var m;
  12171. if (!isFunction(listener))
  12172. throw TypeError('listener must be a function');
  12173. if (!this._events)
  12174. this._events = {};
  12175. // To avoid recursion in the case that type === "newListener"! Before
  12176. // adding it to the listeners, first emit "newListener".
  12177. if (this._events.newListener)
  12178. this.emit('newListener', type,
  12179. isFunction(listener.listener) ?
  12180. listener.listener : listener);
  12181. if (!this._events[type])
  12182. // Optimize the case of one listener. Don't need the extra array object.
  12183. this._events[type] = listener;
  12184. else if (isObject(this._events[type]))
  12185. // If we've already got an array, just append.
  12186. this._events[type].push(listener);
  12187. else
  12188. // Adding the second element, need to change to array.
  12189. this._events[type] = [this._events[type], listener];
  12190. // Check for listener leak
  12191. if (isObject(this._events[type]) && !this._events[type].warned) {
  12192. var m;
  12193. if (!isUndefined(this._maxListeners)) {
  12194. m = this._maxListeners;
  12195. } else {
  12196. m = EventEmitter.defaultMaxListeners;
  12197. }
  12198. if (m && m > 0 && this._events[type].length > m) {
  12199. this._events[type].warned = true;
  12200. console.error('(node) warning: possible EventEmitter memory ' +
  12201. 'leak detected. %d listeners added. ' +
  12202. 'Use emitter.setMaxListeners() to increase limit.',
  12203. this._events[type].length);
  12204. if (typeof console.trace === 'function') {
  12205. // not supported in IE 10
  12206. console.trace();
  12207. }
  12208. }
  12209. }
  12210. return this;
  12211. };
  12212. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  12213. EventEmitter.prototype.once = function(type, listener) {
  12214. if (!isFunction(listener))
  12215. throw TypeError('listener must be a function');
  12216. var fired = false;
  12217. function g() {
  12218. this.removeListener(type, g);
  12219. if (!fired) {
  12220. fired = true;
  12221. listener.apply(this, arguments);
  12222. }
  12223. }
  12224. g.listener = listener;
  12225. this.on(type, g);
  12226. return this;
  12227. };
  12228. // emits a 'removeListener' event iff the listener was removed
  12229. EventEmitter.prototype.removeListener = function(type, listener) {
  12230. var list, position, length, i;
  12231. if (!isFunction(listener))
  12232. throw TypeError('listener must be a function');
  12233. if (!this._events || !this._events[type])
  12234. return this;
  12235. list = this._events[type];
  12236. length = list.length;
  12237. position = -1;
  12238. if (list === listener ||
  12239. (isFunction(list.listener) && list.listener === listener)) {
  12240. delete this._events[type];
  12241. if (this._events.removeListener)
  12242. this.emit('removeListener', type, listener);
  12243. } else if (isObject(list)) {
  12244. for (i = length; i-- > 0;) {
  12245. if (list[i] === listener ||
  12246. (list[i].listener && list[i].listener === listener)) {
  12247. position = i;
  12248. break;
  12249. }
  12250. }
  12251. if (position < 0)
  12252. return this;
  12253. if (list.length === 1) {
  12254. list.length = 0;
  12255. delete this._events[type];
  12256. } else {
  12257. list.splice(position, 1);
  12258. }
  12259. if (this._events.removeListener)
  12260. this.emit('removeListener', type, listener);
  12261. }
  12262. return this;
  12263. };
  12264. EventEmitter.prototype.removeAllListeners = function(type) {
  12265. var key, listeners;
  12266. if (!this._events)
  12267. return this;
  12268. // not listening for removeListener, no need to emit
  12269. if (!this._events.removeListener) {
  12270. if (arguments.length === 0)
  12271. this._events = {};
  12272. else if (this._events[type])
  12273. delete this._events[type];
  12274. return this;
  12275. }
  12276. // emit removeListener for all listeners on all events
  12277. if (arguments.length === 0) {
  12278. for (key in this._events) {
  12279. if (key === 'removeListener') continue;
  12280. this.removeAllListeners(key);
  12281. }
  12282. this.removeAllListeners('removeListener');
  12283. this._events = {};
  12284. return this;
  12285. }
  12286. listeners = this._events[type];
  12287. if (isFunction(listeners)) {
  12288. this.removeListener(type, listeners);
  12289. } else {
  12290. // LIFO order
  12291. while (listeners.length)
  12292. this.removeListener(type, listeners[listeners.length - 1]);
  12293. }
  12294. delete this._events[type];
  12295. return this;
  12296. };
  12297. EventEmitter.prototype.listeners = function(type) {
  12298. var ret;
  12299. if (!this._events || !this._events[type])
  12300. ret = [];
  12301. else if (isFunction(this._events[type]))
  12302. ret = [this._events[type]];
  12303. else
  12304. ret = this._events[type].slice();
  12305. return ret;
  12306. };
  12307. EventEmitter.listenerCount = function(emitter, type) {
  12308. var ret;
  12309. if (!emitter._events || !emitter._events[type])
  12310. ret = 0;
  12311. else if (isFunction(emitter._events[type]))
  12312. ret = 1;
  12313. else
  12314. ret = emitter._events[type].length;
  12315. return ret;
  12316. };
  12317. function isFunction(arg) {
  12318. return typeof arg === 'function';
  12319. }
  12320. function isNumber(arg) {
  12321. return typeof arg === 'number';
  12322. }
  12323. function isObject(arg) {
  12324. return typeof arg === 'object' && arg !== null;
  12325. }
  12326. function isUndefined(arg) {
  12327. return arg === void 0;
  12328. }
  12329. },{}],44:[function(require,module,exports){
  12330. // shim for using process in browser
  12331. var process = module.exports = {};
  12332. var queue = [];
  12333. var draining = false;
  12334. var currentQueue;
  12335. var queueIndex = -1;
  12336. function cleanUpNextTick() {
  12337. draining = false;
  12338. if (currentQueue.length) {
  12339. queue = currentQueue.concat(queue);
  12340. } else {
  12341. queueIndex = -1;
  12342. }
  12343. if (queue.length) {
  12344. drainQueue();
  12345. }
  12346. }
  12347. function drainQueue() {
  12348. if (draining) {
  12349. return;
  12350. }
  12351. var timeout = setTimeout(cleanUpNextTick);
  12352. draining = true;
  12353. var len = queue.length;
  12354. while(len) {
  12355. currentQueue = queue;
  12356. queue = [];
  12357. while (++queueIndex < len) {
  12358. if (currentQueue) {
  12359. currentQueue[queueIndex].run();
  12360. }
  12361. }
  12362. queueIndex = -1;
  12363. len = queue.length;
  12364. }
  12365. currentQueue = null;
  12366. draining = false;
  12367. clearTimeout(timeout);
  12368. }
  12369. process.nextTick = function (fun) {
  12370. var args = new Array(arguments.length - 1);
  12371. if (arguments.length > 1) {
  12372. for (var i = 1; i < arguments.length; i++) {
  12373. args[i - 1] = arguments[i];
  12374. }
  12375. }
  12376. queue.push(new Item(fun, args));
  12377. if (queue.length === 1 && !draining) {
  12378. setTimeout(drainQueue, 0);
  12379. }
  12380. };
  12381. // v8 likes predictible objects
  12382. function Item(fun, array) {
  12383. this.fun = fun;
  12384. this.array = array;
  12385. }
  12386. Item.prototype.run = function () {
  12387. this.fun.apply(null, this.array);
  12388. };
  12389. process.title = 'browser';
  12390. process.browser = true;
  12391. process.env = {};
  12392. process.argv = [];
  12393. process.version = ''; // empty string to avoid regexp issues
  12394. process.versions = {};
  12395. function noop() {}
  12396. process.on = noop;
  12397. process.addListener = noop;
  12398. process.once = noop;
  12399. process.off = noop;
  12400. process.removeListener = noop;
  12401. process.removeAllListeners = noop;
  12402. process.emit = noop;
  12403. process.binding = function (name) {
  12404. throw new Error('process.binding is not supported');
  12405. };
  12406. process.cwd = function () { return '/' };
  12407. process.chdir = function (dir) {
  12408. throw new Error('process.chdir is not supported');
  12409. };
  12410. process.umask = function() { return 0; };
  12411. },{}],45:[function(require,module,exports){
  12412. (function (process,global){
  12413. /*!
  12414. * @overview es6-promise - a tiny implementation of Promises/A+.
  12415. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  12416. * @license Licensed under MIT license
  12417. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  12418. * @version 3.0.2
  12419. */
  12420. (function() {
  12421. "use strict";
  12422. function lib$es6$promise$utils$$objectOrFunction(x) {
  12423. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  12424. }
  12425. function lib$es6$promise$utils$$isFunction(x) {
  12426. return typeof x === 'function';
  12427. }
  12428. function lib$es6$promise$utils$$isMaybeThenable(x) {
  12429. return typeof x === 'object' && x !== null;
  12430. }
  12431. var lib$es6$promise$utils$$_isArray;
  12432. if (!Array.isArray) {
  12433. lib$es6$promise$utils$$_isArray = function (x) {
  12434. return Object.prototype.toString.call(x) === '[object Array]';
  12435. };
  12436. } else {
  12437. lib$es6$promise$utils$$_isArray = Array.isArray;
  12438. }
  12439. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  12440. var lib$es6$promise$asap$$len = 0;
  12441. var lib$es6$promise$asap$$toString = {}.toString;
  12442. var lib$es6$promise$asap$$vertxNext;
  12443. var lib$es6$promise$asap$$customSchedulerFn;
  12444. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  12445. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  12446. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  12447. lib$es6$promise$asap$$len += 2;
  12448. if (lib$es6$promise$asap$$len === 2) {
  12449. // If len is 2, that means that we need to schedule an async flush.
  12450. // If additional callbacks are queued before the queue is flushed, they
  12451. // will be processed by this flush that we are scheduling.
  12452. if (lib$es6$promise$asap$$customSchedulerFn) {
  12453. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  12454. } else {
  12455. lib$es6$promise$asap$$scheduleFlush();
  12456. }
  12457. }
  12458. }
  12459. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  12460. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  12461. }
  12462. function lib$es6$promise$asap$$setAsap(asapFn) {
  12463. lib$es6$promise$asap$$asap = asapFn;
  12464. }
  12465. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  12466. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  12467. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  12468. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  12469. // test for web worker but not in IE10
  12470. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  12471. typeof importScripts !== 'undefined' &&
  12472. typeof MessageChannel !== 'undefined';
  12473. // node
  12474. function lib$es6$promise$asap$$useNextTick() {
  12475. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  12476. // see https://github.com/cujojs/when/issues/410 for details
  12477. return function() {
  12478. process.nextTick(lib$es6$promise$asap$$flush);
  12479. };
  12480. }
  12481. // vertx
  12482. function lib$es6$promise$asap$$useVertxTimer() {
  12483. return function() {
  12484. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  12485. };
  12486. }
  12487. function lib$es6$promise$asap$$useMutationObserver() {
  12488. var iterations = 0;
  12489. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  12490. var node = document.createTextNode('');
  12491. observer.observe(node, { characterData: true });
  12492. return function() {
  12493. node.data = (iterations = ++iterations % 2);
  12494. };
  12495. }
  12496. // web worker
  12497. function lib$es6$promise$asap$$useMessageChannel() {
  12498. var channel = new MessageChannel();
  12499. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  12500. return function () {
  12501. channel.port2.postMessage(0);
  12502. };
  12503. }
  12504. function lib$es6$promise$asap$$useSetTimeout() {
  12505. return function() {
  12506. setTimeout(lib$es6$promise$asap$$flush, 1);
  12507. };
  12508. }
  12509. var lib$es6$promise$asap$$queue = new Array(1000);
  12510. function lib$es6$promise$asap$$flush() {
  12511. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  12512. var callback = lib$es6$promise$asap$$queue[i];
  12513. var arg = lib$es6$promise$asap$$queue[i+1];
  12514. callback(arg);
  12515. lib$es6$promise$asap$$queue[i] = undefined;
  12516. lib$es6$promise$asap$$queue[i+1] = undefined;
  12517. }
  12518. lib$es6$promise$asap$$len = 0;
  12519. }
  12520. function lib$es6$promise$asap$$attemptVertx() {
  12521. try {
  12522. var r = require;
  12523. var vertx = r('vertx');
  12524. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  12525. return lib$es6$promise$asap$$useVertxTimer();
  12526. } catch(e) {
  12527. return lib$es6$promise$asap$$useSetTimeout();
  12528. }
  12529. }
  12530. var lib$es6$promise$asap$$scheduleFlush;
  12531. // Decide what async method to use to triggering processing of queued callbacks:
  12532. if (lib$es6$promise$asap$$isNode) {
  12533. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  12534. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  12535. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  12536. } else if (lib$es6$promise$asap$$isWorker) {
  12537. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  12538. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  12539. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  12540. } else {
  12541. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  12542. }
  12543. function lib$es6$promise$$internal$$noop() {}
  12544. var lib$es6$promise$$internal$$PENDING = void 0;
  12545. var lib$es6$promise$$internal$$FULFILLED = 1;
  12546. var lib$es6$promise$$internal$$REJECTED = 2;
  12547. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  12548. function lib$es6$promise$$internal$$selfFulfillment() {
  12549. return new TypeError("You cannot resolve a promise with itself");
  12550. }
  12551. function lib$es6$promise$$internal$$cannotReturnOwn() {
  12552. return new TypeError('A promises callback cannot return that same promise.');
  12553. }
  12554. function lib$es6$promise$$internal$$getThen(promise) {
  12555. try {
  12556. return promise.then;
  12557. } catch(error) {
  12558. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  12559. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  12560. }
  12561. }
  12562. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  12563. try {
  12564. then.call(value, fulfillmentHandler, rejectionHandler);
  12565. } catch(e) {
  12566. return e;
  12567. }
  12568. }
  12569. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  12570. lib$es6$promise$asap$$asap(function(promise) {
  12571. var sealed = false;
  12572. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  12573. if (sealed) { return; }
  12574. sealed = true;
  12575. if (thenable !== value) {
  12576. lib$es6$promise$$internal$$resolve(promise, value);
  12577. } else {
  12578. lib$es6$promise$$internal$$fulfill(promise, value);
  12579. }
  12580. }, function(reason) {
  12581. if (sealed) { return; }
  12582. sealed = true;
  12583. lib$es6$promise$$internal$$reject(promise, reason);
  12584. }, 'Settle: ' + (promise._label || ' unknown promise'));
  12585. if (!sealed && error) {
  12586. sealed = true;
  12587. lib$es6$promise$$internal$$reject(promise, error);
  12588. }
  12589. }, promise);
  12590. }
  12591. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  12592. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  12593. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  12594. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  12595. lib$es6$promise$$internal$$reject(promise, thenable._result);
  12596. } else {
  12597. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  12598. lib$es6$promise$$internal$$resolve(promise, value);
  12599. }, function(reason) {
  12600. lib$es6$promise$$internal$$reject(promise, reason);
  12601. });
  12602. }
  12603. }
  12604. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  12605. if (maybeThenable.constructor === promise.constructor) {
  12606. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  12607. } else {
  12608. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  12609. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  12610. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  12611. } else if (then === undefined) {
  12612. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  12613. } else if (lib$es6$promise$utils$$isFunction(then)) {
  12614. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  12615. } else {
  12616. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  12617. }
  12618. }
  12619. }
  12620. function lib$es6$promise$$internal$$resolve(promise, value) {
  12621. if (promise === value) {
  12622. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  12623. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  12624. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  12625. } else {
  12626. lib$es6$promise$$internal$$fulfill(promise, value);
  12627. }
  12628. }
  12629. function lib$es6$promise$$internal$$publishRejection(promise) {
  12630. if (promise._onerror) {
  12631. promise._onerror(promise._result);
  12632. }
  12633. lib$es6$promise$$internal$$publish(promise);
  12634. }
  12635. function lib$es6$promise$$internal$$fulfill(promise, value) {
  12636. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  12637. promise._result = value;
  12638. promise._state = lib$es6$promise$$internal$$FULFILLED;
  12639. if (promise._subscribers.length !== 0) {
  12640. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  12641. }
  12642. }
  12643. function lib$es6$promise$$internal$$reject(promise, reason) {
  12644. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  12645. promise._state = lib$es6$promise$$internal$$REJECTED;
  12646. promise._result = reason;
  12647. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  12648. }
  12649. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  12650. var subscribers = parent._subscribers;
  12651. var length = subscribers.length;
  12652. parent._onerror = null;
  12653. subscribers[length] = child;
  12654. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  12655. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  12656. if (length === 0 && parent._state) {
  12657. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  12658. }
  12659. }
  12660. function lib$es6$promise$$internal$$publish(promise) {
  12661. var subscribers = promise._subscribers;
  12662. var settled = promise._state;
  12663. if (subscribers.length === 0) { return; }
  12664. var child, callback, detail = promise._result;
  12665. for (var i = 0; i < subscribers.length; i += 3) {
  12666. child = subscribers[i];
  12667. callback = subscribers[i + settled];
  12668. if (child) {
  12669. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  12670. } else {
  12671. callback(detail);
  12672. }
  12673. }
  12674. promise._subscribers.length = 0;
  12675. }
  12676. function lib$es6$promise$$internal$$ErrorObject() {
  12677. this.error = null;
  12678. }
  12679. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  12680. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  12681. try {
  12682. return callback(detail);
  12683. } catch(e) {
  12684. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  12685. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  12686. }
  12687. }
  12688. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  12689. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  12690. value, error, succeeded, failed;
  12691. if (hasCallback) {
  12692. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  12693. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  12694. failed = true;
  12695. error = value.error;
  12696. value = null;
  12697. } else {
  12698. succeeded = true;
  12699. }
  12700. if (promise === value) {
  12701. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  12702. return;
  12703. }
  12704. } else {
  12705. value = detail;
  12706. succeeded = true;
  12707. }
  12708. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  12709. // noop
  12710. } else if (hasCallback && succeeded) {
  12711. lib$es6$promise$$internal$$resolve(promise, value);
  12712. } else if (failed) {
  12713. lib$es6$promise$$internal$$reject(promise, error);
  12714. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  12715. lib$es6$promise$$internal$$fulfill(promise, value);
  12716. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  12717. lib$es6$promise$$internal$$reject(promise, value);
  12718. }
  12719. }
  12720. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  12721. try {
  12722. resolver(function resolvePromise(value){
  12723. lib$es6$promise$$internal$$resolve(promise, value);
  12724. }, function rejectPromise(reason) {
  12725. lib$es6$promise$$internal$$reject(promise, reason);
  12726. });
  12727. } catch(e) {
  12728. lib$es6$promise$$internal$$reject(promise, e);
  12729. }
  12730. }
  12731. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  12732. var enumerator = this;
  12733. enumerator._instanceConstructor = Constructor;
  12734. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  12735. if (enumerator._validateInput(input)) {
  12736. enumerator._input = input;
  12737. enumerator.length = input.length;
  12738. enumerator._remaining = input.length;
  12739. enumerator._init();
  12740. if (enumerator.length === 0) {
  12741. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  12742. } else {
  12743. enumerator.length = enumerator.length || 0;
  12744. enumerator._enumerate();
  12745. if (enumerator._remaining === 0) {
  12746. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  12747. }
  12748. }
  12749. } else {
  12750. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  12751. }
  12752. }
  12753. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  12754. return lib$es6$promise$utils$$isArray(input);
  12755. };
  12756. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  12757. return new Error('Array Methods must be provided an Array');
  12758. };
  12759. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  12760. this._result = new Array(this.length);
  12761. };
  12762. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  12763. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  12764. var enumerator = this;
  12765. var length = enumerator.length;
  12766. var promise = enumerator.promise;
  12767. var input = enumerator._input;
  12768. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  12769. enumerator._eachEntry(input[i], i);
  12770. }
  12771. };
  12772. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  12773. var enumerator = this;
  12774. var c = enumerator._instanceConstructor;
  12775. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  12776. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  12777. entry._onerror = null;
  12778. enumerator._settledAt(entry._state, i, entry._result);
  12779. } else {
  12780. enumerator._willSettleAt(c.resolve(entry), i);
  12781. }
  12782. } else {
  12783. enumerator._remaining--;
  12784. enumerator._result[i] = entry;
  12785. }
  12786. };
  12787. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  12788. var enumerator = this;
  12789. var promise = enumerator.promise;
  12790. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  12791. enumerator._remaining--;
  12792. if (state === lib$es6$promise$$internal$$REJECTED) {
  12793. lib$es6$promise$$internal$$reject(promise, value);
  12794. } else {
  12795. enumerator._result[i] = value;
  12796. }
  12797. }
  12798. if (enumerator._remaining === 0) {
  12799. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  12800. }
  12801. };
  12802. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  12803. var enumerator = this;
  12804. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  12805. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  12806. }, function(reason) {
  12807. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  12808. });
  12809. };
  12810. function lib$es6$promise$promise$all$$all(entries) {
  12811. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  12812. }
  12813. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  12814. function lib$es6$promise$promise$race$$race(entries) {
  12815. /*jshint validthis:true */
  12816. var Constructor = this;
  12817. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12818. if (!lib$es6$promise$utils$$isArray(entries)) {
  12819. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  12820. return promise;
  12821. }
  12822. var length = entries.length;
  12823. function onFulfillment(value) {
  12824. lib$es6$promise$$internal$$resolve(promise, value);
  12825. }
  12826. function onRejection(reason) {
  12827. lib$es6$promise$$internal$$reject(promise, reason);
  12828. }
  12829. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  12830. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  12831. }
  12832. return promise;
  12833. }
  12834. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  12835. function lib$es6$promise$promise$resolve$$resolve(object) {
  12836. /*jshint validthis:true */
  12837. var Constructor = this;
  12838. if (object && typeof object === 'object' && object.constructor === Constructor) {
  12839. return object;
  12840. }
  12841. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12842. lib$es6$promise$$internal$$resolve(promise, object);
  12843. return promise;
  12844. }
  12845. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  12846. function lib$es6$promise$promise$reject$$reject(reason) {
  12847. /*jshint validthis:true */
  12848. var Constructor = this;
  12849. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12850. lib$es6$promise$$internal$$reject(promise, reason);
  12851. return promise;
  12852. }
  12853. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  12854. var lib$es6$promise$promise$$counter = 0;
  12855. function lib$es6$promise$promise$$needsResolver() {
  12856. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  12857. }
  12858. function lib$es6$promise$promise$$needsNew() {
  12859. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  12860. }
  12861. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  12862. /**
  12863. Promise objects represent the eventual result of an asynchronous operation. The
  12864. primary way of interacting with a promise is through its `then` method, which
  12865. registers callbacks to receive either a promise's eventual value or the reason
  12866. why the promise cannot be fulfilled.
  12867. Terminology
  12868. -----------
  12869. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  12870. - `thenable` is an object or function that defines a `then` method.
  12871. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  12872. - `exception` is a value that is thrown using the throw statement.
  12873. - `reason` is a value that indicates why a promise was rejected.
  12874. - `settled` the final resting state of a promise, fulfilled or rejected.
  12875. A promise can be in one of three states: pending, fulfilled, or rejected.
  12876. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  12877. state. Promises that are rejected have a rejection reason and are in the
  12878. rejected state. A fulfillment value is never a thenable.
  12879. Promises can also be said to *resolve* a value. If this value is also a
  12880. promise, then the original promise's settled state will match the value's
  12881. settled state. So a promise that *resolves* a promise that rejects will
  12882. itself reject, and a promise that *resolves* a promise that fulfills will
  12883. itself fulfill.
  12884. Basic Usage:
  12885. ------------
  12886. ```js
  12887. var promise = new Promise(function(resolve, reject) {
  12888. // on success
  12889. resolve(value);
  12890. // on failure
  12891. reject(reason);
  12892. });
  12893. promise.then(function(value) {
  12894. // on fulfillment
  12895. }, function(reason) {
  12896. // on rejection
  12897. });
  12898. ```
  12899. Advanced Usage:
  12900. ---------------
  12901. Promises shine when abstracting away asynchronous interactions such as
  12902. `XMLHttpRequest`s.
  12903. ```js
  12904. function getJSON(url) {
  12905. return new Promise(function(resolve, reject){
  12906. var xhr = new XMLHttpRequest();
  12907. xhr.open('GET', url);
  12908. xhr.onreadystatechange = handler;
  12909. xhr.responseType = 'json';
  12910. xhr.setRequestHeader('Accept', 'application/json');
  12911. xhr.send();
  12912. function handler() {
  12913. if (this.readyState === this.DONE) {
  12914. if (this.status === 200) {
  12915. resolve(this.response);
  12916. } else {
  12917. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  12918. }
  12919. }
  12920. };
  12921. });
  12922. }
  12923. getJSON('/posts.json').then(function(json) {
  12924. // on fulfillment
  12925. }, function(reason) {
  12926. // on rejection
  12927. });
  12928. ```
  12929. Unlike callbacks, promises are great composable primitives.
  12930. ```js
  12931. Promise.all([
  12932. getJSON('/posts'),
  12933. getJSON('/comments')
  12934. ]).then(function(values){
  12935. values[0] // => postsJSON
  12936. values[1] // => commentsJSON
  12937. return values;
  12938. });
  12939. ```
  12940. @class Promise
  12941. @param {function} resolver
  12942. Useful for tooling.
  12943. @constructor
  12944. */
  12945. function lib$es6$promise$promise$$Promise(resolver) {
  12946. this._id = lib$es6$promise$promise$$counter++;
  12947. this._state = undefined;
  12948. this._result = undefined;
  12949. this._subscribers = [];
  12950. if (lib$es6$promise$$internal$$noop !== resolver) {
  12951. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  12952. lib$es6$promise$promise$$needsResolver();
  12953. }
  12954. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  12955. lib$es6$promise$promise$$needsNew();
  12956. }
  12957. lib$es6$promise$$internal$$initializePromise(this, resolver);
  12958. }
  12959. }
  12960. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  12961. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  12962. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  12963. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  12964. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  12965. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  12966. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  12967. lib$es6$promise$promise$$Promise.prototype = {
  12968. constructor: lib$es6$promise$promise$$Promise,
  12969. /**
  12970. The primary way of interacting with a promise is through its `then` method,
  12971. which registers callbacks to receive either a promise's eventual value or the
  12972. reason why the promise cannot be fulfilled.
  12973. ```js
  12974. findUser().then(function(user){
  12975. // user is available
  12976. }, function(reason){
  12977. // user is unavailable, and you are given the reason why
  12978. });
  12979. ```
  12980. Chaining
  12981. --------
  12982. The return value of `then` is itself a promise. This second, 'downstream'
  12983. promise is resolved with the return value of the first promise's fulfillment
  12984. or rejection handler, or rejected if the handler throws an exception.
  12985. ```js
  12986. findUser().then(function (user) {
  12987. return user.name;
  12988. }, function (reason) {
  12989. return 'default name';
  12990. }).then(function (userName) {
  12991. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  12992. // will be `'default name'`
  12993. });
  12994. findUser().then(function (user) {
  12995. throw new Error('Found user, but still unhappy');
  12996. }, function (reason) {
  12997. throw new Error('`findUser` rejected and we're unhappy');
  12998. }).then(function (value) {
  12999. // never reached
  13000. }, function (reason) {
  13001. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  13002. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  13003. });
  13004. ```
  13005. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  13006. ```js
  13007. findUser().then(function (user) {
  13008. throw new PedagogicalException('Upstream error');
  13009. }).then(function (value) {
  13010. // never reached
  13011. }).then(function (value) {
  13012. // never reached
  13013. }, function (reason) {
  13014. // The `PedgagocialException` is propagated all the way down to here
  13015. });
  13016. ```
  13017. Assimilation
  13018. ------------
  13019. Sometimes the value you want to propagate to a downstream promise can only be
  13020. retrieved asynchronously. This can be achieved by returning a promise in the
  13021. fulfillment or rejection handler. The downstream promise will then be pending
  13022. until the returned promise is settled. This is called *assimilation*.
  13023. ```js
  13024. findUser().then(function (user) {
  13025. return findCommentsByAuthor(user);
  13026. }).then(function (comments) {
  13027. // The user's comments are now available
  13028. });
  13029. ```
  13030. If the assimliated promise rejects, then the downstream promise will also reject.
  13031. ```js
  13032. findUser().then(function (user) {
  13033. return findCommentsByAuthor(user);
  13034. }).then(function (comments) {
  13035. // If `findCommentsByAuthor` fulfills, we'll have the value here
  13036. }, function (reason) {
  13037. // If `findCommentsByAuthor` rejects, we'll have the reason here
  13038. });
  13039. ```
  13040. Simple Example
  13041. --------------
  13042. Synchronous Example
  13043. ```javascript
  13044. var result;
  13045. try {
  13046. result = findResult();
  13047. // success
  13048. } catch(reason) {
  13049. // failure
  13050. }
  13051. ```
  13052. Errback Example
  13053. ```js
  13054. findResult(function(result, err){
  13055. if (err) {
  13056. // failure
  13057. } else {
  13058. // success
  13059. }
  13060. });
  13061. ```
  13062. Promise Example;
  13063. ```javascript
  13064. findResult().then(function(result){
  13065. // success
  13066. }, function(reason){
  13067. // failure
  13068. });
  13069. ```
  13070. Advanced Example
  13071. --------------
  13072. Synchronous Example
  13073. ```javascript
  13074. var author, books;
  13075. try {
  13076. author = findAuthor();
  13077. books = findBooksByAuthor(author);
  13078. // success
  13079. } catch(reason) {
  13080. // failure
  13081. }
  13082. ```
  13083. Errback Example
  13084. ```js
  13085. function foundBooks(books) {
  13086. }
  13087. function failure(reason) {
  13088. }
  13089. findAuthor(function(author, err){
  13090. if (err) {
  13091. failure(err);
  13092. // failure
  13093. } else {
  13094. try {
  13095. findBoooksByAuthor(author, function(books, err) {
  13096. if (err) {
  13097. failure(err);
  13098. } else {
  13099. try {
  13100. foundBooks(books);
  13101. } catch(reason) {
  13102. failure(reason);
  13103. }
  13104. }
  13105. });
  13106. } catch(error) {
  13107. failure(err);
  13108. }
  13109. // success
  13110. }
  13111. });
  13112. ```
  13113. Promise Example;
  13114. ```javascript
  13115. findAuthor().
  13116. then(findBooksByAuthor).
  13117. then(function(books){
  13118. // found books
  13119. }).catch(function(reason){
  13120. // something went wrong
  13121. });
  13122. ```
  13123. @method then
  13124. @param {Function} onFulfilled
  13125. @param {Function} onRejected
  13126. Useful for tooling.
  13127. @return {Promise}
  13128. */
  13129. then: function(onFulfillment, onRejection) {
  13130. var parent = this;
  13131. var state = parent._state;
  13132. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  13133. return this;
  13134. }
  13135. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  13136. var result = parent._result;
  13137. if (state) {
  13138. var callback = arguments[state - 1];
  13139. lib$es6$promise$asap$$asap(function(){
  13140. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  13141. });
  13142. } else {
  13143. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  13144. }
  13145. return child;
  13146. },
  13147. /**
  13148. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  13149. as the catch block of a try/catch statement.
  13150. ```js
  13151. function findAuthor(){
  13152. throw new Error('couldn't find that author');
  13153. }
  13154. // synchronous
  13155. try {
  13156. findAuthor();
  13157. } catch(reason) {
  13158. // something went wrong
  13159. }
  13160. // async with promises
  13161. findAuthor().catch(function(reason){
  13162. // something went wrong
  13163. });
  13164. ```
  13165. @method catch
  13166. @param {Function} onRejection
  13167. Useful for tooling.
  13168. @return {Promise}
  13169. */
  13170. 'catch': function(onRejection) {
  13171. return this.then(null, onRejection);
  13172. }
  13173. };
  13174. function lib$es6$promise$polyfill$$polyfill() {
  13175. var local;
  13176. if (typeof global !== 'undefined') {
  13177. local = global;
  13178. } else if (typeof self !== 'undefined') {
  13179. local = self;
  13180. } else {
  13181. try {
  13182. local = Function('return this')();
  13183. } catch (e) {
  13184. throw new Error('polyfill failed because global object is unavailable in this environment');
  13185. }
  13186. }
  13187. var P = local.Promise;
  13188. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  13189. return;
  13190. }
  13191. local.Promise = lib$es6$promise$promise$$default;
  13192. }
  13193. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  13194. var lib$es6$promise$umd$$ES6Promise = {
  13195. 'Promise': lib$es6$promise$promise$$default,
  13196. 'polyfill': lib$es6$promise$polyfill$$default
  13197. };
  13198. /* global define:true module:true window: true */
  13199. if (typeof define === 'function' && define['amd']) {
  13200. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  13201. } else if (typeof module !== 'undefined' && module['exports']) {
  13202. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  13203. } else if (typeof this !== 'undefined') {
  13204. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  13205. }
  13206. lib$es6$promise$polyfill$$default();
  13207. }).call(this);
  13208. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  13209. },{"_process":44}],46:[function(require,module,exports){
  13210. /* Copyright @ 2015 Atlassian Pty Ltd
  13211. *
  13212. * Licensed under the Apache License, Version 2.0 (the "License");
  13213. * you may not use this file except in compliance with the License.
  13214. * You may obtain a copy of the License at
  13215. *
  13216. * http://www.apache.org/licenses/LICENSE-2.0
  13217. *
  13218. * Unless required by applicable law or agreed to in writing, software
  13219. * distributed under the License is distributed on an "AS IS" BASIS,
  13220. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13221. * See the License for the specific language governing permissions and
  13222. * limitations under the License.
  13223. */
  13224. /**
  13225. * Ordered log levels.
  13226. */
  13227. var levels = {
  13228. "trace": 0,
  13229. "debug": 1,
  13230. "info": 2,
  13231. "log": 3,
  13232. "warn": 4,
  13233. "error": 5
  13234. };
  13235. /**
  13236. * Parses Error's object stack trace and extracts information about the last
  13237. * caller before the log method was called.
  13238. * @returns JS object with info about the caller - method name, file location,
  13239. * line and column.
  13240. */
  13241. function getCallerInfo() {
  13242. var callerInfo = {
  13243. methodName: "",
  13244. fileLocation: "",
  13245. line: null,
  13246. column: null
  13247. };
  13248. //gets the part of the stack without the logger wrappers
  13249. var error = new Error();
  13250. var stack = error.stack? error.stack.split("\n") : [];
  13251. if(!stack || stack.length < 1) {
  13252. return callerInfo;
  13253. }
  13254. var m = null;
  13255. if(stack[3]) {
  13256. m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);
  13257. }
  13258. if(!m || m.length <= 4) {
  13259. //Firefox && Safari
  13260. if(stack[2].indexOf("log@") === 0){
  13261. //Safari
  13262. callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));
  13263. } else {
  13264. //Firefox
  13265. callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));
  13266. }
  13267. return callerInfo;
  13268. }
  13269. callerInfo.methodName = m[1];
  13270. callerInfo.fileLocation = m[2];
  13271. callerInfo.line = m[3];
  13272. callerInfo.column = m[4];
  13273. return callerInfo;
  13274. }
  13275. /**
  13276. * Logs messages using the transports and level from the logger.
  13277. * @param logger a logger instance.
  13278. * @param level the log level of the message. See the levels variable.
  13279. * @param arguments array with arguments that will be logged.
  13280. */
  13281. function log() {
  13282. var logger = arguments[0], level = arguments[1],
  13283. args = Array.prototype.slice.call(arguments, 2);
  13284. if(levels[level] <= logger.level) {
  13285. return;
  13286. }
  13287. var callerInfo = getCallerInfo();
  13288. for(var i = 0; i < logger.transports.length; i++) {
  13289. var t = logger.transports[i];
  13290. var l = t[level];
  13291. if(l && typeof(l) === "function") {
  13292. l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")
  13293. .apply(t, args);
  13294. }
  13295. }
  13296. }
  13297. /**
  13298. *
  13299. * Constructs new logger object.
  13300. * @param level the logging level for the new logger
  13301. * @param id optional identifier for the logger instance.
  13302. * @param transports optional list of handlers(objects) for the logs.
  13303. * The handlers must support - log, warn, error, debug, info, trace.
  13304. * @param format optional (NOT implemented) string.
  13305. */
  13306. function Logger(level, id, transports, format) {
  13307. this.id = id;
  13308. this.format = format;
  13309. if(!this.transports) {
  13310. this.transports = [];
  13311. this.transports.push(Logger.consoleTransport);
  13312. }
  13313. this.level = levels[level];
  13314. var methods = Object.keys(levels);
  13315. for(var i = 0; i < methods.length; i++){
  13316. this[methods[i]] =
  13317. log.bind(null, this, methods[i]);
  13318. }
  13319. }
  13320. /**
  13321. * Sets the log level for the logger.
  13322. * @param level the new log level.
  13323. */
  13324. Logger.prototype.setLevel = function (level) {
  13325. this.level = levels[level];
  13326. };
  13327. module.exports = Logger;
  13328. /**
  13329. * The default transport - console
  13330. */
  13331. Logger.consoleTransport = console;
  13332. /**
  13333. * Enum for the supported log levels.
  13334. */
  13335. Logger.levels = {
  13336. TRACE: "trace",
  13337. DEBUG: "debug",
  13338. INFO: "info",
  13339. LOG: "log",
  13340. WARN: "warn",
  13341. ERROR: "error"
  13342. };
  13343. },{}],47:[function(require,module,exports){
  13344. /* Copyright @ 2015 Atlassian Pty Ltd
  13345. *
  13346. * Licensed under the Apache License, Version 2.0 (the "License");
  13347. * you may not use this file except in compliance with the License.
  13348. * You may obtain a copy of the License at
  13349. *
  13350. * http://www.apache.org/licenses/LICENSE-2.0
  13351. *
  13352. * Unless required by applicable law or agreed to in writing, software
  13353. * distributed under the License is distributed on an "AS IS" BASIS,
  13354. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13355. * See the License for the specific language governing permissions and
  13356. * limitations under the License.
  13357. */
  13358. var Logger = require("./Logger");
  13359. /**
  13360. * Map with the created loggers with ID.
  13361. */
  13362. var idLoggers = {};
  13363. /**
  13364. * Array with the loggers without id.
  13365. */
  13366. var loggers = [];
  13367. /**
  13368. * Log level for the lbrary.
  13369. */
  13370. var curLevel = Logger.levels.TRACE;
  13371. module.exports = {
  13372. /**
  13373. * Creates new logger.
  13374. * @arguments the same as Logger constructor
  13375. */
  13376. getLogger: function(id, transports, format) {
  13377. var logger = new Logger(curLevel, id, transports, format);
  13378. if(id) {
  13379. idLoggers[id] = idLoggers[id] || [];
  13380. idLoggers[id].push(logger);
  13381. } else {
  13382. loggers.push(logger);
  13383. }
  13384. return logger;
  13385. },
  13386. /**
  13387. * Changes the log level for the existing loggers by id.
  13388. * @param level the new log level.
  13389. * @param id if specified the level will be changed only for loggers with the
  13390. * same id. Otherwise the operation will affect all loggers that don't
  13391. * have id.
  13392. */
  13393. setLogLevelById: function(level, id) {
  13394. var l = id? (idLoggers[id] || []) : loggers;
  13395. for(var i = 0; i < l.length; i++) {
  13396. l[i].setLevel(level);
  13397. }
  13398. },
  13399. /**
  13400. * Changes the log level for all existing loggers.
  13401. * @param level the new log level.
  13402. */
  13403. setLogLevel: function (level) {
  13404. curLevel = level;
  13405. var i = 0;
  13406. for(; i < loggers.length; i++) {
  13407. loggers[i].setLevel(level);
  13408. }
  13409. for(var id in idLoggers) {
  13410. var l = idLoggers[id] || [];
  13411. for(i = 0; i < l.length; i++) {
  13412. l[i].setLevel(level);
  13413. }
  13414. }
  13415. },
  13416. /**
  13417. * The supported log levels.
  13418. */
  13419. levels: Logger.levels
  13420. };
  13421. },{"./Logger":46}],48:[function(require,module,exports){
  13422. // Top level file is just a mixin of submodules & constants
  13423. 'use strict';
  13424. var assign = require('./lib/utils/common').assign;
  13425. var deflate = require('./lib/deflate');
  13426. var inflate = require('./lib/inflate');
  13427. var constants = require('./lib/zlib/constants');
  13428. var pako = {};
  13429. assign(pako, deflate, inflate, constants);
  13430. module.exports = pako;
  13431. },{"./lib/deflate":49,"./lib/inflate":50,"./lib/utils/common":51,"./lib/zlib/constants":54}],49:[function(require,module,exports){
  13432. 'use strict';
  13433. var zlib_deflate = require('./zlib/deflate.js');
  13434. var utils = require('./utils/common');
  13435. var strings = require('./utils/strings');
  13436. var msg = require('./zlib/messages');
  13437. var zstream = require('./zlib/zstream');
  13438. var toString = Object.prototype.toString;
  13439. /* Public constants ==========================================================*/
  13440. /* ===========================================================================*/
  13441. var Z_NO_FLUSH = 0;
  13442. var Z_FINISH = 4;
  13443. var Z_OK = 0;
  13444. var Z_STREAM_END = 1;
  13445. var Z_SYNC_FLUSH = 2;
  13446. var Z_DEFAULT_COMPRESSION = -1;
  13447. var Z_DEFAULT_STRATEGY = 0;
  13448. var Z_DEFLATED = 8;
  13449. /* ===========================================================================*/
  13450. /**
  13451. * class Deflate
  13452. *
  13453. * Generic JS-style wrapper for zlib calls. If you don't need
  13454. * streaming behaviour - use more simple functions: [[deflate]],
  13455. * [[deflateRaw]] and [[gzip]].
  13456. **/
  13457. /* internal
  13458. * Deflate.chunks -> Array
  13459. *
  13460. * Chunks of output data, if [[Deflate#onData]] not overriden.
  13461. **/
  13462. /**
  13463. * Deflate.result -> Uint8Array|Array
  13464. *
  13465. * Compressed result, generated by default [[Deflate#onData]]
  13466. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  13467. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  13468. * push a chunk with explicit flush (call [[Deflate#push]] with
  13469. * `Z_SYNC_FLUSH` param).
  13470. **/
  13471. /**
  13472. * Deflate.err -> Number
  13473. *
  13474. * Error code after deflate finished. 0 (Z_OK) on success.
  13475. * You will not need it in real life, because deflate errors
  13476. * are possible only on wrong options or bad `onData` / `onEnd`
  13477. * custom handlers.
  13478. **/
  13479. /**
  13480. * Deflate.msg -> String
  13481. *
  13482. * Error message, if [[Deflate.err]] != 0
  13483. **/
  13484. /**
  13485. * new Deflate(options)
  13486. * - options (Object): zlib deflate options.
  13487. *
  13488. * Creates new deflator instance with specified params. Throws exception
  13489. * on bad params. Supported options:
  13490. *
  13491. * - `level`
  13492. * - `windowBits`
  13493. * - `memLevel`
  13494. * - `strategy`
  13495. *
  13496. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13497. * for more information on these.
  13498. *
  13499. * Additional options, for internal needs:
  13500. *
  13501. * - `chunkSize` - size of generated data chunks (16K by default)
  13502. * - `raw` (Boolean) - do raw deflate
  13503. * - `gzip` (Boolean) - create gzip wrapper
  13504. * - `to` (String) - if equal to 'string', then result will be "binary string"
  13505. * (each char code [0..255])
  13506. * - `header` (Object) - custom header for gzip
  13507. * - `text` (Boolean) - true if compressed data believed to be text
  13508. * - `time` (Number) - modification time, unix timestamp
  13509. * - `os` (Number) - operation system code
  13510. * - `extra` (Array) - array of bytes with extra data (max 65536)
  13511. * - `name` (String) - file name (binary string)
  13512. * - `comment` (String) - comment (binary string)
  13513. * - `hcrc` (Boolean) - true if header crc should be added
  13514. *
  13515. * ##### Example:
  13516. *
  13517. * ```javascript
  13518. * var pako = require('pako')
  13519. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  13520. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  13521. *
  13522. * var deflate = new pako.Deflate({ level: 3});
  13523. *
  13524. * deflate.push(chunk1, false);
  13525. * deflate.push(chunk2, true); // true -> last chunk
  13526. *
  13527. * if (deflate.err) { throw new Error(deflate.err); }
  13528. *
  13529. * console.log(deflate.result);
  13530. * ```
  13531. **/
  13532. var Deflate = function(options) {
  13533. this.options = utils.assign({
  13534. level: Z_DEFAULT_COMPRESSION,
  13535. method: Z_DEFLATED,
  13536. chunkSize: 16384,
  13537. windowBits: 15,
  13538. memLevel: 8,
  13539. strategy: Z_DEFAULT_STRATEGY,
  13540. to: ''
  13541. }, options || {});
  13542. var opt = this.options;
  13543. if (opt.raw && (opt.windowBits > 0)) {
  13544. opt.windowBits = -opt.windowBits;
  13545. }
  13546. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  13547. opt.windowBits += 16;
  13548. }
  13549. this.err = 0; // error code, if happens (0 = Z_OK)
  13550. this.msg = ''; // error message
  13551. this.ended = false; // used to avoid multiple onEnd() calls
  13552. this.chunks = []; // chunks of compressed data
  13553. this.strm = new zstream();
  13554. this.strm.avail_out = 0;
  13555. var status = zlib_deflate.deflateInit2(
  13556. this.strm,
  13557. opt.level,
  13558. opt.method,
  13559. opt.windowBits,
  13560. opt.memLevel,
  13561. opt.strategy
  13562. );
  13563. if (status !== Z_OK) {
  13564. throw new Error(msg[status]);
  13565. }
  13566. if (opt.header) {
  13567. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  13568. }
  13569. };
  13570. /**
  13571. * Deflate#push(data[, mode]) -> Boolean
  13572. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  13573. * converted to utf8 byte sequence.
  13574. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  13575. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  13576. *
  13577. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  13578. * new compressed chunks. Returns `true` on success. The last data block must have
  13579. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  13580. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  13581. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  13582. *
  13583. * On fail call [[Deflate#onEnd]] with error code and return false.
  13584. *
  13585. * We strongly recommend to use `Uint8Array` on input for best speed (output
  13586. * array format is detected automatically). Also, don't skip last param and always
  13587. * use the same type in your code (boolean or number). That will improve JS speed.
  13588. *
  13589. * For regular `Array`-s make sure all elements are [0..255].
  13590. *
  13591. * ##### Example
  13592. *
  13593. * ```javascript
  13594. * push(chunk, false); // push one of data chunks
  13595. * ...
  13596. * push(chunk, true); // push last chunk
  13597. * ```
  13598. **/
  13599. Deflate.prototype.push = function(data, mode) {
  13600. var strm = this.strm;
  13601. var chunkSize = this.options.chunkSize;
  13602. var status, _mode;
  13603. if (this.ended) { return false; }
  13604. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  13605. // Convert data if needed
  13606. if (typeof data === 'string') {
  13607. // If we need to compress text, change encoding to utf8.
  13608. strm.input = strings.string2buf(data);
  13609. } else if (toString.call(data) === '[object ArrayBuffer]') {
  13610. strm.input = new Uint8Array(data);
  13611. } else {
  13612. strm.input = data;
  13613. }
  13614. strm.next_in = 0;
  13615. strm.avail_in = strm.input.length;
  13616. do {
  13617. if (strm.avail_out === 0) {
  13618. strm.output = new utils.Buf8(chunkSize);
  13619. strm.next_out = 0;
  13620. strm.avail_out = chunkSize;
  13621. }
  13622. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  13623. if (status !== Z_STREAM_END && status !== Z_OK) {
  13624. this.onEnd(status);
  13625. this.ended = true;
  13626. return false;
  13627. }
  13628. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  13629. if (this.options.to === 'string') {
  13630. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  13631. } else {
  13632. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  13633. }
  13634. }
  13635. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  13636. // Finalize on the last chunk.
  13637. if (_mode === Z_FINISH) {
  13638. status = zlib_deflate.deflateEnd(this.strm);
  13639. this.onEnd(status);
  13640. this.ended = true;
  13641. return status === Z_OK;
  13642. }
  13643. // callback interim results if Z_SYNC_FLUSH.
  13644. if (_mode === Z_SYNC_FLUSH) {
  13645. this.onEnd(Z_OK);
  13646. strm.avail_out = 0;
  13647. return true;
  13648. }
  13649. return true;
  13650. };
  13651. /**
  13652. * Deflate#onData(chunk) -> Void
  13653. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  13654. * on js engine support. When string output requested, each chunk
  13655. * will be string.
  13656. *
  13657. * By default, stores data blocks in `chunks[]` property and glue
  13658. * those in `onEnd`. Override this handler, if you need another behaviour.
  13659. **/
  13660. Deflate.prototype.onData = function(chunk) {
  13661. this.chunks.push(chunk);
  13662. };
  13663. /**
  13664. * Deflate#onEnd(status) -> Void
  13665. * - status (Number): deflate status. 0 (Z_OK) on success,
  13666. * other if not.
  13667. *
  13668. * Called once after you tell deflate that the input stream is
  13669. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  13670. * or if an error happened. By default - join collected chunks,
  13671. * free memory and fill `results` / `err` properties.
  13672. **/
  13673. Deflate.prototype.onEnd = function(status) {
  13674. // On success - join
  13675. if (status === Z_OK) {
  13676. if (this.options.to === 'string') {
  13677. this.result = this.chunks.join('');
  13678. } else {
  13679. this.result = utils.flattenChunks(this.chunks);
  13680. }
  13681. }
  13682. this.chunks = [];
  13683. this.err = status;
  13684. this.msg = this.strm.msg;
  13685. };
  13686. /**
  13687. * deflate(data[, options]) -> Uint8Array|Array|String
  13688. * - data (Uint8Array|Array|String): input data to compress.
  13689. * - options (Object): zlib deflate options.
  13690. *
  13691. * Compress `data` with deflate alrorythm and `options`.
  13692. *
  13693. * Supported options are:
  13694. *
  13695. * - level
  13696. * - windowBits
  13697. * - memLevel
  13698. * - strategy
  13699. *
  13700. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13701. * for more information on these.
  13702. *
  13703. * Sugar (options):
  13704. *
  13705. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  13706. * negative windowBits implicitly.
  13707. * - `to` (String) - if equal to 'string', then result will be "binary string"
  13708. * (each char code [0..255])
  13709. *
  13710. * ##### Example:
  13711. *
  13712. * ```javascript
  13713. * var pako = require('pako')
  13714. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  13715. *
  13716. * console.log(pako.deflate(data));
  13717. * ```
  13718. **/
  13719. function deflate(input, options) {
  13720. var deflator = new Deflate(options);
  13721. deflator.push(input, true);
  13722. // That will never happens, if you don't cheat with options :)
  13723. if (deflator.err) { throw deflator.msg; }
  13724. return deflator.result;
  13725. }
  13726. /**
  13727. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  13728. * - data (Uint8Array|Array|String): input data to compress.
  13729. * - options (Object): zlib deflate options.
  13730. *
  13731. * The same as [[deflate]], but creates raw data, without wrapper
  13732. * (header and adler32 crc).
  13733. **/
  13734. function deflateRaw(input, options) {
  13735. options = options || {};
  13736. options.raw = true;
  13737. return deflate(input, options);
  13738. }
  13739. /**
  13740. * gzip(data[, options]) -> Uint8Array|Array|String
  13741. * - data (Uint8Array|Array|String): input data to compress.
  13742. * - options (Object): zlib deflate options.
  13743. *
  13744. * The same as [[deflate]], but create gzip wrapper instead of
  13745. * deflate one.
  13746. **/
  13747. function gzip(input, options) {
  13748. options = options || {};
  13749. options.gzip = true;
  13750. return deflate(input, options);
  13751. }
  13752. exports.Deflate = Deflate;
  13753. exports.deflate = deflate;
  13754. exports.deflateRaw = deflateRaw;
  13755. exports.gzip = gzip;
  13756. },{"./utils/common":51,"./utils/strings":52,"./zlib/deflate.js":56,"./zlib/messages":61,"./zlib/zstream":63}],50:[function(require,module,exports){
  13757. 'use strict';
  13758. var zlib_inflate = require('./zlib/inflate.js');
  13759. var utils = require('./utils/common');
  13760. var strings = require('./utils/strings');
  13761. var c = require('./zlib/constants');
  13762. var msg = require('./zlib/messages');
  13763. var zstream = require('./zlib/zstream');
  13764. var gzheader = require('./zlib/gzheader');
  13765. var toString = Object.prototype.toString;
  13766. /**
  13767. * class Inflate
  13768. *
  13769. * Generic JS-style wrapper for zlib calls. If you don't need
  13770. * streaming behaviour - use more simple functions: [[inflate]]
  13771. * and [[inflateRaw]].
  13772. **/
  13773. /* internal
  13774. * inflate.chunks -> Array
  13775. *
  13776. * Chunks of output data, if [[Inflate#onData]] not overriden.
  13777. **/
  13778. /**
  13779. * Inflate.result -> Uint8Array|Array|String
  13780. *
  13781. * Uncompressed result, generated by default [[Inflate#onData]]
  13782. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  13783. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  13784. * push a chunk with explicit flush (call [[Inflate#push]] with
  13785. * `Z_SYNC_FLUSH` param).
  13786. **/
  13787. /**
  13788. * Inflate.err -> Number
  13789. *
  13790. * Error code after inflate finished. 0 (Z_OK) on success.
  13791. * Should be checked if broken data possible.
  13792. **/
  13793. /**
  13794. * Inflate.msg -> String
  13795. *
  13796. * Error message, if [[Inflate.err]] != 0
  13797. **/
  13798. /**
  13799. * new Inflate(options)
  13800. * - options (Object): zlib inflate options.
  13801. *
  13802. * Creates new inflator instance with specified params. Throws exception
  13803. * on bad params. Supported options:
  13804. *
  13805. * - `windowBits`
  13806. *
  13807. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13808. * for more information on these.
  13809. *
  13810. * Additional options, for internal needs:
  13811. *
  13812. * - `chunkSize` - size of generated data chunks (16K by default)
  13813. * - `raw` (Boolean) - do raw inflate
  13814. * - `to` (String) - if equal to 'string', then result will be converted
  13815. * from utf8 to utf16 (javascript) string. When string output requested,
  13816. * chunk length can differ from `chunkSize`, depending on content.
  13817. *
  13818. * By default, when no options set, autodetect deflate/gzip data format via
  13819. * wrapper header.
  13820. *
  13821. * ##### Example:
  13822. *
  13823. * ```javascript
  13824. * var pako = require('pako')
  13825. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  13826. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  13827. *
  13828. * var inflate = new pako.Inflate({ level: 3});
  13829. *
  13830. * inflate.push(chunk1, false);
  13831. * inflate.push(chunk2, true); // true -> last chunk
  13832. *
  13833. * if (inflate.err) { throw new Error(inflate.err); }
  13834. *
  13835. * console.log(inflate.result);
  13836. * ```
  13837. **/
  13838. var Inflate = function(options) {
  13839. this.options = utils.assign({
  13840. chunkSize: 16384,
  13841. windowBits: 0,
  13842. to: ''
  13843. }, options || {});
  13844. var opt = this.options;
  13845. // Force window size for `raw` data, if not set directly,
  13846. // because we have no header for autodetect.
  13847. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  13848. opt.windowBits = -opt.windowBits;
  13849. if (opt.windowBits === 0) { opt.windowBits = -15; }
  13850. }
  13851. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  13852. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  13853. !(options && options.windowBits)) {
  13854. opt.windowBits += 32;
  13855. }
  13856. // Gzip header has no info about windows size, we can do autodetect only
  13857. // for deflate. So, if window size not set, force it to max when gzip possible
  13858. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  13859. // bit 3 (16) -> gzipped data
  13860. // bit 4 (32) -> autodetect gzip/deflate
  13861. if ((opt.windowBits & 15) === 0) {
  13862. opt.windowBits |= 15;
  13863. }
  13864. }
  13865. this.err = 0; // error code, if happens (0 = Z_OK)
  13866. this.msg = ''; // error message
  13867. this.ended = false; // used to avoid multiple onEnd() calls
  13868. this.chunks = []; // chunks of compressed data
  13869. this.strm = new zstream();
  13870. this.strm.avail_out = 0;
  13871. var status = zlib_inflate.inflateInit2(
  13872. this.strm,
  13873. opt.windowBits
  13874. );
  13875. if (status !== c.Z_OK) {
  13876. throw new Error(msg[status]);
  13877. }
  13878. this.header = new gzheader();
  13879. zlib_inflate.inflateGetHeader(this.strm, this.header);
  13880. };
  13881. /**
  13882. * Inflate#push(data[, mode]) -> Boolean
  13883. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  13884. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  13885. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  13886. *
  13887. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  13888. * new output chunks. Returns `true` on success. The last data block must have
  13889. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  13890. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  13891. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  13892. *
  13893. * On fail call [[Inflate#onEnd]] with error code and return false.
  13894. *
  13895. * We strongly recommend to use `Uint8Array` on input for best speed (output
  13896. * format is detected automatically). Also, don't skip last param and always
  13897. * use the same type in your code (boolean or number). That will improve JS speed.
  13898. *
  13899. * For regular `Array`-s make sure all elements are [0..255].
  13900. *
  13901. * ##### Example
  13902. *
  13903. * ```javascript
  13904. * push(chunk, false); // push one of data chunks
  13905. * ...
  13906. * push(chunk, true); // push last chunk
  13907. * ```
  13908. **/
  13909. Inflate.prototype.push = function(data, mode) {
  13910. var strm = this.strm;
  13911. var chunkSize = this.options.chunkSize;
  13912. var status, _mode;
  13913. var next_out_utf8, tail, utf8str;
  13914. // Flag to properly process Z_BUF_ERROR on testing inflate call
  13915. // when we check that all output data was flushed.
  13916. var allowBufError = false;
  13917. if (this.ended) { return false; }
  13918. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  13919. // Convert data if needed
  13920. if (typeof data === 'string') {
  13921. // Only binary strings can be decompressed on practice
  13922. strm.input = strings.binstring2buf(data);
  13923. } else if (toString.call(data) === '[object ArrayBuffer]') {
  13924. strm.input = new Uint8Array(data);
  13925. } else {
  13926. strm.input = data;
  13927. }
  13928. strm.next_in = 0;
  13929. strm.avail_in = strm.input.length;
  13930. do {
  13931. if (strm.avail_out === 0) {
  13932. strm.output = new utils.Buf8(chunkSize);
  13933. strm.next_out = 0;
  13934. strm.avail_out = chunkSize;
  13935. }
  13936. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  13937. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  13938. status = c.Z_OK;
  13939. allowBufError = false;
  13940. }
  13941. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  13942. this.onEnd(status);
  13943. this.ended = true;
  13944. return false;
  13945. }
  13946. if (strm.next_out) {
  13947. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  13948. if (this.options.to === 'string') {
  13949. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  13950. tail = strm.next_out - next_out_utf8;
  13951. utf8str = strings.buf2string(strm.output, next_out_utf8);
  13952. // move tail
  13953. strm.next_out = tail;
  13954. strm.avail_out = chunkSize - tail;
  13955. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  13956. this.onData(utf8str);
  13957. } else {
  13958. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  13959. }
  13960. }
  13961. }
  13962. // When no more input data, we should check that internal inflate buffers
  13963. // are flushed. The only way to do it when avail_out = 0 - run one more
  13964. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  13965. // Here we set flag to process this error properly.
  13966. //
  13967. // NOTE. Deflate does not return error in this case and does not needs such
  13968. // logic.
  13969. if (strm.avail_in === 0 && strm.avail_out === 0) {
  13970. allowBufError = true;
  13971. }
  13972. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  13973. if (status === c.Z_STREAM_END) {
  13974. _mode = c.Z_FINISH;
  13975. }
  13976. // Finalize on the last chunk.
  13977. if (_mode === c.Z_FINISH) {
  13978. status = zlib_inflate.inflateEnd(this.strm);
  13979. this.onEnd(status);
  13980. this.ended = true;
  13981. return status === c.Z_OK;
  13982. }
  13983. // callback interim results if Z_SYNC_FLUSH.
  13984. if (_mode === c.Z_SYNC_FLUSH) {
  13985. this.onEnd(c.Z_OK);
  13986. strm.avail_out = 0;
  13987. return true;
  13988. }
  13989. return true;
  13990. };
  13991. /**
  13992. * Inflate#onData(chunk) -> Void
  13993. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  13994. * on js engine support. When string output requested, each chunk
  13995. * will be string.
  13996. *
  13997. * By default, stores data blocks in `chunks[]` property and glue
  13998. * those in `onEnd`. Override this handler, if you need another behaviour.
  13999. **/
  14000. Inflate.prototype.onData = function(chunk) {
  14001. this.chunks.push(chunk);
  14002. };
  14003. /**
  14004. * Inflate#onEnd(status) -> Void
  14005. * - status (Number): inflate status. 0 (Z_OK) on success,
  14006. * other if not.
  14007. *
  14008. * Called either after you tell inflate that the input stream is
  14009. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  14010. * or if an error happened. By default - join collected chunks,
  14011. * free memory and fill `results` / `err` properties.
  14012. **/
  14013. Inflate.prototype.onEnd = function(status) {
  14014. // On success - join
  14015. if (status === c.Z_OK) {
  14016. if (this.options.to === 'string') {
  14017. // Glue & convert here, until we teach pako to send
  14018. // utf8 alligned strings to onData
  14019. this.result = this.chunks.join('');
  14020. } else {
  14021. this.result = utils.flattenChunks(this.chunks);
  14022. }
  14023. }
  14024. this.chunks = [];
  14025. this.err = status;
  14026. this.msg = this.strm.msg;
  14027. };
  14028. /**
  14029. * inflate(data[, options]) -> Uint8Array|Array|String
  14030. * - data (Uint8Array|Array|String): input data to decompress.
  14031. * - options (Object): zlib inflate options.
  14032. *
  14033. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  14034. * format via wrapper header by default. That's why we don't provide
  14035. * separate `ungzip` method.
  14036. *
  14037. * Supported options are:
  14038. *
  14039. * - windowBits
  14040. *
  14041. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14042. * for more information.
  14043. *
  14044. * Sugar (options):
  14045. *
  14046. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  14047. * negative windowBits implicitly.
  14048. * - `to` (String) - if equal to 'string', then result will be converted
  14049. * from utf8 to utf16 (javascript) string. When string output requested,
  14050. * chunk length can differ from `chunkSize`, depending on content.
  14051. *
  14052. *
  14053. * ##### Example:
  14054. *
  14055. * ```javascript
  14056. * var pako = require('pako')
  14057. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  14058. * , output;
  14059. *
  14060. * try {
  14061. * output = pako.inflate(input);
  14062. * } catch (err)
  14063. * console.log(err);
  14064. * }
  14065. * ```
  14066. **/
  14067. function inflate(input, options) {
  14068. var inflator = new Inflate(options);
  14069. inflator.push(input, true);
  14070. // That will never happens, if you don't cheat with options :)
  14071. if (inflator.err) { throw inflator.msg; }
  14072. return inflator.result;
  14073. }
  14074. /**
  14075. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  14076. * - data (Uint8Array|Array|String): input data to decompress.
  14077. * - options (Object): zlib inflate options.
  14078. *
  14079. * The same as [[inflate]], but creates raw data, without wrapper
  14080. * (header and adler32 crc).
  14081. **/
  14082. function inflateRaw(input, options) {
  14083. options = options || {};
  14084. options.raw = true;
  14085. return inflate(input, options);
  14086. }
  14087. /**
  14088. * ungzip(data[, options]) -> Uint8Array|Array|String
  14089. * - data (Uint8Array|Array|String): input data to decompress.
  14090. * - options (Object): zlib inflate options.
  14091. *
  14092. * Just shortcut to [[inflate]], because it autodetects format
  14093. * by header.content. Done for convenience.
  14094. **/
  14095. exports.Inflate = Inflate;
  14096. exports.inflate = inflate;
  14097. exports.inflateRaw = inflateRaw;
  14098. exports.ungzip = inflate;
  14099. },{"./utils/common":51,"./utils/strings":52,"./zlib/constants":54,"./zlib/gzheader":57,"./zlib/inflate.js":59,"./zlib/messages":61,"./zlib/zstream":63}],51:[function(require,module,exports){
  14100. 'use strict';
  14101. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  14102. (typeof Uint16Array !== 'undefined') &&
  14103. (typeof Int32Array !== 'undefined');
  14104. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  14105. var sources = Array.prototype.slice.call(arguments, 1);
  14106. while (sources.length) {
  14107. var source = sources.shift();
  14108. if (!source) { continue; }
  14109. if (typeof source !== 'object') {
  14110. throw new TypeError(source + 'must be non-object');
  14111. }
  14112. for (var p in source) {
  14113. if (source.hasOwnProperty(p)) {
  14114. obj[p] = source[p];
  14115. }
  14116. }
  14117. }
  14118. return obj;
  14119. };
  14120. // reduce buffer size, avoiding mem copy
  14121. exports.shrinkBuf = function (buf, size) {
  14122. if (buf.length === size) { return buf; }
  14123. if (buf.subarray) { return buf.subarray(0, size); }
  14124. buf.length = size;
  14125. return buf;
  14126. };
  14127. var fnTyped = {
  14128. arraySet: function (dest, src, src_offs, len, dest_offs) {
  14129. if (src.subarray && dest.subarray) {
  14130. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  14131. return;
  14132. }
  14133. // Fallback to ordinary array
  14134. for (var i=0; i<len; i++) {
  14135. dest[dest_offs + i] = src[src_offs + i];
  14136. }
  14137. },
  14138. // Join array of chunks to single array.
  14139. flattenChunks: function(chunks) {
  14140. var i, l, len, pos, chunk, result;
  14141. // calculate data length
  14142. len = 0;
  14143. for (i=0, l=chunks.length; i<l; i++) {
  14144. len += chunks[i].length;
  14145. }
  14146. // join chunks
  14147. result = new Uint8Array(len);
  14148. pos = 0;
  14149. for (i=0, l=chunks.length; i<l; i++) {
  14150. chunk = chunks[i];
  14151. result.set(chunk, pos);
  14152. pos += chunk.length;
  14153. }
  14154. return result;
  14155. }
  14156. };
  14157. var fnUntyped = {
  14158. arraySet: function (dest, src, src_offs, len, dest_offs) {
  14159. for (var i=0; i<len; i++) {
  14160. dest[dest_offs + i] = src[src_offs + i];
  14161. }
  14162. },
  14163. // Join array of chunks to single array.
  14164. flattenChunks: function(chunks) {
  14165. return [].concat.apply([], chunks);
  14166. }
  14167. };
  14168. // Enable/Disable typed arrays use, for testing
  14169. //
  14170. exports.setTyped = function (on) {
  14171. if (on) {
  14172. exports.Buf8 = Uint8Array;
  14173. exports.Buf16 = Uint16Array;
  14174. exports.Buf32 = Int32Array;
  14175. exports.assign(exports, fnTyped);
  14176. } else {
  14177. exports.Buf8 = Array;
  14178. exports.Buf16 = Array;
  14179. exports.Buf32 = Array;
  14180. exports.assign(exports, fnUntyped);
  14181. }
  14182. };
  14183. exports.setTyped(TYPED_OK);
  14184. },{}],52:[function(require,module,exports){
  14185. // String encode/decode helpers
  14186. 'use strict';
  14187. var utils = require('./common');
  14188. // Quick check if we can use fast array to bin string conversion
  14189. //
  14190. // - apply(Array) can fail on Android 2.2
  14191. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  14192. //
  14193. var STR_APPLY_OK = true;
  14194. var STR_APPLY_UIA_OK = true;
  14195. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  14196. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  14197. // Table with utf8 lengths (calculated by first byte of sequence)
  14198. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  14199. // because max possible codepoint is 0x10ffff
  14200. var _utf8len = new utils.Buf8(256);
  14201. for (var q=0; q<256; q++) {
  14202. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  14203. }
  14204. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  14205. // convert string to array (typed, when possible)
  14206. exports.string2buf = function (str) {
  14207. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  14208. // count binary size
  14209. for (m_pos = 0; m_pos < str_len; m_pos++) {
  14210. c = str.charCodeAt(m_pos);
  14211. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  14212. c2 = str.charCodeAt(m_pos+1);
  14213. if ((c2 & 0xfc00) === 0xdc00) {
  14214. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  14215. m_pos++;
  14216. }
  14217. }
  14218. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  14219. }
  14220. // allocate buffer
  14221. buf = new utils.Buf8(buf_len);
  14222. // convert
  14223. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  14224. c = str.charCodeAt(m_pos);
  14225. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  14226. c2 = str.charCodeAt(m_pos+1);
  14227. if ((c2 & 0xfc00) === 0xdc00) {
  14228. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  14229. m_pos++;
  14230. }
  14231. }
  14232. if (c < 0x80) {
  14233. /* one byte */
  14234. buf[i++] = c;
  14235. } else if (c < 0x800) {
  14236. /* two bytes */
  14237. buf[i++] = 0xC0 | (c >>> 6);
  14238. buf[i++] = 0x80 | (c & 0x3f);
  14239. } else if (c < 0x10000) {
  14240. /* three bytes */
  14241. buf[i++] = 0xE0 | (c >>> 12);
  14242. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  14243. buf[i++] = 0x80 | (c & 0x3f);
  14244. } else {
  14245. /* four bytes */
  14246. buf[i++] = 0xf0 | (c >>> 18);
  14247. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  14248. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  14249. buf[i++] = 0x80 | (c & 0x3f);
  14250. }
  14251. }
  14252. return buf;
  14253. };
  14254. // Helper (used in 2 places)
  14255. function buf2binstring(buf, len) {
  14256. // use fallback for big arrays to avoid stack overflow
  14257. if (len < 65537) {
  14258. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  14259. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  14260. }
  14261. }
  14262. var result = '';
  14263. for (var i=0; i < len; i++) {
  14264. result += String.fromCharCode(buf[i]);
  14265. }
  14266. return result;
  14267. }
  14268. // Convert byte array to binary string
  14269. exports.buf2binstring = function(buf) {
  14270. return buf2binstring(buf, buf.length);
  14271. };
  14272. // Convert binary string (typed, when possible)
  14273. exports.binstring2buf = function(str) {
  14274. var buf = new utils.Buf8(str.length);
  14275. for (var i=0, len=buf.length; i < len; i++) {
  14276. buf[i] = str.charCodeAt(i);
  14277. }
  14278. return buf;
  14279. };
  14280. // convert array to string
  14281. exports.buf2string = function (buf, max) {
  14282. var i, out, c, c_len;
  14283. var len = max || buf.length;
  14284. // Reserve max possible length (2 words per char)
  14285. // NB: by unknown reasons, Array is significantly faster for
  14286. // String.fromCharCode.apply than Uint16Array.
  14287. var utf16buf = new Array(len*2);
  14288. for (out=0, i=0; i<len;) {
  14289. c = buf[i++];
  14290. // quick process ascii
  14291. if (c < 0x80) { utf16buf[out++] = c; continue; }
  14292. c_len = _utf8len[c];
  14293. // skip 5 & 6 byte codes
  14294. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  14295. // apply mask on first byte
  14296. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  14297. // join the rest
  14298. while (c_len > 1 && i < len) {
  14299. c = (c << 6) | (buf[i++] & 0x3f);
  14300. c_len--;
  14301. }
  14302. // terminated by end of string?
  14303. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  14304. if (c < 0x10000) {
  14305. utf16buf[out++] = c;
  14306. } else {
  14307. c -= 0x10000;
  14308. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  14309. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  14310. }
  14311. }
  14312. return buf2binstring(utf16buf, out);
  14313. };
  14314. // Calculate max possible position in utf8 buffer,
  14315. // that will not break sequence. If that's not possible
  14316. // - (very small limits) return max size as is.
  14317. //
  14318. // buf[] - utf8 bytes array
  14319. // max - length limit (mandatory);
  14320. exports.utf8border = function(buf, max) {
  14321. var pos;
  14322. max = max || buf.length;
  14323. if (max > buf.length) { max = buf.length; }
  14324. // go back from last position, until start of sequence found
  14325. pos = max-1;
  14326. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  14327. // Fuckup - very small and broken sequence,
  14328. // return max, because we should return something anyway.
  14329. if (pos < 0) { return max; }
  14330. // If we came to start of buffer - that means vuffer is too small,
  14331. // return max too.
  14332. if (pos === 0) { return max; }
  14333. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  14334. };
  14335. },{"./common":51}],53:[function(require,module,exports){
  14336. 'use strict';
  14337. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  14338. // It doesn't worth to make additional optimizationa as in original.
  14339. // Small size is preferable.
  14340. function adler32(adler, buf, len, pos) {
  14341. var s1 = (adler & 0xffff) |0,
  14342. s2 = ((adler >>> 16) & 0xffff) |0,
  14343. n = 0;
  14344. while (len !== 0) {
  14345. // Set limit ~ twice less than 5552, to keep
  14346. // s2 in 31-bits, because we force signed ints.
  14347. // in other case %= will fail.
  14348. n = len > 2000 ? 2000 : len;
  14349. len -= n;
  14350. do {
  14351. s1 = (s1 + buf[pos++]) |0;
  14352. s2 = (s2 + s1) |0;
  14353. } while (--n);
  14354. s1 %= 65521;
  14355. s2 %= 65521;
  14356. }
  14357. return (s1 | (s2 << 16)) |0;
  14358. }
  14359. module.exports = adler32;
  14360. },{}],54:[function(require,module,exports){
  14361. module.exports = {
  14362. /* Allowed flush values; see deflate() and inflate() below for details */
  14363. Z_NO_FLUSH: 0,
  14364. Z_PARTIAL_FLUSH: 1,
  14365. Z_SYNC_FLUSH: 2,
  14366. Z_FULL_FLUSH: 3,
  14367. Z_FINISH: 4,
  14368. Z_BLOCK: 5,
  14369. Z_TREES: 6,
  14370. /* Return codes for the compression/decompression functions. Negative values
  14371. * are errors, positive values are used for special but normal events.
  14372. */
  14373. Z_OK: 0,
  14374. Z_STREAM_END: 1,
  14375. Z_NEED_DICT: 2,
  14376. Z_ERRNO: -1,
  14377. Z_STREAM_ERROR: -2,
  14378. Z_DATA_ERROR: -3,
  14379. //Z_MEM_ERROR: -4,
  14380. Z_BUF_ERROR: -5,
  14381. //Z_VERSION_ERROR: -6,
  14382. /* compression levels */
  14383. Z_NO_COMPRESSION: 0,
  14384. Z_BEST_SPEED: 1,
  14385. Z_BEST_COMPRESSION: 9,
  14386. Z_DEFAULT_COMPRESSION: -1,
  14387. Z_FILTERED: 1,
  14388. Z_HUFFMAN_ONLY: 2,
  14389. Z_RLE: 3,
  14390. Z_FIXED: 4,
  14391. Z_DEFAULT_STRATEGY: 0,
  14392. /* Possible values of the data_type field (though see inflate()) */
  14393. Z_BINARY: 0,
  14394. Z_TEXT: 1,
  14395. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  14396. Z_UNKNOWN: 2,
  14397. /* The deflate compression method */
  14398. Z_DEFLATED: 8
  14399. //Z_NULL: null // Use -1 or null inline, depending on var type
  14400. };
  14401. },{}],55:[function(require,module,exports){
  14402. 'use strict';
  14403. // Note: we can't get significant speed boost here.
  14404. // So write code to minimize size - no pregenerated tables
  14405. // and array tools dependencies.
  14406. // Use ordinary array, since untyped makes no boost here
  14407. function makeTable() {
  14408. var c, table = [];
  14409. for (var n =0; n < 256; n++) {
  14410. c = n;
  14411. for (var k =0; k < 8; k++) {
  14412. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  14413. }
  14414. table[n] = c;
  14415. }
  14416. return table;
  14417. }
  14418. // Create table on load. Just 255 signed longs. Not a problem.
  14419. var crcTable = makeTable();
  14420. function crc32(crc, buf, len, pos) {
  14421. var t = crcTable,
  14422. end = pos + len;
  14423. crc = crc ^ (-1);
  14424. for (var i = pos; i < end; i++) {
  14425. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  14426. }
  14427. return (crc ^ (-1)); // >>> 0;
  14428. }
  14429. module.exports = crc32;
  14430. },{}],56:[function(require,module,exports){
  14431. 'use strict';
  14432. var utils = require('../utils/common');
  14433. var trees = require('./trees');
  14434. var adler32 = require('./adler32');
  14435. var crc32 = require('./crc32');
  14436. var msg = require('./messages');
  14437. /* Public constants ==========================================================*/
  14438. /* ===========================================================================*/
  14439. /* Allowed flush values; see deflate() and inflate() below for details */
  14440. var Z_NO_FLUSH = 0;
  14441. var Z_PARTIAL_FLUSH = 1;
  14442. //var Z_SYNC_FLUSH = 2;
  14443. var Z_FULL_FLUSH = 3;
  14444. var Z_FINISH = 4;
  14445. var Z_BLOCK = 5;
  14446. //var Z_TREES = 6;
  14447. /* Return codes for the compression/decompression functions. Negative values
  14448. * are errors, positive values are used for special but normal events.
  14449. */
  14450. var Z_OK = 0;
  14451. var Z_STREAM_END = 1;
  14452. //var Z_NEED_DICT = 2;
  14453. //var Z_ERRNO = -1;
  14454. var Z_STREAM_ERROR = -2;
  14455. var Z_DATA_ERROR = -3;
  14456. //var Z_MEM_ERROR = -4;
  14457. var Z_BUF_ERROR = -5;
  14458. //var Z_VERSION_ERROR = -6;
  14459. /* compression levels */
  14460. //var Z_NO_COMPRESSION = 0;
  14461. //var Z_BEST_SPEED = 1;
  14462. //var Z_BEST_COMPRESSION = 9;
  14463. var Z_DEFAULT_COMPRESSION = -1;
  14464. var Z_FILTERED = 1;
  14465. var Z_HUFFMAN_ONLY = 2;
  14466. var Z_RLE = 3;
  14467. var Z_FIXED = 4;
  14468. var Z_DEFAULT_STRATEGY = 0;
  14469. /* Possible values of the data_type field (though see inflate()) */
  14470. //var Z_BINARY = 0;
  14471. //var Z_TEXT = 1;
  14472. //var Z_ASCII = 1; // = Z_TEXT
  14473. var Z_UNKNOWN = 2;
  14474. /* The deflate compression method */
  14475. var Z_DEFLATED = 8;
  14476. /*============================================================================*/
  14477. var MAX_MEM_LEVEL = 9;
  14478. /* Maximum value for memLevel in deflateInit2 */
  14479. var MAX_WBITS = 15;
  14480. /* 32K LZ77 window */
  14481. var DEF_MEM_LEVEL = 8;
  14482. var LENGTH_CODES = 29;
  14483. /* number of length codes, not counting the special END_BLOCK code */
  14484. var LITERALS = 256;
  14485. /* number of literal bytes 0..255 */
  14486. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  14487. /* number of Literal or Length codes, including the END_BLOCK code */
  14488. var D_CODES = 30;
  14489. /* number of distance codes */
  14490. var BL_CODES = 19;
  14491. /* number of codes used to transfer the bit lengths */
  14492. var HEAP_SIZE = 2*L_CODES + 1;
  14493. /* maximum heap size */
  14494. var MAX_BITS = 15;
  14495. /* All codes must not exceed MAX_BITS bits */
  14496. var MIN_MATCH = 3;
  14497. var MAX_MATCH = 258;
  14498. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  14499. var PRESET_DICT = 0x20;
  14500. var INIT_STATE = 42;
  14501. var EXTRA_STATE = 69;
  14502. var NAME_STATE = 73;
  14503. var COMMENT_STATE = 91;
  14504. var HCRC_STATE = 103;
  14505. var BUSY_STATE = 113;
  14506. var FINISH_STATE = 666;
  14507. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  14508. var BS_BLOCK_DONE = 2; /* block flush performed */
  14509. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  14510. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  14511. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  14512. function err(strm, errorCode) {
  14513. strm.msg = msg[errorCode];
  14514. return errorCode;
  14515. }
  14516. function rank(f) {
  14517. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  14518. }
  14519. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  14520. /* =========================================================================
  14521. * Flush as much pending output as possible. All deflate() output goes
  14522. * through this function so some applications may wish to modify it
  14523. * to avoid allocating a large strm->output buffer and copying into it.
  14524. * (See also read_buf()).
  14525. */
  14526. function flush_pending(strm) {
  14527. var s = strm.state;
  14528. //_tr_flush_bits(s);
  14529. var len = s.pending;
  14530. if (len > strm.avail_out) {
  14531. len = strm.avail_out;
  14532. }
  14533. if (len === 0) { return; }
  14534. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  14535. strm.next_out += len;
  14536. s.pending_out += len;
  14537. strm.total_out += len;
  14538. strm.avail_out -= len;
  14539. s.pending -= len;
  14540. if (s.pending === 0) {
  14541. s.pending_out = 0;
  14542. }
  14543. }
  14544. function flush_block_only (s, last) {
  14545. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  14546. s.block_start = s.strstart;
  14547. flush_pending(s.strm);
  14548. }
  14549. function put_byte(s, b) {
  14550. s.pending_buf[s.pending++] = b;
  14551. }
  14552. /* =========================================================================
  14553. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  14554. * IN assertion: the stream state is correct and there is enough room in
  14555. * pending_buf.
  14556. */
  14557. function putShortMSB(s, b) {
  14558. // put_byte(s, (Byte)(b >> 8));
  14559. // put_byte(s, (Byte)(b & 0xff));
  14560. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  14561. s.pending_buf[s.pending++] = b & 0xff;
  14562. }
  14563. /* ===========================================================================
  14564. * Read a new buffer from the current input stream, update the adler32
  14565. * and total number of bytes read. All deflate() input goes through
  14566. * this function so some applications may wish to modify it to avoid
  14567. * allocating a large strm->input buffer and copying from it.
  14568. * (See also flush_pending()).
  14569. */
  14570. function read_buf(strm, buf, start, size) {
  14571. var len = strm.avail_in;
  14572. if (len > size) { len = size; }
  14573. if (len === 0) { return 0; }
  14574. strm.avail_in -= len;
  14575. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  14576. if (strm.state.wrap === 1) {
  14577. strm.adler = adler32(strm.adler, buf, len, start);
  14578. }
  14579. else if (strm.state.wrap === 2) {
  14580. strm.adler = crc32(strm.adler, buf, len, start);
  14581. }
  14582. strm.next_in += len;
  14583. strm.total_in += len;
  14584. return len;
  14585. }
  14586. /* ===========================================================================
  14587. * Set match_start to the longest match starting at the given string and
  14588. * return its length. Matches shorter or equal to prev_length are discarded,
  14589. * in which case the result is equal to prev_length and match_start is
  14590. * garbage.
  14591. * IN assertions: cur_match is the head of the hash chain for the current
  14592. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  14593. * OUT assertion: the match length is not greater than s->lookahead.
  14594. */
  14595. function longest_match(s, cur_match) {
  14596. var chain_length = s.max_chain_length; /* max hash chain length */
  14597. var scan = s.strstart; /* current string */
  14598. var match; /* matched string */
  14599. var len; /* length of current match */
  14600. var best_len = s.prev_length; /* best match length so far */
  14601. var nice_match = s.nice_match; /* stop if match long enough */
  14602. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  14603. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  14604. var _win = s.window; // shortcut
  14605. var wmask = s.w_mask;
  14606. var prev = s.prev;
  14607. /* Stop when cur_match becomes <= limit. To simplify the code,
  14608. * we prevent matches with the string of window index 0.
  14609. */
  14610. var strend = s.strstart + MAX_MATCH;
  14611. var scan_end1 = _win[scan + best_len - 1];
  14612. var scan_end = _win[scan + best_len];
  14613. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  14614. * It is easy to get rid of this optimization if necessary.
  14615. */
  14616. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  14617. /* Do not waste too much time if we already have a good match: */
  14618. if (s.prev_length >= s.good_match) {
  14619. chain_length >>= 2;
  14620. }
  14621. /* Do not look for matches beyond the end of the input. This is necessary
  14622. * to make deflate deterministic.
  14623. */
  14624. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  14625. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  14626. do {
  14627. // Assert(cur_match < s->strstart, "no future");
  14628. match = cur_match;
  14629. /* Skip to next match if the match length cannot increase
  14630. * or if the match length is less than 2. Note that the checks below
  14631. * for insufficient lookahead only occur occasionally for performance
  14632. * reasons. Therefore uninitialized memory will be accessed, and
  14633. * conditional jumps will be made that depend on those values.
  14634. * However the length of the match is limited to the lookahead, so
  14635. * the output of deflate is not affected by the uninitialized values.
  14636. */
  14637. if (_win[match + best_len] !== scan_end ||
  14638. _win[match + best_len - 1] !== scan_end1 ||
  14639. _win[match] !== _win[scan] ||
  14640. _win[++match] !== _win[scan + 1]) {
  14641. continue;
  14642. }
  14643. /* The check at best_len-1 can be removed because it will be made
  14644. * again later. (This heuristic is not always a win.)
  14645. * It is not necessary to compare scan[2] and match[2] since they
  14646. * are always equal when the other bytes match, given that
  14647. * the hash keys are equal and that HASH_BITS >= 8.
  14648. */
  14649. scan += 2;
  14650. match++;
  14651. // Assert(*scan == *match, "match[2]?");
  14652. /* We check for insufficient lookahead only every 8th comparison;
  14653. * the 256th check will be made at strstart+258.
  14654. */
  14655. do {
  14656. /*jshint noempty:false*/
  14657. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14658. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14659. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14660. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14661. scan < strend);
  14662. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  14663. len = MAX_MATCH - (strend - scan);
  14664. scan = strend - MAX_MATCH;
  14665. if (len > best_len) {
  14666. s.match_start = cur_match;
  14667. best_len = len;
  14668. if (len >= nice_match) {
  14669. break;
  14670. }
  14671. scan_end1 = _win[scan + best_len - 1];
  14672. scan_end = _win[scan + best_len];
  14673. }
  14674. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  14675. if (best_len <= s.lookahead) {
  14676. return best_len;
  14677. }
  14678. return s.lookahead;
  14679. }
  14680. /* ===========================================================================
  14681. * Fill the window when the lookahead becomes insufficient.
  14682. * Updates strstart and lookahead.
  14683. *
  14684. * IN assertion: lookahead < MIN_LOOKAHEAD
  14685. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  14686. * At least one byte has been read, or avail_in == 0; reads are
  14687. * performed for at least two bytes (required for the zip translate_eol
  14688. * option -- not supported here).
  14689. */
  14690. function fill_window(s) {
  14691. var _w_size = s.w_size;
  14692. var p, n, m, more, str;
  14693. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  14694. do {
  14695. more = s.window_size - s.lookahead - s.strstart;
  14696. // JS ints have 32 bit, block below not needed
  14697. /* Deal with !@#$% 64K limit: */
  14698. //if (sizeof(int) <= 2) {
  14699. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  14700. // more = wsize;
  14701. //
  14702. // } else if (more == (unsigned)(-1)) {
  14703. // /* Very unlikely, but possible on 16 bit machine if
  14704. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  14705. // */
  14706. // more--;
  14707. // }
  14708. //}
  14709. /* If the window is almost full and there is insufficient lookahead,
  14710. * move the upper half to the lower one to make room in the upper half.
  14711. */
  14712. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  14713. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  14714. s.match_start -= _w_size;
  14715. s.strstart -= _w_size;
  14716. /* we now have strstart >= MAX_DIST */
  14717. s.block_start -= _w_size;
  14718. /* Slide the hash table (could be avoided with 32 bit values
  14719. at the expense of memory usage). We slide even when level == 0
  14720. to keep the hash table consistent if we switch back to level > 0
  14721. later. (Using level 0 permanently is not an optimal usage of
  14722. zlib, so we don't care about this pathological case.)
  14723. */
  14724. n = s.hash_size;
  14725. p = n;
  14726. do {
  14727. m = s.head[--p];
  14728. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  14729. } while (--n);
  14730. n = _w_size;
  14731. p = n;
  14732. do {
  14733. m = s.prev[--p];
  14734. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  14735. /* If n is not on any hash chain, prev[n] is garbage but
  14736. * its value will never be used.
  14737. */
  14738. } while (--n);
  14739. more += _w_size;
  14740. }
  14741. if (s.strm.avail_in === 0) {
  14742. break;
  14743. }
  14744. /* If there was no sliding:
  14745. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  14746. * more == window_size - lookahead - strstart
  14747. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  14748. * => more >= window_size - 2*WSIZE + 2
  14749. * In the BIG_MEM or MMAP case (not yet supported),
  14750. * window_size == input_size + MIN_LOOKAHEAD &&
  14751. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  14752. * Otherwise, window_size == 2*WSIZE so more >= 2.
  14753. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  14754. */
  14755. //Assert(more >= 2, "more < 2");
  14756. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  14757. s.lookahead += n;
  14758. /* Initialize the hash value now that we have some input: */
  14759. if (s.lookahead + s.insert >= MIN_MATCH) {
  14760. str = s.strstart - s.insert;
  14761. s.ins_h = s.window[str];
  14762. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  14763. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  14764. //#if MIN_MATCH != 3
  14765. // Call update_hash() MIN_MATCH-3 more times
  14766. //#endif
  14767. while (s.insert) {
  14768. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  14769. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  14770. s.prev[str & s.w_mask] = s.head[s.ins_h];
  14771. s.head[s.ins_h] = str;
  14772. str++;
  14773. s.insert--;
  14774. if (s.lookahead + s.insert < MIN_MATCH) {
  14775. break;
  14776. }
  14777. }
  14778. }
  14779. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  14780. * but this is not important since only literal bytes will be emitted.
  14781. */
  14782. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  14783. /* If the WIN_INIT bytes after the end of the current data have never been
  14784. * written, then zero those bytes in order to avoid memory check reports of
  14785. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  14786. * the longest match routines. Update the high water mark for the next
  14787. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  14788. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  14789. */
  14790. // if (s.high_water < s.window_size) {
  14791. // var curr = s.strstart + s.lookahead;
  14792. // var init = 0;
  14793. //
  14794. // if (s.high_water < curr) {
  14795. // /* Previous high water mark below current data -- zero WIN_INIT
  14796. // * bytes or up to end of window, whichever is less.
  14797. // */
  14798. // init = s.window_size - curr;
  14799. // if (init > WIN_INIT)
  14800. // init = WIN_INIT;
  14801. // zmemzero(s->window + curr, (unsigned)init);
  14802. // s->high_water = curr + init;
  14803. // }
  14804. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  14805. // /* High water mark at or above current data, but below current data
  14806. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  14807. // * to end of window, whichever is less.
  14808. // */
  14809. // init = (ulg)curr + WIN_INIT - s->high_water;
  14810. // if (init > s->window_size - s->high_water)
  14811. // init = s->window_size - s->high_water;
  14812. // zmemzero(s->window + s->high_water, (unsigned)init);
  14813. // s->high_water += init;
  14814. // }
  14815. // }
  14816. //
  14817. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  14818. // "not enough room for search");
  14819. }
  14820. /* ===========================================================================
  14821. * Copy without compression as much as possible from the input stream, return
  14822. * the current block state.
  14823. * This function does not insert new strings in the dictionary since
  14824. * uncompressible data is probably not useful. This function is used
  14825. * only for the level=0 compression option.
  14826. * NOTE: this function should be optimized to avoid extra copying from
  14827. * window to pending_buf.
  14828. */
  14829. function deflate_stored(s, flush) {
  14830. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  14831. * to pending_buf_size, and each stored block has a 5 byte header:
  14832. */
  14833. var max_block_size = 0xffff;
  14834. if (max_block_size > s.pending_buf_size - 5) {
  14835. max_block_size = s.pending_buf_size - 5;
  14836. }
  14837. /* Copy as much as possible from input to output: */
  14838. for (;;) {
  14839. /* Fill the window as much as possible: */
  14840. if (s.lookahead <= 1) {
  14841. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  14842. // s->block_start >= (long)s->w_size, "slide too late");
  14843. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  14844. // s.block_start >= s.w_size)) {
  14845. // throw new Error("slide too late");
  14846. // }
  14847. fill_window(s);
  14848. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  14849. return BS_NEED_MORE;
  14850. }
  14851. if (s.lookahead === 0) {
  14852. break;
  14853. }
  14854. /* flush the current block */
  14855. }
  14856. //Assert(s->block_start >= 0L, "block gone");
  14857. // if (s.block_start < 0) throw new Error("block gone");
  14858. s.strstart += s.lookahead;
  14859. s.lookahead = 0;
  14860. /* Emit a stored block if pending_buf will be full: */
  14861. var max_start = s.block_start + max_block_size;
  14862. if (s.strstart === 0 || s.strstart >= max_start) {
  14863. /* strstart == 0 is possible when wraparound on 16-bit machine */
  14864. s.lookahead = s.strstart - max_start;
  14865. s.strstart = max_start;
  14866. /*** FLUSH_BLOCK(s, 0); ***/
  14867. flush_block_only(s, false);
  14868. if (s.strm.avail_out === 0) {
  14869. return BS_NEED_MORE;
  14870. }
  14871. /***/
  14872. }
  14873. /* Flush if we may have to slide, otherwise block_start may become
  14874. * negative and the data will be gone:
  14875. */
  14876. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  14877. /*** FLUSH_BLOCK(s, 0); ***/
  14878. flush_block_only(s, false);
  14879. if (s.strm.avail_out === 0) {
  14880. return BS_NEED_MORE;
  14881. }
  14882. /***/
  14883. }
  14884. }
  14885. s.insert = 0;
  14886. if (flush === Z_FINISH) {
  14887. /*** FLUSH_BLOCK(s, 1); ***/
  14888. flush_block_only(s, true);
  14889. if (s.strm.avail_out === 0) {
  14890. return BS_FINISH_STARTED;
  14891. }
  14892. /***/
  14893. return BS_FINISH_DONE;
  14894. }
  14895. if (s.strstart > s.block_start) {
  14896. /*** FLUSH_BLOCK(s, 0); ***/
  14897. flush_block_only(s, false);
  14898. if (s.strm.avail_out === 0) {
  14899. return BS_NEED_MORE;
  14900. }
  14901. /***/
  14902. }
  14903. return BS_NEED_MORE;
  14904. }
  14905. /* ===========================================================================
  14906. * Compress as much as possible from the input stream, return the current
  14907. * block state.
  14908. * This function does not perform lazy evaluation of matches and inserts
  14909. * new strings in the dictionary only for unmatched strings or for short
  14910. * matches. It is used only for the fast compression options.
  14911. */
  14912. function deflate_fast(s, flush) {
  14913. var hash_head; /* head of the hash chain */
  14914. var bflush; /* set if current block must be flushed */
  14915. for (;;) {
  14916. /* Make sure that we always have enough lookahead, except
  14917. * at the end of the input file. We need MAX_MATCH bytes
  14918. * for the next match, plus MIN_MATCH bytes to insert the
  14919. * string following the next match.
  14920. */
  14921. if (s.lookahead < MIN_LOOKAHEAD) {
  14922. fill_window(s);
  14923. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  14924. return BS_NEED_MORE;
  14925. }
  14926. if (s.lookahead === 0) {
  14927. break; /* flush the current block */
  14928. }
  14929. }
  14930. /* Insert the string window[strstart .. strstart+2] in the
  14931. * dictionary, and set hash_head to the head of the hash chain:
  14932. */
  14933. hash_head = 0/*NIL*/;
  14934. if (s.lookahead >= MIN_MATCH) {
  14935. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14936. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14937. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14938. s.head[s.ins_h] = s.strstart;
  14939. /***/
  14940. }
  14941. /* Find the longest match, discarding those <= prev_length.
  14942. * At this point we have always match_length < MIN_MATCH
  14943. */
  14944. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  14945. /* To simplify the code, we prevent matches with the string
  14946. * of window index 0 (in particular we have to avoid a match
  14947. * of the string with itself at the start of the input file).
  14948. */
  14949. s.match_length = longest_match(s, hash_head);
  14950. /* longest_match() sets match_start */
  14951. }
  14952. if (s.match_length >= MIN_MATCH) {
  14953. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  14954. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  14955. s.match_length - MIN_MATCH, bflush); ***/
  14956. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  14957. s.lookahead -= s.match_length;
  14958. /* Insert new strings in the hash table only if the match length
  14959. * is not too large. This saves time but degrades compression.
  14960. */
  14961. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  14962. s.match_length--; /* string at strstart already in table */
  14963. do {
  14964. s.strstart++;
  14965. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14966. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14967. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14968. s.head[s.ins_h] = s.strstart;
  14969. /***/
  14970. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  14971. * always MIN_MATCH bytes ahead.
  14972. */
  14973. } while (--s.match_length !== 0);
  14974. s.strstart++;
  14975. } else
  14976. {
  14977. s.strstart += s.match_length;
  14978. s.match_length = 0;
  14979. s.ins_h = s.window[s.strstart];
  14980. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  14981. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  14982. //#if MIN_MATCH != 3
  14983. // Call UPDATE_HASH() MIN_MATCH-3 more times
  14984. //#endif
  14985. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  14986. * matter since it will be recomputed at next deflate call.
  14987. */
  14988. }
  14989. } else {
  14990. /* No match, output a literal byte */
  14991. //Tracevv((stderr,"%c", s.window[s.strstart]));
  14992. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14993. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14994. s.lookahead--;
  14995. s.strstart++;
  14996. }
  14997. if (bflush) {
  14998. /*** FLUSH_BLOCK(s, 0); ***/
  14999. flush_block_only(s, false);
  15000. if (s.strm.avail_out === 0) {
  15001. return BS_NEED_MORE;
  15002. }
  15003. /***/
  15004. }
  15005. }
  15006. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  15007. if (flush === Z_FINISH) {
  15008. /*** FLUSH_BLOCK(s, 1); ***/
  15009. flush_block_only(s, true);
  15010. if (s.strm.avail_out === 0) {
  15011. return BS_FINISH_STARTED;
  15012. }
  15013. /***/
  15014. return BS_FINISH_DONE;
  15015. }
  15016. if (s.last_lit) {
  15017. /*** FLUSH_BLOCK(s, 0); ***/
  15018. flush_block_only(s, false);
  15019. if (s.strm.avail_out === 0) {
  15020. return BS_NEED_MORE;
  15021. }
  15022. /***/
  15023. }
  15024. return BS_BLOCK_DONE;
  15025. }
  15026. /* ===========================================================================
  15027. * Same as above, but achieves better compression. We use a lazy
  15028. * evaluation for matches: a match is finally adopted only if there is
  15029. * no better match at the next window position.
  15030. */
  15031. function deflate_slow(s, flush) {
  15032. var hash_head; /* head of hash chain */
  15033. var bflush; /* set if current block must be flushed */
  15034. var max_insert;
  15035. /* Process the input block. */
  15036. for (;;) {
  15037. /* Make sure that we always have enough lookahead, except
  15038. * at the end of the input file. We need MAX_MATCH bytes
  15039. * for the next match, plus MIN_MATCH bytes to insert the
  15040. * string following the next match.
  15041. */
  15042. if (s.lookahead < MIN_LOOKAHEAD) {
  15043. fill_window(s);
  15044. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  15045. return BS_NEED_MORE;
  15046. }
  15047. if (s.lookahead === 0) { break; } /* flush the current block */
  15048. }
  15049. /* Insert the string window[strstart .. strstart+2] in the
  15050. * dictionary, and set hash_head to the head of the hash chain:
  15051. */
  15052. hash_head = 0/*NIL*/;
  15053. if (s.lookahead >= MIN_MATCH) {
  15054. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15055. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15056. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15057. s.head[s.ins_h] = s.strstart;
  15058. /***/
  15059. }
  15060. /* Find the longest match, discarding those <= prev_length.
  15061. */
  15062. s.prev_length = s.match_length;
  15063. s.prev_match = s.match_start;
  15064. s.match_length = MIN_MATCH-1;
  15065. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  15066. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  15067. /* To simplify the code, we prevent matches with the string
  15068. * of window index 0 (in particular we have to avoid a match
  15069. * of the string with itself at the start of the input file).
  15070. */
  15071. s.match_length = longest_match(s, hash_head);
  15072. /* longest_match() sets match_start */
  15073. if (s.match_length <= 5 &&
  15074. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  15075. /* If prev_match is also MIN_MATCH, match_start is garbage
  15076. * but we will ignore the current match anyway.
  15077. */
  15078. s.match_length = MIN_MATCH-1;
  15079. }
  15080. }
  15081. /* If there was a match at the previous step and the current
  15082. * match is not better, output the previous match:
  15083. */
  15084. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  15085. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  15086. /* Do not insert strings in hash table beyond this. */
  15087. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  15088. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  15089. s.prev_length - MIN_MATCH, bflush);***/
  15090. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  15091. /* Insert in hash table all strings up to the end of the match.
  15092. * strstart-1 and strstart are already inserted. If there is not
  15093. * enough lookahead, the last two strings are not inserted in
  15094. * the hash table.
  15095. */
  15096. s.lookahead -= s.prev_length-1;
  15097. s.prev_length -= 2;
  15098. do {
  15099. if (++s.strstart <= max_insert) {
  15100. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15101. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15102. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15103. s.head[s.ins_h] = s.strstart;
  15104. /***/
  15105. }
  15106. } while (--s.prev_length !== 0);
  15107. s.match_available = 0;
  15108. s.match_length = MIN_MATCH-1;
  15109. s.strstart++;
  15110. if (bflush) {
  15111. /*** FLUSH_BLOCK(s, 0); ***/
  15112. flush_block_only(s, false);
  15113. if (s.strm.avail_out === 0) {
  15114. return BS_NEED_MORE;
  15115. }
  15116. /***/
  15117. }
  15118. } else if (s.match_available) {
  15119. /* If there was no match at the previous position, output a
  15120. * single literal. If there was a match but the current match
  15121. * is longer, truncate the previous match to a single literal.
  15122. */
  15123. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  15124. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  15125. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  15126. if (bflush) {
  15127. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  15128. flush_block_only(s, false);
  15129. /***/
  15130. }
  15131. s.strstart++;
  15132. s.lookahead--;
  15133. if (s.strm.avail_out === 0) {
  15134. return BS_NEED_MORE;
  15135. }
  15136. } else {
  15137. /* There is no previous match to compare with, wait for
  15138. * the next step to decide.
  15139. */
  15140. s.match_available = 1;
  15141. s.strstart++;
  15142. s.lookahead--;
  15143. }
  15144. }
  15145. //Assert (flush != Z_NO_FLUSH, "no flush?");
  15146. if (s.match_available) {
  15147. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  15148. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  15149. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  15150. s.match_available = 0;
  15151. }
  15152. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  15153. if (flush === Z_FINISH) {
  15154. /*** FLUSH_BLOCK(s, 1); ***/
  15155. flush_block_only(s, true);
  15156. if (s.strm.avail_out === 0) {
  15157. return BS_FINISH_STARTED;
  15158. }
  15159. /***/
  15160. return BS_FINISH_DONE;
  15161. }
  15162. if (s.last_lit) {
  15163. /*** FLUSH_BLOCK(s, 0); ***/
  15164. flush_block_only(s, false);
  15165. if (s.strm.avail_out === 0) {
  15166. return BS_NEED_MORE;
  15167. }
  15168. /***/
  15169. }
  15170. return BS_BLOCK_DONE;
  15171. }
  15172. /* ===========================================================================
  15173. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  15174. * one. Do not maintain a hash table. (It will be regenerated if this run of
  15175. * deflate switches away from Z_RLE.)
  15176. */
  15177. function deflate_rle(s, flush) {
  15178. var bflush; /* set if current block must be flushed */
  15179. var prev; /* byte at distance one to match */
  15180. var scan, strend; /* scan goes up to strend for length of run */
  15181. var _win = s.window;
  15182. for (;;) {
  15183. /* Make sure that we always have enough lookahead, except
  15184. * at the end of the input file. We need MAX_MATCH bytes
  15185. * for the longest run, plus one for the unrolled loop.
  15186. */
  15187. if (s.lookahead <= MAX_MATCH) {
  15188. fill_window(s);
  15189. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  15190. return BS_NEED_MORE;
  15191. }
  15192. if (s.lookahead === 0) { break; } /* flush the current block */
  15193. }
  15194. /* See how many times the previous byte repeats */
  15195. s.match_length = 0;
  15196. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  15197. scan = s.strstart - 1;
  15198. prev = _win[scan];
  15199. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  15200. strend = s.strstart + MAX_MATCH;
  15201. do {
  15202. /*jshint noempty:false*/
  15203. } while (prev === _win[++scan] && prev === _win[++scan] &&
  15204. prev === _win[++scan] && prev === _win[++scan] &&
  15205. prev === _win[++scan] && prev === _win[++scan] &&
  15206. prev === _win[++scan] && prev === _win[++scan] &&
  15207. scan < strend);
  15208. s.match_length = MAX_MATCH - (strend - scan);
  15209. if (s.match_length > s.lookahead) {
  15210. s.match_length = s.lookahead;
  15211. }
  15212. }
  15213. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  15214. }
  15215. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  15216. if (s.match_length >= MIN_MATCH) {
  15217. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  15218. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  15219. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  15220. s.lookahead -= s.match_length;
  15221. s.strstart += s.match_length;
  15222. s.match_length = 0;
  15223. } else {
  15224. /* No match, output a literal byte */
  15225. //Tracevv((stderr,"%c", s->window[s->strstart]));
  15226. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  15227. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  15228. s.lookahead--;
  15229. s.strstart++;
  15230. }
  15231. if (bflush) {
  15232. /*** FLUSH_BLOCK(s, 0); ***/
  15233. flush_block_only(s, false);
  15234. if (s.strm.avail_out === 0) {
  15235. return BS_NEED_MORE;
  15236. }
  15237. /***/
  15238. }
  15239. }
  15240. s.insert = 0;
  15241. if (flush === Z_FINISH) {
  15242. /*** FLUSH_BLOCK(s, 1); ***/
  15243. flush_block_only(s, true);
  15244. if (s.strm.avail_out === 0) {
  15245. return BS_FINISH_STARTED;
  15246. }
  15247. /***/
  15248. return BS_FINISH_DONE;
  15249. }
  15250. if (s.last_lit) {
  15251. /*** FLUSH_BLOCK(s, 0); ***/
  15252. flush_block_only(s, false);
  15253. if (s.strm.avail_out === 0) {
  15254. return BS_NEED_MORE;
  15255. }
  15256. /***/
  15257. }
  15258. return BS_BLOCK_DONE;
  15259. }
  15260. /* ===========================================================================
  15261. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  15262. * (It will be regenerated if this run of deflate switches away from Huffman.)
  15263. */
  15264. function deflate_huff(s, flush) {
  15265. var bflush; /* set if current block must be flushed */
  15266. for (;;) {
  15267. /* Make sure that we have a literal to write. */
  15268. if (s.lookahead === 0) {
  15269. fill_window(s);
  15270. if (s.lookahead === 0) {
  15271. if (flush === Z_NO_FLUSH) {
  15272. return BS_NEED_MORE;
  15273. }
  15274. break; /* flush the current block */
  15275. }
  15276. }
  15277. /* Output a literal byte */
  15278. s.match_length = 0;
  15279. //Tracevv((stderr,"%c", s->window[s->strstart]));
  15280. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  15281. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  15282. s.lookahead--;
  15283. s.strstart++;
  15284. if (bflush) {
  15285. /*** FLUSH_BLOCK(s, 0); ***/
  15286. flush_block_only(s, false);
  15287. if (s.strm.avail_out === 0) {
  15288. return BS_NEED_MORE;
  15289. }
  15290. /***/
  15291. }
  15292. }
  15293. s.insert = 0;
  15294. if (flush === Z_FINISH) {
  15295. /*** FLUSH_BLOCK(s, 1); ***/
  15296. flush_block_only(s, true);
  15297. if (s.strm.avail_out === 0) {
  15298. return BS_FINISH_STARTED;
  15299. }
  15300. /***/
  15301. return BS_FINISH_DONE;
  15302. }
  15303. if (s.last_lit) {
  15304. /*** FLUSH_BLOCK(s, 0); ***/
  15305. flush_block_only(s, false);
  15306. if (s.strm.avail_out === 0) {
  15307. return BS_NEED_MORE;
  15308. }
  15309. /***/
  15310. }
  15311. return BS_BLOCK_DONE;
  15312. }
  15313. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  15314. * the desired pack level (0..9). The values given below have been tuned to
  15315. * exclude worst case performance for pathological files. Better values may be
  15316. * found for specific files.
  15317. */
  15318. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  15319. this.good_length = good_length;
  15320. this.max_lazy = max_lazy;
  15321. this.nice_length = nice_length;
  15322. this.max_chain = max_chain;
  15323. this.func = func;
  15324. };
  15325. var configuration_table;
  15326. configuration_table = [
  15327. /* good lazy nice chain */
  15328. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  15329. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  15330. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  15331. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  15332. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  15333. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  15334. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  15335. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  15336. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  15337. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  15338. ];
  15339. /* ===========================================================================
  15340. * Initialize the "longest match" routines for a new zlib stream
  15341. */
  15342. function lm_init(s) {
  15343. s.window_size = 2 * s.w_size;
  15344. /*** CLEAR_HASH(s); ***/
  15345. zero(s.head); // Fill with NIL (= 0);
  15346. /* Set the default configuration parameters:
  15347. */
  15348. s.max_lazy_match = configuration_table[s.level].max_lazy;
  15349. s.good_match = configuration_table[s.level].good_length;
  15350. s.nice_match = configuration_table[s.level].nice_length;
  15351. s.max_chain_length = configuration_table[s.level].max_chain;
  15352. s.strstart = 0;
  15353. s.block_start = 0;
  15354. s.lookahead = 0;
  15355. s.insert = 0;
  15356. s.match_length = s.prev_length = MIN_MATCH - 1;
  15357. s.match_available = 0;
  15358. s.ins_h = 0;
  15359. }
  15360. function DeflateState() {
  15361. this.strm = null; /* pointer back to this zlib stream */
  15362. this.status = 0; /* as the name implies */
  15363. this.pending_buf = null; /* output still pending */
  15364. this.pending_buf_size = 0; /* size of pending_buf */
  15365. this.pending_out = 0; /* next pending byte to output to the stream */
  15366. this.pending = 0; /* nb of bytes in the pending buffer */
  15367. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  15368. this.gzhead = null; /* gzip header information to write */
  15369. this.gzindex = 0; /* where in extra, name, or comment */
  15370. this.method = Z_DEFLATED; /* can only be DEFLATED */
  15371. this.last_flush = -1; /* value of flush param for previous deflate call */
  15372. this.w_size = 0; /* LZ77 window size (32K by default) */
  15373. this.w_bits = 0; /* log2(w_size) (8..16) */
  15374. this.w_mask = 0; /* w_size - 1 */
  15375. this.window = null;
  15376. /* Sliding window. Input bytes are read into the second half of the window,
  15377. * and move to the first half later to keep a dictionary of at least wSize
  15378. * bytes. With this organization, matches are limited to a distance of
  15379. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  15380. * performed with a length multiple of the block size.
  15381. */
  15382. this.window_size = 0;
  15383. /* Actual size of window: 2*wSize, except when the user input buffer
  15384. * is directly used as sliding window.
  15385. */
  15386. this.prev = null;
  15387. /* Link to older string with same hash index. To limit the size of this
  15388. * array to 64K, this link is maintained only for the last 32K strings.
  15389. * An index in this array is thus a window index modulo 32K.
  15390. */
  15391. this.head = null; /* Heads of the hash chains or NIL. */
  15392. this.ins_h = 0; /* hash index of string to be inserted */
  15393. this.hash_size = 0; /* number of elements in hash table */
  15394. this.hash_bits = 0; /* log2(hash_size) */
  15395. this.hash_mask = 0; /* hash_size-1 */
  15396. this.hash_shift = 0;
  15397. /* Number of bits by which ins_h must be shifted at each input
  15398. * step. It must be such that after MIN_MATCH steps, the oldest
  15399. * byte no longer takes part in the hash key, that is:
  15400. * hash_shift * MIN_MATCH >= hash_bits
  15401. */
  15402. this.block_start = 0;
  15403. /* Window position at the beginning of the current output block. Gets
  15404. * negative when the window is moved backwards.
  15405. */
  15406. this.match_length = 0; /* length of best match */
  15407. this.prev_match = 0; /* previous match */
  15408. this.match_available = 0; /* set if previous match exists */
  15409. this.strstart = 0; /* start of string to insert */
  15410. this.match_start = 0; /* start of matching string */
  15411. this.lookahead = 0; /* number of valid bytes ahead in window */
  15412. this.prev_length = 0;
  15413. /* Length of the best match at previous step. Matches not greater than this
  15414. * are discarded. This is used in the lazy match evaluation.
  15415. */
  15416. this.max_chain_length = 0;
  15417. /* To speed up deflation, hash chains are never searched beyond this
  15418. * length. A higher limit improves compression ratio but degrades the
  15419. * speed.
  15420. */
  15421. this.max_lazy_match = 0;
  15422. /* Attempt to find a better match only when the current match is strictly
  15423. * smaller than this value. This mechanism is used only for compression
  15424. * levels >= 4.
  15425. */
  15426. // That's alias to max_lazy_match, don't use directly
  15427. //this.max_insert_length = 0;
  15428. /* Insert new strings in the hash table only if the match length is not
  15429. * greater than this length. This saves time but degrades compression.
  15430. * max_insert_length is used only for compression levels <= 3.
  15431. */
  15432. this.level = 0; /* compression level (1..9) */
  15433. this.strategy = 0; /* favor or force Huffman coding*/
  15434. this.good_match = 0;
  15435. /* Use a faster search when the previous match is longer than this */
  15436. this.nice_match = 0; /* Stop searching when current match exceeds this */
  15437. /* used by trees.c: */
  15438. /* Didn't use ct_data typedef below to suppress compiler warning */
  15439. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  15440. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  15441. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  15442. // Use flat array of DOUBLE size, with interleaved fata,
  15443. // because JS does not support effective
  15444. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  15445. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  15446. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  15447. zero(this.dyn_ltree);
  15448. zero(this.dyn_dtree);
  15449. zero(this.bl_tree);
  15450. this.l_desc = null; /* desc. for literal tree */
  15451. this.d_desc = null; /* desc. for distance tree */
  15452. this.bl_desc = null; /* desc. for bit length tree */
  15453. //ush bl_count[MAX_BITS+1];
  15454. this.bl_count = new utils.Buf16(MAX_BITS+1);
  15455. /* number of codes at each bit length for an optimal tree */
  15456. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  15457. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  15458. zero(this.heap);
  15459. this.heap_len = 0; /* number of elements in the heap */
  15460. this.heap_max = 0; /* element of largest frequency */
  15461. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  15462. * The same heap array is used to build all trees.
  15463. */
  15464. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  15465. zero(this.depth);
  15466. /* Depth of each subtree used as tie breaker for trees of equal frequency
  15467. */
  15468. this.l_buf = 0; /* buffer index for literals or lengths */
  15469. this.lit_bufsize = 0;
  15470. /* Size of match buffer for literals/lengths. There are 4 reasons for
  15471. * limiting lit_bufsize to 64K:
  15472. * - frequencies can be kept in 16 bit counters
  15473. * - if compression is not successful for the first block, all input
  15474. * data is still in the window so we can still emit a stored block even
  15475. * when input comes from standard input. (This can also be done for
  15476. * all blocks if lit_bufsize is not greater than 32K.)
  15477. * - if compression is not successful for a file smaller than 64K, we can
  15478. * even emit a stored file instead of a stored block (saving 5 bytes).
  15479. * This is applicable only for zip (not gzip or zlib).
  15480. * - creating new Huffman trees less frequently may not provide fast
  15481. * adaptation to changes in the input data statistics. (Take for
  15482. * example a binary file with poorly compressible code followed by
  15483. * a highly compressible string table.) Smaller buffer sizes give
  15484. * fast adaptation but have of course the overhead of transmitting
  15485. * trees more frequently.
  15486. * - I can't count above 4
  15487. */
  15488. this.last_lit = 0; /* running index in l_buf */
  15489. this.d_buf = 0;
  15490. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  15491. * the same number of elements. To use different lengths, an extra flag
  15492. * array would be necessary.
  15493. */
  15494. this.opt_len = 0; /* bit length of current block with optimal trees */
  15495. this.static_len = 0; /* bit length of current block with static trees */
  15496. this.matches = 0; /* number of string matches in current block */
  15497. this.insert = 0; /* bytes at end of window left to insert */
  15498. this.bi_buf = 0;
  15499. /* Output buffer. bits are inserted starting at the bottom (least
  15500. * significant bits).
  15501. */
  15502. this.bi_valid = 0;
  15503. /* Number of valid bits in bi_buf. All bits above the last valid bit
  15504. * are always zero.
  15505. */
  15506. // Used for window memory init. We safely ignore it for JS. That makes
  15507. // sense only for pointers and memory check tools.
  15508. //this.high_water = 0;
  15509. /* High water mark offset in window for initialized bytes -- bytes above
  15510. * this are set to zero in order to avoid memory check warnings when
  15511. * longest match routines access bytes past the input. This is then
  15512. * updated to the new high water mark.
  15513. */
  15514. }
  15515. function deflateResetKeep(strm) {
  15516. var s;
  15517. if (!strm || !strm.state) {
  15518. return err(strm, Z_STREAM_ERROR);
  15519. }
  15520. strm.total_in = strm.total_out = 0;
  15521. strm.data_type = Z_UNKNOWN;
  15522. s = strm.state;
  15523. s.pending = 0;
  15524. s.pending_out = 0;
  15525. if (s.wrap < 0) {
  15526. s.wrap = -s.wrap;
  15527. /* was made negative by deflate(..., Z_FINISH); */
  15528. }
  15529. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  15530. strm.adler = (s.wrap === 2) ?
  15531. 0 // crc32(0, Z_NULL, 0)
  15532. :
  15533. 1; // adler32(0, Z_NULL, 0)
  15534. s.last_flush = Z_NO_FLUSH;
  15535. trees._tr_init(s);
  15536. return Z_OK;
  15537. }
  15538. function deflateReset(strm) {
  15539. var ret = deflateResetKeep(strm);
  15540. if (ret === Z_OK) {
  15541. lm_init(strm.state);
  15542. }
  15543. return ret;
  15544. }
  15545. function deflateSetHeader(strm, head) {
  15546. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15547. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  15548. strm.state.gzhead = head;
  15549. return Z_OK;
  15550. }
  15551. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  15552. if (!strm) { // === Z_NULL
  15553. return Z_STREAM_ERROR;
  15554. }
  15555. var wrap = 1;
  15556. if (level === Z_DEFAULT_COMPRESSION) {
  15557. level = 6;
  15558. }
  15559. if (windowBits < 0) { /* suppress zlib wrapper */
  15560. wrap = 0;
  15561. windowBits = -windowBits;
  15562. }
  15563. else if (windowBits > 15) {
  15564. wrap = 2; /* write gzip wrapper instead */
  15565. windowBits -= 16;
  15566. }
  15567. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  15568. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  15569. strategy < 0 || strategy > Z_FIXED) {
  15570. return err(strm, Z_STREAM_ERROR);
  15571. }
  15572. if (windowBits === 8) {
  15573. windowBits = 9;
  15574. }
  15575. /* until 256-byte window bug fixed */
  15576. var s = new DeflateState();
  15577. strm.state = s;
  15578. s.strm = strm;
  15579. s.wrap = wrap;
  15580. s.gzhead = null;
  15581. s.w_bits = windowBits;
  15582. s.w_size = 1 << s.w_bits;
  15583. s.w_mask = s.w_size - 1;
  15584. s.hash_bits = memLevel + 7;
  15585. s.hash_size = 1 << s.hash_bits;
  15586. s.hash_mask = s.hash_size - 1;
  15587. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  15588. s.window = new utils.Buf8(s.w_size * 2);
  15589. s.head = new utils.Buf16(s.hash_size);
  15590. s.prev = new utils.Buf16(s.w_size);
  15591. // Don't need mem init magic for JS.
  15592. //s.high_water = 0; /* nothing written to s->window yet */
  15593. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  15594. s.pending_buf_size = s.lit_bufsize * 4;
  15595. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  15596. s.d_buf = s.lit_bufsize >> 1;
  15597. s.l_buf = (1 + 2) * s.lit_bufsize;
  15598. s.level = level;
  15599. s.strategy = strategy;
  15600. s.method = method;
  15601. return deflateReset(strm);
  15602. }
  15603. function deflateInit(strm, level) {
  15604. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  15605. }
  15606. function deflate(strm, flush) {
  15607. var old_flush, s;
  15608. var beg, val; // for gzip header write only
  15609. if (!strm || !strm.state ||
  15610. flush > Z_BLOCK || flush < 0) {
  15611. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  15612. }
  15613. s = strm.state;
  15614. if (!strm.output ||
  15615. (!strm.input && strm.avail_in !== 0) ||
  15616. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  15617. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  15618. }
  15619. s.strm = strm; /* just in case */
  15620. old_flush = s.last_flush;
  15621. s.last_flush = flush;
  15622. /* Write the header */
  15623. if (s.status === INIT_STATE) {
  15624. if (s.wrap === 2) { // GZIP header
  15625. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  15626. put_byte(s, 31);
  15627. put_byte(s, 139);
  15628. put_byte(s, 8);
  15629. if (!s.gzhead) { // s->gzhead == Z_NULL
  15630. put_byte(s, 0);
  15631. put_byte(s, 0);
  15632. put_byte(s, 0);
  15633. put_byte(s, 0);
  15634. put_byte(s, 0);
  15635. put_byte(s, s.level === 9 ? 2 :
  15636. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  15637. 4 : 0));
  15638. put_byte(s, OS_CODE);
  15639. s.status = BUSY_STATE;
  15640. }
  15641. else {
  15642. put_byte(s, (s.gzhead.text ? 1 : 0) +
  15643. (s.gzhead.hcrc ? 2 : 0) +
  15644. (!s.gzhead.extra ? 0 : 4) +
  15645. (!s.gzhead.name ? 0 : 8) +
  15646. (!s.gzhead.comment ? 0 : 16)
  15647. );
  15648. put_byte(s, s.gzhead.time & 0xff);
  15649. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  15650. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  15651. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  15652. put_byte(s, s.level === 9 ? 2 :
  15653. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  15654. 4 : 0));
  15655. put_byte(s, s.gzhead.os & 0xff);
  15656. if (s.gzhead.extra && s.gzhead.extra.length) {
  15657. put_byte(s, s.gzhead.extra.length & 0xff);
  15658. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  15659. }
  15660. if (s.gzhead.hcrc) {
  15661. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  15662. }
  15663. s.gzindex = 0;
  15664. s.status = EXTRA_STATE;
  15665. }
  15666. }
  15667. else // DEFLATE header
  15668. {
  15669. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  15670. var level_flags = -1;
  15671. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  15672. level_flags = 0;
  15673. } else if (s.level < 6) {
  15674. level_flags = 1;
  15675. } else if (s.level === 6) {
  15676. level_flags = 2;
  15677. } else {
  15678. level_flags = 3;
  15679. }
  15680. header |= (level_flags << 6);
  15681. if (s.strstart !== 0) { header |= PRESET_DICT; }
  15682. header += 31 - (header % 31);
  15683. s.status = BUSY_STATE;
  15684. putShortMSB(s, header);
  15685. /* Save the adler32 of the preset dictionary: */
  15686. if (s.strstart !== 0) {
  15687. putShortMSB(s, strm.adler >>> 16);
  15688. putShortMSB(s, strm.adler & 0xffff);
  15689. }
  15690. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  15691. }
  15692. }
  15693. //#ifdef GZIP
  15694. if (s.status === EXTRA_STATE) {
  15695. if (s.gzhead.extra/* != Z_NULL*/) {
  15696. beg = s.pending; /* start of bytes to update crc */
  15697. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  15698. if (s.pending === s.pending_buf_size) {
  15699. if (s.gzhead.hcrc && s.pending > beg) {
  15700. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15701. }
  15702. flush_pending(strm);
  15703. beg = s.pending;
  15704. if (s.pending === s.pending_buf_size) {
  15705. break;
  15706. }
  15707. }
  15708. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  15709. s.gzindex++;
  15710. }
  15711. if (s.gzhead.hcrc && s.pending > beg) {
  15712. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15713. }
  15714. if (s.gzindex === s.gzhead.extra.length) {
  15715. s.gzindex = 0;
  15716. s.status = NAME_STATE;
  15717. }
  15718. }
  15719. else {
  15720. s.status = NAME_STATE;
  15721. }
  15722. }
  15723. if (s.status === NAME_STATE) {
  15724. if (s.gzhead.name/* != Z_NULL*/) {
  15725. beg = s.pending; /* start of bytes to update crc */
  15726. //int val;
  15727. do {
  15728. if (s.pending === s.pending_buf_size) {
  15729. if (s.gzhead.hcrc && s.pending > beg) {
  15730. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15731. }
  15732. flush_pending(strm);
  15733. beg = s.pending;
  15734. if (s.pending === s.pending_buf_size) {
  15735. val = 1;
  15736. break;
  15737. }
  15738. }
  15739. // JS specific: little magic to add zero terminator to end of string
  15740. if (s.gzindex < s.gzhead.name.length) {
  15741. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  15742. } else {
  15743. val = 0;
  15744. }
  15745. put_byte(s, val);
  15746. } while (val !== 0);
  15747. if (s.gzhead.hcrc && s.pending > beg) {
  15748. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15749. }
  15750. if (val === 0) {
  15751. s.gzindex = 0;
  15752. s.status = COMMENT_STATE;
  15753. }
  15754. }
  15755. else {
  15756. s.status = COMMENT_STATE;
  15757. }
  15758. }
  15759. if (s.status === COMMENT_STATE) {
  15760. if (s.gzhead.comment/* != Z_NULL*/) {
  15761. beg = s.pending; /* start of bytes to update crc */
  15762. //int val;
  15763. do {
  15764. if (s.pending === s.pending_buf_size) {
  15765. if (s.gzhead.hcrc && s.pending > beg) {
  15766. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15767. }
  15768. flush_pending(strm);
  15769. beg = s.pending;
  15770. if (s.pending === s.pending_buf_size) {
  15771. val = 1;
  15772. break;
  15773. }
  15774. }
  15775. // JS specific: little magic to add zero terminator to end of string
  15776. if (s.gzindex < s.gzhead.comment.length) {
  15777. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  15778. } else {
  15779. val = 0;
  15780. }
  15781. put_byte(s, val);
  15782. } while (val !== 0);
  15783. if (s.gzhead.hcrc && s.pending > beg) {
  15784. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15785. }
  15786. if (val === 0) {
  15787. s.status = HCRC_STATE;
  15788. }
  15789. }
  15790. else {
  15791. s.status = HCRC_STATE;
  15792. }
  15793. }
  15794. if (s.status === HCRC_STATE) {
  15795. if (s.gzhead.hcrc) {
  15796. if (s.pending + 2 > s.pending_buf_size) {
  15797. flush_pending(strm);
  15798. }
  15799. if (s.pending + 2 <= s.pending_buf_size) {
  15800. put_byte(s, strm.adler & 0xff);
  15801. put_byte(s, (strm.adler >> 8) & 0xff);
  15802. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  15803. s.status = BUSY_STATE;
  15804. }
  15805. }
  15806. else {
  15807. s.status = BUSY_STATE;
  15808. }
  15809. }
  15810. //#endif
  15811. /* Flush as much pending output as possible */
  15812. if (s.pending !== 0) {
  15813. flush_pending(strm);
  15814. if (strm.avail_out === 0) {
  15815. /* Since avail_out is 0, deflate will be called again with
  15816. * more output space, but possibly with both pending and
  15817. * avail_in equal to zero. There won't be anything to do,
  15818. * but this is not an error situation so make sure we
  15819. * return OK instead of BUF_ERROR at next call of deflate:
  15820. */
  15821. s.last_flush = -1;
  15822. return Z_OK;
  15823. }
  15824. /* Make sure there is something to do and avoid duplicate consecutive
  15825. * flushes. For repeated and useless calls with Z_FINISH, we keep
  15826. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  15827. */
  15828. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  15829. flush !== Z_FINISH) {
  15830. return err(strm, Z_BUF_ERROR);
  15831. }
  15832. /* User must not provide more input after the first FINISH: */
  15833. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  15834. return err(strm, Z_BUF_ERROR);
  15835. }
  15836. /* Start a new block or continue the current one.
  15837. */
  15838. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  15839. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  15840. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  15841. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  15842. configuration_table[s.level].func(s, flush));
  15843. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  15844. s.status = FINISH_STATE;
  15845. }
  15846. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  15847. if (strm.avail_out === 0) {
  15848. s.last_flush = -1;
  15849. /* avoid BUF_ERROR next call, see above */
  15850. }
  15851. return Z_OK;
  15852. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  15853. * of deflate should use the same flush parameter to make sure
  15854. * that the flush is complete. So we don't have to output an
  15855. * empty block here, this will be done at next call. This also
  15856. * ensures that for a very small output buffer, we emit at most
  15857. * one empty block.
  15858. */
  15859. }
  15860. if (bstate === BS_BLOCK_DONE) {
  15861. if (flush === Z_PARTIAL_FLUSH) {
  15862. trees._tr_align(s);
  15863. }
  15864. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  15865. trees._tr_stored_block(s, 0, 0, false);
  15866. /* For a full flush, this empty block will be recognized
  15867. * as a special marker by inflate_sync().
  15868. */
  15869. if (flush === Z_FULL_FLUSH) {
  15870. /*** CLEAR_HASH(s); ***/ /* forget history */
  15871. zero(s.head); // Fill with NIL (= 0);
  15872. if (s.lookahead === 0) {
  15873. s.strstart = 0;
  15874. s.block_start = 0;
  15875. s.insert = 0;
  15876. }
  15877. }
  15878. }
  15879. flush_pending(strm);
  15880. if (strm.avail_out === 0) {
  15881. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  15882. return Z_OK;
  15883. }
  15884. }
  15885. }
  15886. //Assert(strm->avail_out > 0, "bug2");
  15887. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  15888. if (flush !== Z_FINISH) { return Z_OK; }
  15889. if (s.wrap <= 0) { return Z_STREAM_END; }
  15890. /* Write the trailer */
  15891. if (s.wrap === 2) {
  15892. put_byte(s, strm.adler & 0xff);
  15893. put_byte(s, (strm.adler >> 8) & 0xff);
  15894. put_byte(s, (strm.adler >> 16) & 0xff);
  15895. put_byte(s, (strm.adler >> 24) & 0xff);
  15896. put_byte(s, strm.total_in & 0xff);
  15897. put_byte(s, (strm.total_in >> 8) & 0xff);
  15898. put_byte(s, (strm.total_in >> 16) & 0xff);
  15899. put_byte(s, (strm.total_in >> 24) & 0xff);
  15900. }
  15901. else
  15902. {
  15903. putShortMSB(s, strm.adler >>> 16);
  15904. putShortMSB(s, strm.adler & 0xffff);
  15905. }
  15906. flush_pending(strm);
  15907. /* If avail_out is zero, the application will call deflate again
  15908. * to flush the rest.
  15909. */
  15910. if (s.wrap > 0) { s.wrap = -s.wrap; }
  15911. /* write the trailer only once! */
  15912. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  15913. }
  15914. function deflateEnd(strm) {
  15915. var status;
  15916. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  15917. return Z_STREAM_ERROR;
  15918. }
  15919. status = strm.state.status;
  15920. if (status !== INIT_STATE &&
  15921. status !== EXTRA_STATE &&
  15922. status !== NAME_STATE &&
  15923. status !== COMMENT_STATE &&
  15924. status !== HCRC_STATE &&
  15925. status !== BUSY_STATE &&
  15926. status !== FINISH_STATE
  15927. ) {
  15928. return err(strm, Z_STREAM_ERROR);
  15929. }
  15930. strm.state = null;
  15931. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  15932. }
  15933. /* =========================================================================
  15934. * Copy the source state to the destination state
  15935. */
  15936. //function deflateCopy(dest, source) {
  15937. //
  15938. //}
  15939. exports.deflateInit = deflateInit;
  15940. exports.deflateInit2 = deflateInit2;
  15941. exports.deflateReset = deflateReset;
  15942. exports.deflateResetKeep = deflateResetKeep;
  15943. exports.deflateSetHeader = deflateSetHeader;
  15944. exports.deflate = deflate;
  15945. exports.deflateEnd = deflateEnd;
  15946. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  15947. /* Not implemented
  15948. exports.deflateBound = deflateBound;
  15949. exports.deflateCopy = deflateCopy;
  15950. exports.deflateSetDictionary = deflateSetDictionary;
  15951. exports.deflateParams = deflateParams;
  15952. exports.deflatePending = deflatePending;
  15953. exports.deflatePrime = deflatePrime;
  15954. exports.deflateTune = deflateTune;
  15955. */
  15956. },{"../utils/common":51,"./adler32":53,"./crc32":55,"./messages":61,"./trees":62}],57:[function(require,module,exports){
  15957. 'use strict';
  15958. function GZheader() {
  15959. /* true if compressed data believed to be text */
  15960. this.text = 0;
  15961. /* modification time */
  15962. this.time = 0;
  15963. /* extra flags (not used when writing a gzip file) */
  15964. this.xflags = 0;
  15965. /* operating system */
  15966. this.os = 0;
  15967. /* pointer to extra field or Z_NULL if none */
  15968. this.extra = null;
  15969. /* extra field length (valid if extra != Z_NULL) */
  15970. this.extra_len = 0; // Actually, we don't need it in JS,
  15971. // but leave for few code modifications
  15972. //
  15973. // Setup limits is not necessary because in js we should not preallocate memory
  15974. // for inflate use constant limit in 65536 bytes
  15975. //
  15976. /* space at extra (only when reading header) */
  15977. // this.extra_max = 0;
  15978. /* pointer to zero-terminated file name or Z_NULL */
  15979. this.name = '';
  15980. /* space at name (only when reading header) */
  15981. // this.name_max = 0;
  15982. /* pointer to zero-terminated comment or Z_NULL */
  15983. this.comment = '';
  15984. /* space at comment (only when reading header) */
  15985. // this.comm_max = 0;
  15986. /* true if there was or will be a header crc */
  15987. this.hcrc = 0;
  15988. /* true when done reading gzip header (not used when writing a gzip file) */
  15989. this.done = false;
  15990. }
  15991. module.exports = GZheader;
  15992. },{}],58:[function(require,module,exports){
  15993. 'use strict';
  15994. // See state defs from inflate.js
  15995. var BAD = 30; /* got a data error -- remain here until reset */
  15996. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  15997. /*
  15998. Decode literal, length, and distance codes and write out the resulting
  15999. literal and match bytes until either not enough input or output is
  16000. available, an end-of-block is encountered, or a data error is encountered.
  16001. When large enough input and output buffers are supplied to inflate(), for
  16002. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  16003. inflate execution time is spent in this routine.
  16004. Entry assumptions:
  16005. state.mode === LEN
  16006. strm.avail_in >= 6
  16007. strm.avail_out >= 258
  16008. start >= strm.avail_out
  16009. state.bits < 8
  16010. On return, state.mode is one of:
  16011. LEN -- ran out of enough output space or enough available input
  16012. TYPE -- reached end of block code, inflate() to interpret next block
  16013. BAD -- error in block data
  16014. Notes:
  16015. - The maximum input bits used by a length/distance pair is 15 bits for the
  16016. length code, 5 bits for the length extra, 15 bits for the distance code,
  16017. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  16018. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  16019. checking for available input while decoding.
  16020. - The maximum bytes that a single length/distance pair can output is 258
  16021. bytes, which is the maximum length that can be coded. inflate_fast()
  16022. requires strm.avail_out >= 258 for each loop to avoid checking for
  16023. output space.
  16024. */
  16025. module.exports = function inflate_fast(strm, start) {
  16026. var state;
  16027. var _in; /* local strm.input */
  16028. var last; /* have enough input while in < last */
  16029. var _out; /* local strm.output */
  16030. var beg; /* inflate()'s initial strm.output */
  16031. var end; /* while out < end, enough space available */
  16032. //#ifdef INFLATE_STRICT
  16033. var dmax; /* maximum distance from zlib header */
  16034. //#endif
  16035. var wsize; /* window size or zero if not using window */
  16036. var whave; /* valid bytes in the window */
  16037. var wnext; /* window write index */
  16038. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  16039. var s_window; /* allocated sliding window, if wsize != 0 */
  16040. var hold; /* local strm.hold */
  16041. var bits; /* local strm.bits */
  16042. var lcode; /* local strm.lencode */
  16043. var dcode; /* local strm.distcode */
  16044. var lmask; /* mask for first level of length codes */
  16045. var dmask; /* mask for first level of distance codes */
  16046. var here; /* retrieved table entry */
  16047. var op; /* code bits, operation, extra bits, or */
  16048. /* window position, window bytes to copy */
  16049. var len; /* match length, unused bytes */
  16050. var dist; /* match distance */
  16051. var from; /* where to copy match from */
  16052. var from_source;
  16053. var input, output; // JS specific, because we have no pointers
  16054. /* copy state to local variables */
  16055. state = strm.state;
  16056. //here = state.here;
  16057. _in = strm.next_in;
  16058. input = strm.input;
  16059. last = _in + (strm.avail_in - 5);
  16060. _out = strm.next_out;
  16061. output = strm.output;
  16062. beg = _out - (start - strm.avail_out);
  16063. end = _out + (strm.avail_out - 257);
  16064. //#ifdef INFLATE_STRICT
  16065. dmax = state.dmax;
  16066. //#endif
  16067. wsize = state.wsize;
  16068. whave = state.whave;
  16069. wnext = state.wnext;
  16070. s_window = state.window;
  16071. hold = state.hold;
  16072. bits = state.bits;
  16073. lcode = state.lencode;
  16074. dcode = state.distcode;
  16075. lmask = (1 << state.lenbits) - 1;
  16076. dmask = (1 << state.distbits) - 1;
  16077. /* decode literals and length/distances until end-of-block or not enough
  16078. input data or output space */
  16079. top:
  16080. do {
  16081. if (bits < 15) {
  16082. hold += input[_in++] << bits;
  16083. bits += 8;
  16084. hold += input[_in++] << bits;
  16085. bits += 8;
  16086. }
  16087. here = lcode[hold & lmask];
  16088. dolen:
  16089. for (;;) { // Goto emulation
  16090. op = here >>> 24/*here.bits*/;
  16091. hold >>>= op;
  16092. bits -= op;
  16093. op = (here >>> 16) & 0xff/*here.op*/;
  16094. if (op === 0) { /* literal */
  16095. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  16096. // "inflate: literal '%c'\n" :
  16097. // "inflate: literal 0x%02x\n", here.val));
  16098. output[_out++] = here & 0xffff/*here.val*/;
  16099. }
  16100. else if (op & 16) { /* length base */
  16101. len = here & 0xffff/*here.val*/;
  16102. op &= 15; /* number of extra bits */
  16103. if (op) {
  16104. if (bits < op) {
  16105. hold += input[_in++] << bits;
  16106. bits += 8;
  16107. }
  16108. len += hold & ((1 << op) - 1);
  16109. hold >>>= op;
  16110. bits -= op;
  16111. }
  16112. //Tracevv((stderr, "inflate: length %u\n", len));
  16113. if (bits < 15) {
  16114. hold += input[_in++] << bits;
  16115. bits += 8;
  16116. hold += input[_in++] << bits;
  16117. bits += 8;
  16118. }
  16119. here = dcode[hold & dmask];
  16120. dodist:
  16121. for (;;) { // goto emulation
  16122. op = here >>> 24/*here.bits*/;
  16123. hold >>>= op;
  16124. bits -= op;
  16125. op = (here >>> 16) & 0xff/*here.op*/;
  16126. if (op & 16) { /* distance base */
  16127. dist = here & 0xffff/*here.val*/;
  16128. op &= 15; /* number of extra bits */
  16129. if (bits < op) {
  16130. hold += input[_in++] << bits;
  16131. bits += 8;
  16132. if (bits < op) {
  16133. hold += input[_in++] << bits;
  16134. bits += 8;
  16135. }
  16136. }
  16137. dist += hold & ((1 << op) - 1);
  16138. //#ifdef INFLATE_STRICT
  16139. if (dist > dmax) {
  16140. strm.msg = 'invalid distance too far back';
  16141. state.mode = BAD;
  16142. break top;
  16143. }
  16144. //#endif
  16145. hold >>>= op;
  16146. bits -= op;
  16147. //Tracevv((stderr, "inflate: distance %u\n", dist));
  16148. op = _out - beg; /* max distance in output */
  16149. if (dist > op) { /* see if copy from window */
  16150. op = dist - op; /* distance back in window */
  16151. if (op > whave) {
  16152. if (state.sane) {
  16153. strm.msg = 'invalid distance too far back';
  16154. state.mode = BAD;
  16155. break top;
  16156. }
  16157. // (!) This block is disabled in zlib defailts,
  16158. // don't enable it for binary compatibility
  16159. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  16160. // if (len <= op - whave) {
  16161. // do {
  16162. // output[_out++] = 0;
  16163. // } while (--len);
  16164. // continue top;
  16165. // }
  16166. // len -= op - whave;
  16167. // do {
  16168. // output[_out++] = 0;
  16169. // } while (--op > whave);
  16170. // if (op === 0) {
  16171. // from = _out - dist;
  16172. // do {
  16173. // output[_out++] = output[from++];
  16174. // } while (--len);
  16175. // continue top;
  16176. // }
  16177. //#endif
  16178. }
  16179. from = 0; // window index
  16180. from_source = s_window;
  16181. if (wnext === 0) { /* very common case */
  16182. from += wsize - op;
  16183. if (op < len) { /* some from window */
  16184. len -= op;
  16185. do {
  16186. output[_out++] = s_window[from++];
  16187. } while (--op);
  16188. from = _out - dist; /* rest from output */
  16189. from_source = output;
  16190. }
  16191. }
  16192. else if (wnext < op) { /* wrap around window */
  16193. from += wsize + wnext - op;
  16194. op -= wnext;
  16195. if (op < len) { /* some from end of window */
  16196. len -= op;
  16197. do {
  16198. output[_out++] = s_window[from++];
  16199. } while (--op);
  16200. from = 0;
  16201. if (wnext < len) { /* some from start of window */
  16202. op = wnext;
  16203. len -= op;
  16204. do {
  16205. output[_out++] = s_window[from++];
  16206. } while (--op);
  16207. from = _out - dist; /* rest from output */
  16208. from_source = output;
  16209. }
  16210. }
  16211. }
  16212. else { /* contiguous in window */
  16213. from += wnext - op;
  16214. if (op < len) { /* some from window */
  16215. len -= op;
  16216. do {
  16217. output[_out++] = s_window[from++];
  16218. } while (--op);
  16219. from = _out - dist; /* rest from output */
  16220. from_source = output;
  16221. }
  16222. }
  16223. while (len > 2) {
  16224. output[_out++] = from_source[from++];
  16225. output[_out++] = from_source[from++];
  16226. output[_out++] = from_source[from++];
  16227. len -= 3;
  16228. }
  16229. if (len) {
  16230. output[_out++] = from_source[from++];
  16231. if (len > 1) {
  16232. output[_out++] = from_source[from++];
  16233. }
  16234. }
  16235. }
  16236. else {
  16237. from = _out - dist; /* copy direct from output */
  16238. do { /* minimum length is three */
  16239. output[_out++] = output[from++];
  16240. output[_out++] = output[from++];
  16241. output[_out++] = output[from++];
  16242. len -= 3;
  16243. } while (len > 2);
  16244. if (len) {
  16245. output[_out++] = output[from++];
  16246. if (len > 1) {
  16247. output[_out++] = output[from++];
  16248. }
  16249. }
  16250. }
  16251. }
  16252. else if ((op & 64) === 0) { /* 2nd level distance code */
  16253. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  16254. continue dodist;
  16255. }
  16256. else {
  16257. strm.msg = 'invalid distance code';
  16258. state.mode = BAD;
  16259. break top;
  16260. }
  16261. break; // need to emulate goto via "continue"
  16262. }
  16263. }
  16264. else if ((op & 64) === 0) { /* 2nd level length code */
  16265. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  16266. continue dolen;
  16267. }
  16268. else if (op & 32) { /* end-of-block */
  16269. //Tracevv((stderr, "inflate: end of block\n"));
  16270. state.mode = TYPE;
  16271. break top;
  16272. }
  16273. else {
  16274. strm.msg = 'invalid literal/length code';
  16275. state.mode = BAD;
  16276. break top;
  16277. }
  16278. break; // need to emulate goto via "continue"
  16279. }
  16280. } while (_in < last && _out < end);
  16281. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  16282. len = bits >> 3;
  16283. _in -= len;
  16284. bits -= len << 3;
  16285. hold &= (1 << bits) - 1;
  16286. /* update state and return */
  16287. strm.next_in = _in;
  16288. strm.next_out = _out;
  16289. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  16290. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  16291. state.hold = hold;
  16292. state.bits = bits;
  16293. return;
  16294. };
  16295. },{}],59:[function(require,module,exports){
  16296. 'use strict';
  16297. var utils = require('../utils/common');
  16298. var adler32 = require('./adler32');
  16299. var crc32 = require('./crc32');
  16300. var inflate_fast = require('./inffast');
  16301. var inflate_table = require('./inftrees');
  16302. var CODES = 0;
  16303. var LENS = 1;
  16304. var DISTS = 2;
  16305. /* Public constants ==========================================================*/
  16306. /* ===========================================================================*/
  16307. /* Allowed flush values; see deflate() and inflate() below for details */
  16308. //var Z_NO_FLUSH = 0;
  16309. //var Z_PARTIAL_FLUSH = 1;
  16310. //var Z_SYNC_FLUSH = 2;
  16311. //var Z_FULL_FLUSH = 3;
  16312. var Z_FINISH = 4;
  16313. var Z_BLOCK = 5;
  16314. var Z_TREES = 6;
  16315. /* Return codes for the compression/decompression functions. Negative values
  16316. * are errors, positive values are used for special but normal events.
  16317. */
  16318. var Z_OK = 0;
  16319. var Z_STREAM_END = 1;
  16320. var Z_NEED_DICT = 2;
  16321. //var Z_ERRNO = -1;
  16322. var Z_STREAM_ERROR = -2;
  16323. var Z_DATA_ERROR = -3;
  16324. var Z_MEM_ERROR = -4;
  16325. var Z_BUF_ERROR = -5;
  16326. //var Z_VERSION_ERROR = -6;
  16327. /* The deflate compression method */
  16328. var Z_DEFLATED = 8;
  16329. /* STATES ====================================================================*/
  16330. /* ===========================================================================*/
  16331. var HEAD = 1; /* i: waiting for magic header */
  16332. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  16333. var TIME = 3; /* i: waiting for modification time (gzip) */
  16334. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  16335. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  16336. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  16337. var NAME = 7; /* i: waiting for end of file name (gzip) */
  16338. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  16339. var HCRC = 9; /* i: waiting for header crc (gzip) */
  16340. var DICTID = 10; /* i: waiting for dictionary check value */
  16341. var DICT = 11; /* waiting for inflateSetDictionary() call */
  16342. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  16343. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  16344. var STORED = 14; /* i: waiting for stored size (length and complement) */
  16345. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  16346. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  16347. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  16348. var LENLENS = 18; /* i: waiting for code length code lengths */
  16349. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  16350. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  16351. var LEN = 21; /* i: waiting for length/lit/eob code */
  16352. var LENEXT = 22; /* i: waiting for length extra bits */
  16353. var DIST = 23; /* i: waiting for distance code */
  16354. var DISTEXT = 24; /* i: waiting for distance extra bits */
  16355. var MATCH = 25; /* o: waiting for output space to copy string */
  16356. var LIT = 26; /* o: waiting for output space to write literal */
  16357. var CHECK = 27; /* i: waiting for 32-bit check value */
  16358. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  16359. var DONE = 29; /* finished check, done -- remain here until reset */
  16360. var BAD = 30; /* got a data error -- remain here until reset */
  16361. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  16362. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  16363. /* ===========================================================================*/
  16364. var ENOUGH_LENS = 852;
  16365. var ENOUGH_DISTS = 592;
  16366. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  16367. var MAX_WBITS = 15;
  16368. /* 32K LZ77 window */
  16369. var DEF_WBITS = MAX_WBITS;
  16370. function ZSWAP32(q) {
  16371. return (((q >>> 24) & 0xff) +
  16372. ((q >>> 8) & 0xff00) +
  16373. ((q & 0xff00) << 8) +
  16374. ((q & 0xff) << 24));
  16375. }
  16376. function InflateState() {
  16377. this.mode = 0; /* current inflate mode */
  16378. this.last = false; /* true if processing last block */
  16379. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  16380. this.havedict = false; /* true if dictionary provided */
  16381. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  16382. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  16383. this.check = 0; /* protected copy of check value */
  16384. this.total = 0; /* protected copy of output count */
  16385. // TODO: may be {}
  16386. this.head = null; /* where to save gzip header information */
  16387. /* sliding window */
  16388. this.wbits = 0; /* log base 2 of requested window size */
  16389. this.wsize = 0; /* window size or zero if not using window */
  16390. this.whave = 0; /* valid bytes in the window */
  16391. this.wnext = 0; /* window write index */
  16392. this.window = null; /* allocated sliding window, if needed */
  16393. /* bit accumulator */
  16394. this.hold = 0; /* input bit accumulator */
  16395. this.bits = 0; /* number of bits in "in" */
  16396. /* for string and stored block copying */
  16397. this.length = 0; /* literal or length of data to copy */
  16398. this.offset = 0; /* distance back to copy string from */
  16399. /* for table and code decoding */
  16400. this.extra = 0; /* extra bits needed */
  16401. /* fixed and dynamic code tables */
  16402. this.lencode = null; /* starting table for length/literal codes */
  16403. this.distcode = null; /* starting table for distance codes */
  16404. this.lenbits = 0; /* index bits for lencode */
  16405. this.distbits = 0; /* index bits for distcode */
  16406. /* dynamic table building */
  16407. this.ncode = 0; /* number of code length code lengths */
  16408. this.nlen = 0; /* number of length code lengths */
  16409. this.ndist = 0; /* number of distance code lengths */
  16410. this.have = 0; /* number of code lengths in lens[] */
  16411. this.next = null; /* next available space in codes[] */
  16412. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  16413. this.work = new utils.Buf16(288); /* work area for code table building */
  16414. /*
  16415. because we don't have pointers in js, we use lencode and distcode directly
  16416. as buffers so we don't need codes
  16417. */
  16418. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  16419. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  16420. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  16421. this.sane = 0; /* if false, allow invalid distance too far */
  16422. this.back = 0; /* bits back of last unprocessed length/lit */
  16423. this.was = 0; /* initial length of match */
  16424. }
  16425. function inflateResetKeep(strm) {
  16426. var state;
  16427. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16428. state = strm.state;
  16429. strm.total_in = strm.total_out = state.total = 0;
  16430. strm.msg = ''; /*Z_NULL*/
  16431. if (state.wrap) { /* to support ill-conceived Java test suite */
  16432. strm.adler = state.wrap & 1;
  16433. }
  16434. state.mode = HEAD;
  16435. state.last = 0;
  16436. state.havedict = 0;
  16437. state.dmax = 32768;
  16438. state.head = null/*Z_NULL*/;
  16439. state.hold = 0;
  16440. state.bits = 0;
  16441. //state.lencode = state.distcode = state.next = state.codes;
  16442. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  16443. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  16444. state.sane = 1;
  16445. state.back = -1;
  16446. //Tracev((stderr, "inflate: reset\n"));
  16447. return Z_OK;
  16448. }
  16449. function inflateReset(strm) {
  16450. var state;
  16451. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16452. state = strm.state;
  16453. state.wsize = 0;
  16454. state.whave = 0;
  16455. state.wnext = 0;
  16456. return inflateResetKeep(strm);
  16457. }
  16458. function inflateReset2(strm, windowBits) {
  16459. var wrap;
  16460. var state;
  16461. /* get the state */
  16462. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16463. state = strm.state;
  16464. /* extract wrap request from windowBits parameter */
  16465. if (windowBits < 0) {
  16466. wrap = 0;
  16467. windowBits = -windowBits;
  16468. }
  16469. else {
  16470. wrap = (windowBits >> 4) + 1;
  16471. if (windowBits < 48) {
  16472. windowBits &= 15;
  16473. }
  16474. }
  16475. /* set number of window bits, free window if different */
  16476. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  16477. return Z_STREAM_ERROR;
  16478. }
  16479. if (state.window !== null && state.wbits !== windowBits) {
  16480. state.window = null;
  16481. }
  16482. /* update state and reset the rest of it */
  16483. state.wrap = wrap;
  16484. state.wbits = windowBits;
  16485. return inflateReset(strm);
  16486. }
  16487. function inflateInit2(strm, windowBits) {
  16488. var ret;
  16489. var state;
  16490. if (!strm) { return Z_STREAM_ERROR; }
  16491. //strm.msg = Z_NULL; /* in case we return an error */
  16492. state = new InflateState();
  16493. //if (state === Z_NULL) return Z_MEM_ERROR;
  16494. //Tracev((stderr, "inflate: allocated\n"));
  16495. strm.state = state;
  16496. state.window = null/*Z_NULL*/;
  16497. ret = inflateReset2(strm, windowBits);
  16498. if (ret !== Z_OK) {
  16499. strm.state = null/*Z_NULL*/;
  16500. }
  16501. return ret;
  16502. }
  16503. function inflateInit(strm) {
  16504. return inflateInit2(strm, DEF_WBITS);
  16505. }
  16506. /*
  16507. Return state with length and distance decoding tables and index sizes set to
  16508. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  16509. If BUILDFIXED is defined, then instead this routine builds the tables the
  16510. first time it's called, and returns those tables the first time and
  16511. thereafter. This reduces the size of the code by about 2K bytes, in
  16512. exchange for a little execution time. However, BUILDFIXED should not be
  16513. used for threaded applications, since the rewriting of the tables and virgin
  16514. may not be thread-safe.
  16515. */
  16516. var virgin = true;
  16517. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  16518. function fixedtables(state) {
  16519. /* build fixed huffman tables if first call (may not be thread safe) */
  16520. if (virgin) {
  16521. var sym;
  16522. lenfix = new utils.Buf32(512);
  16523. distfix = new utils.Buf32(32);
  16524. /* literal/length table */
  16525. sym = 0;
  16526. while (sym < 144) { state.lens[sym++] = 8; }
  16527. while (sym < 256) { state.lens[sym++] = 9; }
  16528. while (sym < 280) { state.lens[sym++] = 7; }
  16529. while (sym < 288) { state.lens[sym++] = 8; }
  16530. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  16531. /* distance table */
  16532. sym = 0;
  16533. while (sym < 32) { state.lens[sym++] = 5; }
  16534. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  16535. /* do this just once */
  16536. virgin = false;
  16537. }
  16538. state.lencode = lenfix;
  16539. state.lenbits = 9;
  16540. state.distcode = distfix;
  16541. state.distbits = 5;
  16542. }
  16543. /*
  16544. Update the window with the last wsize (normally 32K) bytes written before
  16545. returning. If window does not exist yet, create it. This is only called
  16546. when a window is already in use, or when output has been written during this
  16547. inflate call, but the end of the deflate stream has not been reached yet.
  16548. It is also called to create a window for dictionary data when a dictionary
  16549. is loaded.
  16550. Providing output buffers larger than 32K to inflate() should provide a speed
  16551. advantage, since only the last 32K of output is copied to the sliding window
  16552. upon return from inflate(), and since all distances after the first 32K of
  16553. output will fall in the output data, making match copies simpler and faster.
  16554. The advantage may be dependent on the size of the processor's data caches.
  16555. */
  16556. function updatewindow(strm, src, end, copy) {
  16557. var dist;
  16558. var state = strm.state;
  16559. /* if it hasn't been done already, allocate space for the window */
  16560. if (state.window === null) {
  16561. state.wsize = 1 << state.wbits;
  16562. state.wnext = 0;
  16563. state.whave = 0;
  16564. state.window = new utils.Buf8(state.wsize);
  16565. }
  16566. /* copy state->wsize or less output bytes into the circular window */
  16567. if (copy >= state.wsize) {
  16568. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  16569. state.wnext = 0;
  16570. state.whave = state.wsize;
  16571. }
  16572. else {
  16573. dist = state.wsize - state.wnext;
  16574. if (dist > copy) {
  16575. dist = copy;
  16576. }
  16577. //zmemcpy(state->window + state->wnext, end - copy, dist);
  16578. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  16579. copy -= dist;
  16580. if (copy) {
  16581. //zmemcpy(state->window, end - copy, copy);
  16582. utils.arraySet(state.window,src, end - copy, copy, 0);
  16583. state.wnext = copy;
  16584. state.whave = state.wsize;
  16585. }
  16586. else {
  16587. state.wnext += dist;
  16588. if (state.wnext === state.wsize) { state.wnext = 0; }
  16589. if (state.whave < state.wsize) { state.whave += dist; }
  16590. }
  16591. }
  16592. return 0;
  16593. }
  16594. function inflate(strm, flush) {
  16595. var state;
  16596. var input, output; // input/output buffers
  16597. var next; /* next input INDEX */
  16598. var put; /* next output INDEX */
  16599. var have, left; /* available input and output */
  16600. var hold; /* bit buffer */
  16601. var bits; /* bits in bit buffer */
  16602. var _in, _out; /* save starting available input and output */
  16603. var copy; /* number of stored or match bytes to copy */
  16604. var from; /* where to copy match bytes from */
  16605. var from_source;
  16606. var here = 0; /* current decoding table entry */
  16607. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  16608. //var last; /* parent table entry */
  16609. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  16610. var len; /* length to copy for repeats, bits to drop */
  16611. var ret; /* return code */
  16612. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  16613. var opts;
  16614. var n; // temporary var for NEED_BITS
  16615. var order = /* permutation of code lengths */
  16616. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  16617. if (!strm || !strm.state || !strm.output ||
  16618. (!strm.input && strm.avail_in !== 0)) {
  16619. return Z_STREAM_ERROR;
  16620. }
  16621. state = strm.state;
  16622. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  16623. //--- LOAD() ---
  16624. put = strm.next_out;
  16625. output = strm.output;
  16626. left = strm.avail_out;
  16627. next = strm.next_in;
  16628. input = strm.input;
  16629. have = strm.avail_in;
  16630. hold = state.hold;
  16631. bits = state.bits;
  16632. //---
  16633. _in = have;
  16634. _out = left;
  16635. ret = Z_OK;
  16636. inf_leave: // goto emulation
  16637. for (;;) {
  16638. switch (state.mode) {
  16639. case HEAD:
  16640. if (state.wrap === 0) {
  16641. state.mode = TYPEDO;
  16642. break;
  16643. }
  16644. //=== NEEDBITS(16);
  16645. while (bits < 16) {
  16646. if (have === 0) { break inf_leave; }
  16647. have--;
  16648. hold += input[next++] << bits;
  16649. bits += 8;
  16650. }
  16651. //===//
  16652. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  16653. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  16654. //=== CRC2(state.check, hold);
  16655. hbuf[0] = hold & 0xff;
  16656. hbuf[1] = (hold >>> 8) & 0xff;
  16657. state.check = crc32(state.check, hbuf, 2, 0);
  16658. //===//
  16659. //=== INITBITS();
  16660. hold = 0;
  16661. bits = 0;
  16662. //===//
  16663. state.mode = FLAGS;
  16664. break;
  16665. }
  16666. state.flags = 0; /* expect zlib header */
  16667. if (state.head) {
  16668. state.head.done = false;
  16669. }
  16670. if (!(state.wrap & 1) || /* check if zlib header allowed */
  16671. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  16672. strm.msg = 'incorrect header check';
  16673. state.mode = BAD;
  16674. break;
  16675. }
  16676. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  16677. strm.msg = 'unknown compression method';
  16678. state.mode = BAD;
  16679. break;
  16680. }
  16681. //--- DROPBITS(4) ---//
  16682. hold >>>= 4;
  16683. bits -= 4;
  16684. //---//
  16685. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  16686. if (state.wbits === 0) {
  16687. state.wbits = len;
  16688. }
  16689. else if (len > state.wbits) {
  16690. strm.msg = 'invalid window size';
  16691. state.mode = BAD;
  16692. break;
  16693. }
  16694. state.dmax = 1 << len;
  16695. //Tracev((stderr, "inflate: zlib header ok\n"));
  16696. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  16697. state.mode = hold & 0x200 ? DICTID : TYPE;
  16698. //=== INITBITS();
  16699. hold = 0;
  16700. bits = 0;
  16701. //===//
  16702. break;
  16703. case FLAGS:
  16704. //=== NEEDBITS(16); */
  16705. while (bits < 16) {
  16706. if (have === 0) { break inf_leave; }
  16707. have--;
  16708. hold += input[next++] << bits;
  16709. bits += 8;
  16710. }
  16711. //===//
  16712. state.flags = hold;
  16713. if ((state.flags & 0xff) !== Z_DEFLATED) {
  16714. strm.msg = 'unknown compression method';
  16715. state.mode = BAD;
  16716. break;
  16717. }
  16718. if (state.flags & 0xe000) {
  16719. strm.msg = 'unknown header flags set';
  16720. state.mode = BAD;
  16721. break;
  16722. }
  16723. if (state.head) {
  16724. state.head.text = ((hold >> 8) & 1);
  16725. }
  16726. if (state.flags & 0x0200) {
  16727. //=== CRC2(state.check, hold);
  16728. hbuf[0] = hold & 0xff;
  16729. hbuf[1] = (hold >>> 8) & 0xff;
  16730. state.check = crc32(state.check, hbuf, 2, 0);
  16731. //===//
  16732. }
  16733. //=== INITBITS();
  16734. hold = 0;
  16735. bits = 0;
  16736. //===//
  16737. state.mode = TIME;
  16738. /* falls through */
  16739. case TIME:
  16740. //=== NEEDBITS(32); */
  16741. while (bits < 32) {
  16742. if (have === 0) { break inf_leave; }
  16743. have--;
  16744. hold += input[next++] << bits;
  16745. bits += 8;
  16746. }
  16747. //===//
  16748. if (state.head) {
  16749. state.head.time = hold;
  16750. }
  16751. if (state.flags & 0x0200) {
  16752. //=== CRC4(state.check, hold)
  16753. hbuf[0] = hold & 0xff;
  16754. hbuf[1] = (hold >>> 8) & 0xff;
  16755. hbuf[2] = (hold >>> 16) & 0xff;
  16756. hbuf[3] = (hold >>> 24) & 0xff;
  16757. state.check = crc32(state.check, hbuf, 4, 0);
  16758. //===
  16759. }
  16760. //=== INITBITS();
  16761. hold = 0;
  16762. bits = 0;
  16763. //===//
  16764. state.mode = OS;
  16765. /* falls through */
  16766. case OS:
  16767. //=== NEEDBITS(16); */
  16768. while (bits < 16) {
  16769. if (have === 0) { break inf_leave; }
  16770. have--;
  16771. hold += input[next++] << bits;
  16772. bits += 8;
  16773. }
  16774. //===//
  16775. if (state.head) {
  16776. state.head.xflags = (hold & 0xff);
  16777. state.head.os = (hold >> 8);
  16778. }
  16779. if (state.flags & 0x0200) {
  16780. //=== CRC2(state.check, hold);
  16781. hbuf[0] = hold & 0xff;
  16782. hbuf[1] = (hold >>> 8) & 0xff;
  16783. state.check = crc32(state.check, hbuf, 2, 0);
  16784. //===//
  16785. }
  16786. //=== INITBITS();
  16787. hold = 0;
  16788. bits = 0;
  16789. //===//
  16790. state.mode = EXLEN;
  16791. /* falls through */
  16792. case EXLEN:
  16793. if (state.flags & 0x0400) {
  16794. //=== NEEDBITS(16); */
  16795. while (bits < 16) {
  16796. if (have === 0) { break inf_leave; }
  16797. have--;
  16798. hold += input[next++] << bits;
  16799. bits += 8;
  16800. }
  16801. //===//
  16802. state.length = hold;
  16803. if (state.head) {
  16804. state.head.extra_len = hold;
  16805. }
  16806. if (state.flags & 0x0200) {
  16807. //=== CRC2(state.check, hold);
  16808. hbuf[0] = hold & 0xff;
  16809. hbuf[1] = (hold >>> 8) & 0xff;
  16810. state.check = crc32(state.check, hbuf, 2, 0);
  16811. //===//
  16812. }
  16813. //=== INITBITS();
  16814. hold = 0;
  16815. bits = 0;
  16816. //===//
  16817. }
  16818. else if (state.head) {
  16819. state.head.extra = null/*Z_NULL*/;
  16820. }
  16821. state.mode = EXTRA;
  16822. /* falls through */
  16823. case EXTRA:
  16824. if (state.flags & 0x0400) {
  16825. copy = state.length;
  16826. if (copy > have) { copy = have; }
  16827. if (copy) {
  16828. if (state.head) {
  16829. len = state.head.extra_len - state.length;
  16830. if (!state.head.extra) {
  16831. // Use untyped array for more conveniend processing later
  16832. state.head.extra = new Array(state.head.extra_len);
  16833. }
  16834. utils.arraySet(
  16835. state.head.extra,
  16836. input,
  16837. next,
  16838. // extra field is limited to 65536 bytes
  16839. // - no need for additional size check
  16840. copy,
  16841. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  16842. len
  16843. );
  16844. //zmemcpy(state.head.extra + len, next,
  16845. // len + copy > state.head.extra_max ?
  16846. // state.head.extra_max - len : copy);
  16847. }
  16848. if (state.flags & 0x0200) {
  16849. state.check = crc32(state.check, input, copy, next);
  16850. }
  16851. have -= copy;
  16852. next += copy;
  16853. state.length -= copy;
  16854. }
  16855. if (state.length) { break inf_leave; }
  16856. }
  16857. state.length = 0;
  16858. state.mode = NAME;
  16859. /* falls through */
  16860. case NAME:
  16861. if (state.flags & 0x0800) {
  16862. if (have === 0) { break inf_leave; }
  16863. copy = 0;
  16864. do {
  16865. // TODO: 2 or 1 bytes?
  16866. len = input[next + copy++];
  16867. /* use constant limit because in js we should not preallocate memory */
  16868. if (state.head && len &&
  16869. (state.length < 65536 /*state.head.name_max*/)) {
  16870. state.head.name += String.fromCharCode(len);
  16871. }
  16872. } while (len && copy < have);
  16873. if (state.flags & 0x0200) {
  16874. state.check = crc32(state.check, input, copy, next);
  16875. }
  16876. have -= copy;
  16877. next += copy;
  16878. if (len) { break inf_leave; }
  16879. }
  16880. else if (state.head) {
  16881. state.head.name = null;
  16882. }
  16883. state.length = 0;
  16884. state.mode = COMMENT;
  16885. /* falls through */
  16886. case COMMENT:
  16887. if (state.flags & 0x1000) {
  16888. if (have === 0) { break inf_leave; }
  16889. copy = 0;
  16890. do {
  16891. len = input[next + copy++];
  16892. /* use constant limit because in js we should not preallocate memory */
  16893. if (state.head && len &&
  16894. (state.length < 65536 /*state.head.comm_max*/)) {
  16895. state.head.comment += String.fromCharCode(len);
  16896. }
  16897. } while (len && copy < have);
  16898. if (state.flags & 0x0200) {
  16899. state.check = crc32(state.check, input, copy, next);
  16900. }
  16901. have -= copy;
  16902. next += copy;
  16903. if (len) { break inf_leave; }
  16904. }
  16905. else if (state.head) {
  16906. state.head.comment = null;
  16907. }
  16908. state.mode = HCRC;
  16909. /* falls through */
  16910. case HCRC:
  16911. if (state.flags & 0x0200) {
  16912. //=== NEEDBITS(16); */
  16913. while (bits < 16) {
  16914. if (have === 0) { break inf_leave; }
  16915. have--;
  16916. hold += input[next++] << bits;
  16917. bits += 8;
  16918. }
  16919. //===//
  16920. if (hold !== (state.check & 0xffff)) {
  16921. strm.msg = 'header crc mismatch';
  16922. state.mode = BAD;
  16923. break;
  16924. }
  16925. //=== INITBITS();
  16926. hold = 0;
  16927. bits = 0;
  16928. //===//
  16929. }
  16930. if (state.head) {
  16931. state.head.hcrc = ((state.flags >> 9) & 1);
  16932. state.head.done = true;
  16933. }
  16934. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  16935. state.mode = TYPE;
  16936. break;
  16937. case DICTID:
  16938. //=== NEEDBITS(32); */
  16939. while (bits < 32) {
  16940. if (have === 0) { break inf_leave; }
  16941. have--;
  16942. hold += input[next++] << bits;
  16943. bits += 8;
  16944. }
  16945. //===//
  16946. strm.adler = state.check = ZSWAP32(hold);
  16947. //=== INITBITS();
  16948. hold = 0;
  16949. bits = 0;
  16950. //===//
  16951. state.mode = DICT;
  16952. /* falls through */
  16953. case DICT:
  16954. if (state.havedict === 0) {
  16955. //--- RESTORE() ---
  16956. strm.next_out = put;
  16957. strm.avail_out = left;
  16958. strm.next_in = next;
  16959. strm.avail_in = have;
  16960. state.hold = hold;
  16961. state.bits = bits;
  16962. //---
  16963. return Z_NEED_DICT;
  16964. }
  16965. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  16966. state.mode = TYPE;
  16967. /* falls through */
  16968. case TYPE:
  16969. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  16970. /* falls through */
  16971. case TYPEDO:
  16972. if (state.last) {
  16973. //--- BYTEBITS() ---//
  16974. hold >>>= bits & 7;
  16975. bits -= bits & 7;
  16976. //---//
  16977. state.mode = CHECK;
  16978. break;
  16979. }
  16980. //=== NEEDBITS(3); */
  16981. while (bits < 3) {
  16982. if (have === 0) { break inf_leave; }
  16983. have--;
  16984. hold += input[next++] << bits;
  16985. bits += 8;
  16986. }
  16987. //===//
  16988. state.last = (hold & 0x01)/*BITS(1)*/;
  16989. //--- DROPBITS(1) ---//
  16990. hold >>>= 1;
  16991. bits -= 1;
  16992. //---//
  16993. switch ((hold & 0x03)/*BITS(2)*/) {
  16994. case 0: /* stored block */
  16995. //Tracev((stderr, "inflate: stored block%s\n",
  16996. // state.last ? " (last)" : ""));
  16997. state.mode = STORED;
  16998. break;
  16999. case 1: /* fixed block */
  17000. fixedtables(state);
  17001. //Tracev((stderr, "inflate: fixed codes block%s\n",
  17002. // state.last ? " (last)" : ""));
  17003. state.mode = LEN_; /* decode codes */
  17004. if (flush === Z_TREES) {
  17005. //--- DROPBITS(2) ---//
  17006. hold >>>= 2;
  17007. bits -= 2;
  17008. //---//
  17009. break inf_leave;
  17010. }
  17011. break;
  17012. case 2: /* dynamic block */
  17013. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  17014. // state.last ? " (last)" : ""));
  17015. state.mode = TABLE;
  17016. break;
  17017. case 3:
  17018. strm.msg = 'invalid block type';
  17019. state.mode = BAD;
  17020. }
  17021. //--- DROPBITS(2) ---//
  17022. hold >>>= 2;
  17023. bits -= 2;
  17024. //---//
  17025. break;
  17026. case STORED:
  17027. //--- BYTEBITS() ---// /* go to byte boundary */
  17028. hold >>>= bits & 7;
  17029. bits -= bits & 7;
  17030. //---//
  17031. //=== NEEDBITS(32); */
  17032. while (bits < 32) {
  17033. if (have === 0) { break inf_leave; }
  17034. have--;
  17035. hold += input[next++] << bits;
  17036. bits += 8;
  17037. }
  17038. //===//
  17039. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  17040. strm.msg = 'invalid stored block lengths';
  17041. state.mode = BAD;
  17042. break;
  17043. }
  17044. state.length = hold & 0xffff;
  17045. //Tracev((stderr, "inflate: stored length %u\n",
  17046. // state.length));
  17047. //=== INITBITS();
  17048. hold = 0;
  17049. bits = 0;
  17050. //===//
  17051. state.mode = COPY_;
  17052. if (flush === Z_TREES) { break inf_leave; }
  17053. /* falls through */
  17054. case COPY_:
  17055. state.mode = COPY;
  17056. /* falls through */
  17057. case COPY:
  17058. copy = state.length;
  17059. if (copy) {
  17060. if (copy > have) { copy = have; }
  17061. if (copy > left) { copy = left; }
  17062. if (copy === 0) { break inf_leave; }
  17063. //--- zmemcpy(put, next, copy); ---
  17064. utils.arraySet(output, input, next, copy, put);
  17065. //---//
  17066. have -= copy;
  17067. next += copy;
  17068. left -= copy;
  17069. put += copy;
  17070. state.length -= copy;
  17071. break;
  17072. }
  17073. //Tracev((stderr, "inflate: stored end\n"));
  17074. state.mode = TYPE;
  17075. break;
  17076. case TABLE:
  17077. //=== NEEDBITS(14); */
  17078. while (bits < 14) {
  17079. if (have === 0) { break inf_leave; }
  17080. have--;
  17081. hold += input[next++] << bits;
  17082. bits += 8;
  17083. }
  17084. //===//
  17085. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  17086. //--- DROPBITS(5) ---//
  17087. hold >>>= 5;
  17088. bits -= 5;
  17089. //---//
  17090. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  17091. //--- DROPBITS(5) ---//
  17092. hold >>>= 5;
  17093. bits -= 5;
  17094. //---//
  17095. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  17096. //--- DROPBITS(4) ---//
  17097. hold >>>= 4;
  17098. bits -= 4;
  17099. //---//
  17100. //#ifndef PKZIP_BUG_WORKAROUND
  17101. if (state.nlen > 286 || state.ndist > 30) {
  17102. strm.msg = 'too many length or distance symbols';
  17103. state.mode = BAD;
  17104. break;
  17105. }
  17106. //#endif
  17107. //Tracev((stderr, "inflate: table sizes ok\n"));
  17108. state.have = 0;
  17109. state.mode = LENLENS;
  17110. /* falls through */
  17111. case LENLENS:
  17112. while (state.have < state.ncode) {
  17113. //=== NEEDBITS(3);
  17114. while (bits < 3) {
  17115. if (have === 0) { break inf_leave; }
  17116. have--;
  17117. hold += input[next++] << bits;
  17118. bits += 8;
  17119. }
  17120. //===//
  17121. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  17122. //--- DROPBITS(3) ---//
  17123. hold >>>= 3;
  17124. bits -= 3;
  17125. //---//
  17126. }
  17127. while (state.have < 19) {
  17128. state.lens[order[state.have++]] = 0;
  17129. }
  17130. // We have separate tables & no pointers. 2 commented lines below not needed.
  17131. //state.next = state.codes;
  17132. //state.lencode = state.next;
  17133. // Switch to use dynamic table
  17134. state.lencode = state.lendyn;
  17135. state.lenbits = 7;
  17136. opts = {bits: state.lenbits};
  17137. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  17138. state.lenbits = opts.bits;
  17139. if (ret) {
  17140. strm.msg = 'invalid code lengths set';
  17141. state.mode = BAD;
  17142. break;
  17143. }
  17144. //Tracev((stderr, "inflate: code lengths ok\n"));
  17145. state.have = 0;
  17146. state.mode = CODELENS;
  17147. /* falls through */
  17148. case CODELENS:
  17149. while (state.have < state.nlen + state.ndist) {
  17150. for (;;) {
  17151. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  17152. here_bits = here >>> 24;
  17153. here_op = (here >>> 16) & 0xff;
  17154. here_val = here & 0xffff;
  17155. if ((here_bits) <= bits) { break; }
  17156. //--- PULLBYTE() ---//
  17157. if (have === 0) { break inf_leave; }
  17158. have--;
  17159. hold += input[next++] << bits;
  17160. bits += 8;
  17161. //---//
  17162. }
  17163. if (here_val < 16) {
  17164. //--- DROPBITS(here.bits) ---//
  17165. hold >>>= here_bits;
  17166. bits -= here_bits;
  17167. //---//
  17168. state.lens[state.have++] = here_val;
  17169. }
  17170. else {
  17171. if (here_val === 16) {
  17172. //=== NEEDBITS(here.bits + 2);
  17173. n = here_bits + 2;
  17174. while (bits < n) {
  17175. if (have === 0) { break inf_leave; }
  17176. have--;
  17177. hold += input[next++] << bits;
  17178. bits += 8;
  17179. }
  17180. //===//
  17181. //--- DROPBITS(here.bits) ---//
  17182. hold >>>= here_bits;
  17183. bits -= here_bits;
  17184. //---//
  17185. if (state.have === 0) {
  17186. strm.msg = 'invalid bit length repeat';
  17187. state.mode = BAD;
  17188. break;
  17189. }
  17190. len = state.lens[state.have - 1];
  17191. copy = 3 + (hold & 0x03);//BITS(2);
  17192. //--- DROPBITS(2) ---//
  17193. hold >>>= 2;
  17194. bits -= 2;
  17195. //---//
  17196. }
  17197. else if (here_val === 17) {
  17198. //=== NEEDBITS(here.bits + 3);
  17199. n = here_bits + 3;
  17200. while (bits < n) {
  17201. if (have === 0) { break inf_leave; }
  17202. have--;
  17203. hold += input[next++] << bits;
  17204. bits += 8;
  17205. }
  17206. //===//
  17207. //--- DROPBITS(here.bits) ---//
  17208. hold >>>= here_bits;
  17209. bits -= here_bits;
  17210. //---//
  17211. len = 0;
  17212. copy = 3 + (hold & 0x07);//BITS(3);
  17213. //--- DROPBITS(3) ---//
  17214. hold >>>= 3;
  17215. bits -= 3;
  17216. //---//
  17217. }
  17218. else {
  17219. //=== NEEDBITS(here.bits + 7);
  17220. n = here_bits + 7;
  17221. while (bits < n) {
  17222. if (have === 0) { break inf_leave; }
  17223. have--;
  17224. hold += input[next++] << bits;
  17225. bits += 8;
  17226. }
  17227. //===//
  17228. //--- DROPBITS(here.bits) ---//
  17229. hold >>>= here_bits;
  17230. bits -= here_bits;
  17231. //---//
  17232. len = 0;
  17233. copy = 11 + (hold & 0x7f);//BITS(7);
  17234. //--- DROPBITS(7) ---//
  17235. hold >>>= 7;
  17236. bits -= 7;
  17237. //---//
  17238. }
  17239. if (state.have + copy > state.nlen + state.ndist) {
  17240. strm.msg = 'invalid bit length repeat';
  17241. state.mode = BAD;
  17242. break;
  17243. }
  17244. while (copy--) {
  17245. state.lens[state.have++] = len;
  17246. }
  17247. }
  17248. }
  17249. /* handle error breaks in while */
  17250. if (state.mode === BAD) { break; }
  17251. /* check for end-of-block code (better have one) */
  17252. if (state.lens[256] === 0) {
  17253. strm.msg = 'invalid code -- missing end-of-block';
  17254. state.mode = BAD;
  17255. break;
  17256. }
  17257. /* build code tables -- note: do not change the lenbits or distbits
  17258. values here (9 and 6) without reading the comments in inftrees.h
  17259. concerning the ENOUGH constants, which depend on those values */
  17260. state.lenbits = 9;
  17261. opts = {bits: state.lenbits};
  17262. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  17263. // We have separate tables & no pointers. 2 commented lines below not needed.
  17264. // state.next_index = opts.table_index;
  17265. state.lenbits = opts.bits;
  17266. // state.lencode = state.next;
  17267. if (ret) {
  17268. strm.msg = 'invalid literal/lengths set';
  17269. state.mode = BAD;
  17270. break;
  17271. }
  17272. state.distbits = 6;
  17273. //state.distcode.copy(state.codes);
  17274. // Switch to use dynamic table
  17275. state.distcode = state.distdyn;
  17276. opts = {bits: state.distbits};
  17277. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  17278. // We have separate tables & no pointers. 2 commented lines below not needed.
  17279. // state.next_index = opts.table_index;
  17280. state.distbits = opts.bits;
  17281. // state.distcode = state.next;
  17282. if (ret) {
  17283. strm.msg = 'invalid distances set';
  17284. state.mode = BAD;
  17285. break;
  17286. }
  17287. //Tracev((stderr, 'inflate: codes ok\n'));
  17288. state.mode = LEN_;
  17289. if (flush === Z_TREES) { break inf_leave; }
  17290. /* falls through */
  17291. case LEN_:
  17292. state.mode = LEN;
  17293. /* falls through */
  17294. case LEN:
  17295. if (have >= 6 && left >= 258) {
  17296. //--- RESTORE() ---
  17297. strm.next_out = put;
  17298. strm.avail_out = left;
  17299. strm.next_in = next;
  17300. strm.avail_in = have;
  17301. state.hold = hold;
  17302. state.bits = bits;
  17303. //---
  17304. inflate_fast(strm, _out);
  17305. //--- LOAD() ---
  17306. put = strm.next_out;
  17307. output = strm.output;
  17308. left = strm.avail_out;
  17309. next = strm.next_in;
  17310. input = strm.input;
  17311. have = strm.avail_in;
  17312. hold = state.hold;
  17313. bits = state.bits;
  17314. //---
  17315. if (state.mode === TYPE) {
  17316. state.back = -1;
  17317. }
  17318. break;
  17319. }
  17320. state.back = 0;
  17321. for (;;) {
  17322. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  17323. here_bits = here >>> 24;
  17324. here_op = (here >>> 16) & 0xff;
  17325. here_val = here & 0xffff;
  17326. if (here_bits <= bits) { break; }
  17327. //--- PULLBYTE() ---//
  17328. if (have === 0) { break inf_leave; }
  17329. have--;
  17330. hold += input[next++] << bits;
  17331. bits += 8;
  17332. //---//
  17333. }
  17334. if (here_op && (here_op & 0xf0) === 0) {
  17335. last_bits = here_bits;
  17336. last_op = here_op;
  17337. last_val = here_val;
  17338. for (;;) {
  17339. here = state.lencode[last_val +
  17340. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  17341. here_bits = here >>> 24;
  17342. here_op = (here >>> 16) & 0xff;
  17343. here_val = here & 0xffff;
  17344. if ((last_bits + here_bits) <= bits) { break; }
  17345. //--- PULLBYTE() ---//
  17346. if (have === 0) { break inf_leave; }
  17347. have--;
  17348. hold += input[next++] << bits;
  17349. bits += 8;
  17350. //---//
  17351. }
  17352. //--- DROPBITS(last.bits) ---//
  17353. hold >>>= last_bits;
  17354. bits -= last_bits;
  17355. //---//
  17356. state.back += last_bits;
  17357. }
  17358. //--- DROPBITS(here.bits) ---//
  17359. hold >>>= here_bits;
  17360. bits -= here_bits;
  17361. //---//
  17362. state.back += here_bits;
  17363. state.length = here_val;
  17364. if (here_op === 0) {
  17365. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  17366. // "inflate: literal '%c'\n" :
  17367. // "inflate: literal 0x%02x\n", here.val));
  17368. state.mode = LIT;
  17369. break;
  17370. }
  17371. if (here_op & 32) {
  17372. //Tracevv((stderr, "inflate: end of block\n"));
  17373. state.back = -1;
  17374. state.mode = TYPE;
  17375. break;
  17376. }
  17377. if (here_op & 64) {
  17378. strm.msg = 'invalid literal/length code';
  17379. state.mode = BAD;
  17380. break;
  17381. }
  17382. state.extra = here_op & 15;
  17383. state.mode = LENEXT;
  17384. /* falls through */
  17385. case LENEXT:
  17386. if (state.extra) {
  17387. //=== NEEDBITS(state.extra);
  17388. n = state.extra;
  17389. while (bits < n) {
  17390. if (have === 0) { break inf_leave; }
  17391. have--;
  17392. hold += input[next++] << bits;
  17393. bits += 8;
  17394. }
  17395. //===//
  17396. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  17397. //--- DROPBITS(state.extra) ---//
  17398. hold >>>= state.extra;
  17399. bits -= state.extra;
  17400. //---//
  17401. state.back += state.extra;
  17402. }
  17403. //Tracevv((stderr, "inflate: length %u\n", state.length));
  17404. state.was = state.length;
  17405. state.mode = DIST;
  17406. /* falls through */
  17407. case DIST:
  17408. for (;;) {
  17409. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  17410. here_bits = here >>> 24;
  17411. here_op = (here >>> 16) & 0xff;
  17412. here_val = here & 0xffff;
  17413. if ((here_bits) <= bits) { break; }
  17414. //--- PULLBYTE() ---//
  17415. if (have === 0) { break inf_leave; }
  17416. have--;
  17417. hold += input[next++] << bits;
  17418. bits += 8;
  17419. //---//
  17420. }
  17421. if ((here_op & 0xf0) === 0) {
  17422. last_bits = here_bits;
  17423. last_op = here_op;
  17424. last_val = here_val;
  17425. for (;;) {
  17426. here = state.distcode[last_val +
  17427. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  17428. here_bits = here >>> 24;
  17429. here_op = (here >>> 16) & 0xff;
  17430. here_val = here & 0xffff;
  17431. if ((last_bits + here_bits) <= bits) { break; }
  17432. //--- PULLBYTE() ---//
  17433. if (have === 0) { break inf_leave; }
  17434. have--;
  17435. hold += input[next++] << bits;
  17436. bits += 8;
  17437. //---//
  17438. }
  17439. //--- DROPBITS(last.bits) ---//
  17440. hold >>>= last_bits;
  17441. bits -= last_bits;
  17442. //---//
  17443. state.back += last_bits;
  17444. }
  17445. //--- DROPBITS(here.bits) ---//
  17446. hold >>>= here_bits;
  17447. bits -= here_bits;
  17448. //---//
  17449. state.back += here_bits;
  17450. if (here_op & 64) {
  17451. strm.msg = 'invalid distance code';
  17452. state.mode = BAD;
  17453. break;
  17454. }
  17455. state.offset = here_val;
  17456. state.extra = (here_op) & 15;
  17457. state.mode = DISTEXT;
  17458. /* falls through */
  17459. case DISTEXT:
  17460. if (state.extra) {
  17461. //=== NEEDBITS(state.extra);
  17462. n = state.extra;
  17463. while (bits < n) {
  17464. if (have === 0) { break inf_leave; }
  17465. have--;
  17466. hold += input[next++] << bits;
  17467. bits += 8;
  17468. }
  17469. //===//
  17470. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  17471. //--- DROPBITS(state.extra) ---//
  17472. hold >>>= state.extra;
  17473. bits -= state.extra;
  17474. //---//
  17475. state.back += state.extra;
  17476. }
  17477. //#ifdef INFLATE_STRICT
  17478. if (state.offset > state.dmax) {
  17479. strm.msg = 'invalid distance too far back';
  17480. state.mode = BAD;
  17481. break;
  17482. }
  17483. //#endif
  17484. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  17485. state.mode = MATCH;
  17486. /* falls through */
  17487. case MATCH:
  17488. if (left === 0) { break inf_leave; }
  17489. copy = _out - left;
  17490. if (state.offset > copy) { /* copy from window */
  17491. copy = state.offset - copy;
  17492. if (copy > state.whave) {
  17493. if (state.sane) {
  17494. strm.msg = 'invalid distance too far back';
  17495. state.mode = BAD;
  17496. break;
  17497. }
  17498. // (!) This block is disabled in zlib defailts,
  17499. // don't enable it for binary compatibility
  17500. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  17501. // Trace((stderr, "inflate.c too far\n"));
  17502. // copy -= state.whave;
  17503. // if (copy > state.length) { copy = state.length; }
  17504. // if (copy > left) { copy = left; }
  17505. // left -= copy;
  17506. // state.length -= copy;
  17507. // do {
  17508. // output[put++] = 0;
  17509. // } while (--copy);
  17510. // if (state.length === 0) { state.mode = LEN; }
  17511. // break;
  17512. //#endif
  17513. }
  17514. if (copy > state.wnext) {
  17515. copy -= state.wnext;
  17516. from = state.wsize - copy;
  17517. }
  17518. else {
  17519. from = state.wnext - copy;
  17520. }
  17521. if (copy > state.length) { copy = state.length; }
  17522. from_source = state.window;
  17523. }
  17524. else { /* copy from output */
  17525. from_source = output;
  17526. from = put - state.offset;
  17527. copy = state.length;
  17528. }
  17529. if (copy > left) { copy = left; }
  17530. left -= copy;
  17531. state.length -= copy;
  17532. do {
  17533. output[put++] = from_source[from++];
  17534. } while (--copy);
  17535. if (state.length === 0) { state.mode = LEN; }
  17536. break;
  17537. case LIT:
  17538. if (left === 0) { break inf_leave; }
  17539. output[put++] = state.length;
  17540. left--;
  17541. state.mode = LEN;
  17542. break;
  17543. case CHECK:
  17544. if (state.wrap) {
  17545. //=== NEEDBITS(32);
  17546. while (bits < 32) {
  17547. if (have === 0) { break inf_leave; }
  17548. have--;
  17549. // Use '|' insdead of '+' to make sure that result is signed
  17550. hold |= input[next++] << bits;
  17551. bits += 8;
  17552. }
  17553. //===//
  17554. _out -= left;
  17555. strm.total_out += _out;
  17556. state.total += _out;
  17557. if (_out) {
  17558. strm.adler = state.check =
  17559. /*UPDATE(state.check, put - _out, _out);*/
  17560. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  17561. }
  17562. _out = left;
  17563. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  17564. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  17565. strm.msg = 'incorrect data check';
  17566. state.mode = BAD;
  17567. break;
  17568. }
  17569. //=== INITBITS();
  17570. hold = 0;
  17571. bits = 0;
  17572. //===//
  17573. //Tracev((stderr, "inflate: check matches trailer\n"));
  17574. }
  17575. state.mode = LENGTH;
  17576. /* falls through */
  17577. case LENGTH:
  17578. if (state.wrap && state.flags) {
  17579. //=== NEEDBITS(32);
  17580. while (bits < 32) {
  17581. if (have === 0) { break inf_leave; }
  17582. have--;
  17583. hold += input[next++] << bits;
  17584. bits += 8;
  17585. }
  17586. //===//
  17587. if (hold !== (state.total & 0xffffffff)) {
  17588. strm.msg = 'incorrect length check';
  17589. state.mode = BAD;
  17590. break;
  17591. }
  17592. //=== INITBITS();
  17593. hold = 0;
  17594. bits = 0;
  17595. //===//
  17596. //Tracev((stderr, "inflate: length matches trailer\n"));
  17597. }
  17598. state.mode = DONE;
  17599. /* falls through */
  17600. case DONE:
  17601. ret = Z_STREAM_END;
  17602. break inf_leave;
  17603. case BAD:
  17604. ret = Z_DATA_ERROR;
  17605. break inf_leave;
  17606. case MEM:
  17607. return Z_MEM_ERROR;
  17608. case SYNC:
  17609. /* falls through */
  17610. default:
  17611. return Z_STREAM_ERROR;
  17612. }
  17613. }
  17614. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  17615. /*
  17616. Return from inflate(), updating the total counts and the check value.
  17617. If there was no progress during the inflate() call, return a buffer
  17618. error. Call updatewindow() to create and/or update the window state.
  17619. Note: a memory error from inflate() is non-recoverable.
  17620. */
  17621. //--- RESTORE() ---
  17622. strm.next_out = put;
  17623. strm.avail_out = left;
  17624. strm.next_in = next;
  17625. strm.avail_in = have;
  17626. state.hold = hold;
  17627. state.bits = bits;
  17628. //---
  17629. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  17630. (state.mode < CHECK || flush !== Z_FINISH))) {
  17631. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  17632. state.mode = MEM;
  17633. return Z_MEM_ERROR;
  17634. }
  17635. }
  17636. _in -= strm.avail_in;
  17637. _out -= strm.avail_out;
  17638. strm.total_in += _in;
  17639. strm.total_out += _out;
  17640. state.total += _out;
  17641. if (state.wrap && _out) {
  17642. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  17643. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  17644. }
  17645. strm.data_type = state.bits + (state.last ? 64 : 0) +
  17646. (state.mode === TYPE ? 128 : 0) +
  17647. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  17648. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  17649. ret = Z_BUF_ERROR;
  17650. }
  17651. return ret;
  17652. }
  17653. function inflateEnd(strm) {
  17654. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  17655. return Z_STREAM_ERROR;
  17656. }
  17657. var state = strm.state;
  17658. if (state.window) {
  17659. state.window = null;
  17660. }
  17661. strm.state = null;
  17662. return Z_OK;
  17663. }
  17664. function inflateGetHeader(strm, head) {
  17665. var state;
  17666. /* check state */
  17667. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17668. state = strm.state;
  17669. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  17670. /* save header structure */
  17671. state.head = head;
  17672. head.done = false;
  17673. return Z_OK;
  17674. }
  17675. exports.inflateReset = inflateReset;
  17676. exports.inflateReset2 = inflateReset2;
  17677. exports.inflateResetKeep = inflateResetKeep;
  17678. exports.inflateInit = inflateInit;
  17679. exports.inflateInit2 = inflateInit2;
  17680. exports.inflate = inflate;
  17681. exports.inflateEnd = inflateEnd;
  17682. exports.inflateGetHeader = inflateGetHeader;
  17683. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  17684. /* Not implemented
  17685. exports.inflateCopy = inflateCopy;
  17686. exports.inflateGetDictionary = inflateGetDictionary;
  17687. exports.inflateMark = inflateMark;
  17688. exports.inflatePrime = inflatePrime;
  17689. exports.inflateSetDictionary = inflateSetDictionary;
  17690. exports.inflateSync = inflateSync;
  17691. exports.inflateSyncPoint = inflateSyncPoint;
  17692. exports.inflateUndermine = inflateUndermine;
  17693. */
  17694. },{"../utils/common":51,"./adler32":53,"./crc32":55,"./inffast":58,"./inftrees":60}],60:[function(require,module,exports){
  17695. 'use strict';
  17696. var utils = require('../utils/common');
  17697. var MAXBITS = 15;
  17698. var ENOUGH_LENS = 852;
  17699. var ENOUGH_DISTS = 592;
  17700. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  17701. var CODES = 0;
  17702. var LENS = 1;
  17703. var DISTS = 2;
  17704. var lbase = [ /* Length codes 257..285 base */
  17705. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  17706. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  17707. ];
  17708. var lext = [ /* Length codes 257..285 extra */
  17709. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  17710. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  17711. ];
  17712. var dbase = [ /* Distance codes 0..29 base */
  17713. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  17714. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  17715. 8193, 12289, 16385, 24577, 0, 0
  17716. ];
  17717. var dext = [ /* Distance codes 0..29 extra */
  17718. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  17719. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  17720. 28, 28, 29, 29, 64, 64
  17721. ];
  17722. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  17723. {
  17724. var bits = opts.bits;
  17725. //here = opts.here; /* table entry for duplication */
  17726. var len = 0; /* a code's length in bits */
  17727. var sym = 0; /* index of code symbols */
  17728. var min = 0, max = 0; /* minimum and maximum code lengths */
  17729. var root = 0; /* number of index bits for root table */
  17730. var curr = 0; /* number of index bits for current table */
  17731. var drop = 0; /* code bits to drop for sub-table */
  17732. var left = 0; /* number of prefix codes available */
  17733. var used = 0; /* code entries in table used */
  17734. var huff = 0; /* Huffman code */
  17735. var incr; /* for incrementing code, index */
  17736. var fill; /* index for replicating entries */
  17737. var low; /* low bits for current root entry */
  17738. var mask; /* mask for low root bits */
  17739. var next; /* next available space in table */
  17740. var base = null; /* base value table to use */
  17741. var base_index = 0;
  17742. // var shoextra; /* extra bits table to use */
  17743. var end; /* use base and extra for symbol > end */
  17744. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  17745. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  17746. var extra = null;
  17747. var extra_index = 0;
  17748. var here_bits, here_op, here_val;
  17749. /*
  17750. Process a set of code lengths to create a canonical Huffman code. The
  17751. code lengths are lens[0..codes-1]. Each length corresponds to the
  17752. symbols 0..codes-1. The Huffman code is generated by first sorting the
  17753. symbols by length from short to long, and retaining the symbol order
  17754. for codes with equal lengths. Then the code starts with all zero bits
  17755. for the first code of the shortest length, and the codes are integer
  17756. increments for the same length, and zeros are appended as the length
  17757. increases. For the deflate format, these bits are stored backwards
  17758. from their more natural integer increment ordering, and so when the
  17759. decoding tables are built in the large loop below, the integer codes
  17760. are incremented backwards.
  17761. This routine assumes, but does not check, that all of the entries in
  17762. lens[] are in the range 0..MAXBITS. The caller must assure this.
  17763. 1..MAXBITS is interpreted as that code length. zero means that that
  17764. symbol does not occur in this code.
  17765. The codes are sorted by computing a count of codes for each length,
  17766. creating from that a table of starting indices for each length in the
  17767. sorted table, and then entering the symbols in order in the sorted
  17768. table. The sorted table is work[], with that space being provided by
  17769. the caller.
  17770. The length counts are used for other purposes as well, i.e. finding
  17771. the minimum and maximum length codes, determining if there are any
  17772. codes at all, checking for a valid set of lengths, and looking ahead
  17773. at length counts to determine sub-table sizes when building the
  17774. decoding tables.
  17775. */
  17776. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  17777. for (len = 0; len <= MAXBITS; len++) {
  17778. count[len] = 0;
  17779. }
  17780. for (sym = 0; sym < codes; sym++) {
  17781. count[lens[lens_index + sym]]++;
  17782. }
  17783. /* bound code lengths, force root to be within code lengths */
  17784. root = bits;
  17785. for (max = MAXBITS; max >= 1; max--) {
  17786. if (count[max] !== 0) { break; }
  17787. }
  17788. if (root > max) {
  17789. root = max;
  17790. }
  17791. if (max === 0) { /* no symbols to code at all */
  17792. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  17793. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  17794. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  17795. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  17796. //table.op[opts.table_index] = 64;
  17797. //table.bits[opts.table_index] = 1;
  17798. //table.val[opts.table_index++] = 0;
  17799. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  17800. opts.bits = 1;
  17801. return 0; /* no symbols, but wait for decoding to report error */
  17802. }
  17803. for (min = 1; min < max; min++) {
  17804. if (count[min] !== 0) { break; }
  17805. }
  17806. if (root < min) {
  17807. root = min;
  17808. }
  17809. /* check for an over-subscribed or incomplete set of lengths */
  17810. left = 1;
  17811. for (len = 1; len <= MAXBITS; len++) {
  17812. left <<= 1;
  17813. left -= count[len];
  17814. if (left < 0) {
  17815. return -1;
  17816. } /* over-subscribed */
  17817. }
  17818. if (left > 0 && (type === CODES || max !== 1)) {
  17819. return -1; /* incomplete set */
  17820. }
  17821. /* generate offsets into symbol table for each length for sorting */
  17822. offs[1] = 0;
  17823. for (len = 1; len < MAXBITS; len++) {
  17824. offs[len + 1] = offs[len] + count[len];
  17825. }
  17826. /* sort symbols by length, by symbol order within each length */
  17827. for (sym = 0; sym < codes; sym++) {
  17828. if (lens[lens_index + sym] !== 0) {
  17829. work[offs[lens[lens_index + sym]]++] = sym;
  17830. }
  17831. }
  17832. /*
  17833. Create and fill in decoding tables. In this loop, the table being
  17834. filled is at next and has curr index bits. The code being used is huff
  17835. with length len. That code is converted to an index by dropping drop
  17836. bits off of the bottom. For codes where len is less than drop + curr,
  17837. those top drop + curr - len bits are incremented through all values to
  17838. fill the table with replicated entries.
  17839. root is the number of index bits for the root table. When len exceeds
  17840. root, sub-tables are created pointed to by the root entry with an index
  17841. of the low root bits of huff. This is saved in low to check for when a
  17842. new sub-table should be started. drop is zero when the root table is
  17843. being filled, and drop is root when sub-tables are being filled.
  17844. When a new sub-table is needed, it is necessary to look ahead in the
  17845. code lengths to determine what size sub-table is needed. The length
  17846. counts are used for this, and so count[] is decremented as codes are
  17847. entered in the tables.
  17848. used keeps track of how many table entries have been allocated from the
  17849. provided *table space. It is checked for LENS and DIST tables against
  17850. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  17851. the initial root table size constants. See the comments in inftrees.h
  17852. for more information.
  17853. sym increments through all symbols, and the loop terminates when
  17854. all codes of length max, i.e. all codes, have been processed. This
  17855. routine permits incomplete codes, so another loop after this one fills
  17856. in the rest of the decoding tables with invalid code markers.
  17857. */
  17858. /* set up for code type */
  17859. // poor man optimization - use if-else instead of switch,
  17860. // to avoid deopts in old v8
  17861. if (type === CODES) {
  17862. base = extra = work; /* dummy value--not used */
  17863. end = 19;
  17864. } else if (type === LENS) {
  17865. base = lbase;
  17866. base_index -= 257;
  17867. extra = lext;
  17868. extra_index -= 257;
  17869. end = 256;
  17870. } else { /* DISTS */
  17871. base = dbase;
  17872. extra = dext;
  17873. end = -1;
  17874. }
  17875. /* initialize opts for loop */
  17876. huff = 0; /* starting code */
  17877. sym = 0; /* starting code symbol */
  17878. len = min; /* starting code length */
  17879. next = table_index; /* current table to fill in */
  17880. curr = root; /* current table index bits */
  17881. drop = 0; /* current bits to drop from code for index */
  17882. low = -1; /* trigger new sub-table when len > root */
  17883. used = 1 << root; /* use root table entries */
  17884. mask = used - 1; /* mask for comparing low */
  17885. /* check available table space */
  17886. if ((type === LENS && used > ENOUGH_LENS) ||
  17887. (type === DISTS && used > ENOUGH_DISTS)) {
  17888. return 1;
  17889. }
  17890. var i=0;
  17891. /* process all codes and make table entries */
  17892. for (;;) {
  17893. i++;
  17894. /* create table entry */
  17895. here_bits = len - drop;
  17896. if (work[sym] < end) {
  17897. here_op = 0;
  17898. here_val = work[sym];
  17899. }
  17900. else if (work[sym] > end) {
  17901. here_op = extra[extra_index + work[sym]];
  17902. here_val = base[base_index + work[sym]];
  17903. }
  17904. else {
  17905. here_op = 32 + 64; /* end of block */
  17906. here_val = 0;
  17907. }
  17908. /* replicate for those indices with low len bits equal to huff */
  17909. incr = 1 << (len - drop);
  17910. fill = 1 << curr;
  17911. min = fill; /* save offset to next table */
  17912. do {
  17913. fill -= incr;
  17914. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  17915. } while (fill !== 0);
  17916. /* backwards increment the len-bit code huff */
  17917. incr = 1 << (len - 1);
  17918. while (huff & incr) {
  17919. incr >>= 1;
  17920. }
  17921. if (incr !== 0) {
  17922. huff &= incr - 1;
  17923. huff += incr;
  17924. } else {
  17925. huff = 0;
  17926. }
  17927. /* go to next symbol, update count, len */
  17928. sym++;
  17929. if (--count[len] === 0) {
  17930. if (len === max) { break; }
  17931. len = lens[lens_index + work[sym]];
  17932. }
  17933. /* create new sub-table if needed */
  17934. if (len > root && (huff & mask) !== low) {
  17935. /* if first time, transition to sub-tables */
  17936. if (drop === 0) {
  17937. drop = root;
  17938. }
  17939. /* increment past last table */
  17940. next += min; /* here min is 1 << curr */
  17941. /* determine length of next table */
  17942. curr = len - drop;
  17943. left = 1 << curr;
  17944. while (curr + drop < max) {
  17945. left -= count[curr + drop];
  17946. if (left <= 0) { break; }
  17947. curr++;
  17948. left <<= 1;
  17949. }
  17950. /* check for enough space */
  17951. used += 1 << curr;
  17952. if ((type === LENS && used > ENOUGH_LENS) ||
  17953. (type === DISTS && used > ENOUGH_DISTS)) {
  17954. return 1;
  17955. }
  17956. /* point entry in root table to sub-table */
  17957. low = huff & mask;
  17958. /*table.op[low] = curr;
  17959. table.bits[low] = root;
  17960. table.val[low] = next - opts.table_index;*/
  17961. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  17962. }
  17963. }
  17964. /* fill in remaining table entry if code is incomplete (guaranteed to have
  17965. at most one remaining entry, since if the code is incomplete, the
  17966. maximum code length that was allowed to get this far is one bit) */
  17967. if (huff !== 0) {
  17968. //table.op[next + huff] = 64; /* invalid code marker */
  17969. //table.bits[next + huff] = len - drop;
  17970. //table.val[next + huff] = 0;
  17971. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  17972. }
  17973. /* set return parameters */
  17974. //opts.table_index += used;
  17975. opts.bits = root;
  17976. return 0;
  17977. };
  17978. },{"../utils/common":51}],61:[function(require,module,exports){
  17979. 'use strict';
  17980. module.exports = {
  17981. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  17982. '1': 'stream end', /* Z_STREAM_END 1 */
  17983. '0': '', /* Z_OK 0 */
  17984. '-1': 'file error', /* Z_ERRNO (-1) */
  17985. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  17986. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  17987. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  17988. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  17989. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  17990. };
  17991. },{}],62:[function(require,module,exports){
  17992. 'use strict';
  17993. var utils = require('../utils/common');
  17994. /* Public constants ==========================================================*/
  17995. /* ===========================================================================*/
  17996. //var Z_FILTERED = 1;
  17997. //var Z_HUFFMAN_ONLY = 2;
  17998. //var Z_RLE = 3;
  17999. var Z_FIXED = 4;
  18000. //var Z_DEFAULT_STRATEGY = 0;
  18001. /* Possible values of the data_type field (though see inflate()) */
  18002. var Z_BINARY = 0;
  18003. var Z_TEXT = 1;
  18004. //var Z_ASCII = 1; // = Z_TEXT
  18005. var Z_UNKNOWN = 2;
  18006. /*============================================================================*/
  18007. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  18008. // From zutil.h
  18009. var STORED_BLOCK = 0;
  18010. var STATIC_TREES = 1;
  18011. var DYN_TREES = 2;
  18012. /* The three kinds of block type */
  18013. var MIN_MATCH = 3;
  18014. var MAX_MATCH = 258;
  18015. /* The minimum and maximum match lengths */
  18016. // From deflate.h
  18017. /* ===========================================================================
  18018. * Internal compression state.
  18019. */
  18020. var LENGTH_CODES = 29;
  18021. /* number of length codes, not counting the special END_BLOCK code */
  18022. var LITERALS = 256;
  18023. /* number of literal bytes 0..255 */
  18024. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  18025. /* number of Literal or Length codes, including the END_BLOCK code */
  18026. var D_CODES = 30;
  18027. /* number of distance codes */
  18028. var BL_CODES = 19;
  18029. /* number of codes used to transfer the bit lengths */
  18030. var HEAP_SIZE = 2*L_CODES + 1;
  18031. /* maximum heap size */
  18032. var MAX_BITS = 15;
  18033. /* All codes must not exceed MAX_BITS bits */
  18034. var Buf_size = 16;
  18035. /* size of bit buffer in bi_buf */
  18036. /* ===========================================================================
  18037. * Constants
  18038. */
  18039. var MAX_BL_BITS = 7;
  18040. /* Bit length codes must not exceed MAX_BL_BITS bits */
  18041. var END_BLOCK = 256;
  18042. /* end of block literal code */
  18043. var REP_3_6 = 16;
  18044. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  18045. var REPZ_3_10 = 17;
  18046. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  18047. var REPZ_11_138 = 18;
  18048. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  18049. var extra_lbits = /* extra bits for each length code */
  18050. [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];
  18051. var extra_dbits = /* extra bits for each distance code */
  18052. [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];
  18053. var extra_blbits = /* extra bits for each bit length code */
  18054. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  18055. var bl_order =
  18056. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  18057. /* The lengths of the bit length codes are sent in order of decreasing
  18058. * probability, to avoid transmitting the lengths for unused bit length codes.
  18059. */
  18060. /* ===========================================================================
  18061. * Local data. These are initialized only once.
  18062. */
  18063. // We pre-fill arrays with 0 to avoid uninitialized gaps
  18064. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  18065. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  18066. var static_ltree = new Array((L_CODES+2) * 2);
  18067. zero(static_ltree);
  18068. /* The static literal tree. Since the bit lengths are imposed, there is no
  18069. * need for the L_CODES extra codes used during heap construction. However
  18070. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  18071. * below).
  18072. */
  18073. var static_dtree = new Array(D_CODES * 2);
  18074. zero(static_dtree);
  18075. /* The static distance tree. (Actually a trivial tree since all codes use
  18076. * 5 bits.)
  18077. */
  18078. var _dist_code = new Array(DIST_CODE_LEN);
  18079. zero(_dist_code);
  18080. /* Distance codes. The first 256 values correspond to the distances
  18081. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  18082. * the 15 bit distances.
  18083. */
  18084. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  18085. zero(_length_code);
  18086. /* length code for each normalized match length (0 == MIN_MATCH) */
  18087. var base_length = new Array(LENGTH_CODES);
  18088. zero(base_length);
  18089. /* First normalized length for each code (0 = MIN_MATCH) */
  18090. var base_dist = new Array(D_CODES);
  18091. zero(base_dist);
  18092. /* First normalized distance for each code (0 = distance of 1) */
  18093. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  18094. this.static_tree = static_tree; /* static tree or NULL */
  18095. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  18096. this.extra_base = extra_base; /* base index for extra_bits */
  18097. this.elems = elems; /* max number of elements in the tree */
  18098. this.max_length = max_length; /* max bit length for the codes */
  18099. // show if `static_tree` has data or dummy - needed for monomorphic objects
  18100. this.has_stree = static_tree && static_tree.length;
  18101. };
  18102. var static_l_desc;
  18103. var static_d_desc;
  18104. var static_bl_desc;
  18105. var TreeDesc = function(dyn_tree, stat_desc) {
  18106. this.dyn_tree = dyn_tree; /* the dynamic tree */
  18107. this.max_code = 0; /* largest code with non zero frequency */
  18108. this.stat_desc = stat_desc; /* the corresponding static tree */
  18109. };
  18110. function d_code(dist) {
  18111. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  18112. }
  18113. /* ===========================================================================
  18114. * Output a short LSB first on the stream.
  18115. * IN assertion: there is enough room in pendingBuf.
  18116. */
  18117. function put_short (s, w) {
  18118. // put_byte(s, (uch)((w) & 0xff));
  18119. // put_byte(s, (uch)((ush)(w) >> 8));
  18120. s.pending_buf[s.pending++] = (w) & 0xff;
  18121. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  18122. }
  18123. /* ===========================================================================
  18124. * Send a value on a given number of bits.
  18125. * IN assertion: length <= 16 and value fits in length bits.
  18126. */
  18127. function send_bits(s, value, length) {
  18128. if (s.bi_valid > (Buf_size - length)) {
  18129. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  18130. put_short(s, s.bi_buf);
  18131. s.bi_buf = value >> (Buf_size - s.bi_valid);
  18132. s.bi_valid += length - Buf_size;
  18133. } else {
  18134. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  18135. s.bi_valid += length;
  18136. }
  18137. }
  18138. function send_code(s, c, tree) {
  18139. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  18140. }
  18141. /* ===========================================================================
  18142. * Reverse the first len bits of a code, using straightforward code (a faster
  18143. * method would use a table)
  18144. * IN assertion: 1 <= len <= 15
  18145. */
  18146. function bi_reverse(code, len) {
  18147. var res = 0;
  18148. do {
  18149. res |= code & 1;
  18150. code >>>= 1;
  18151. res <<= 1;
  18152. } while (--len > 0);
  18153. return res >>> 1;
  18154. }
  18155. /* ===========================================================================
  18156. * Flush the bit buffer, keeping at most 7 bits in it.
  18157. */
  18158. function bi_flush(s) {
  18159. if (s.bi_valid === 16) {
  18160. put_short(s, s.bi_buf);
  18161. s.bi_buf = 0;
  18162. s.bi_valid = 0;
  18163. } else if (s.bi_valid >= 8) {
  18164. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  18165. s.bi_buf >>= 8;
  18166. s.bi_valid -= 8;
  18167. }
  18168. }
  18169. /* ===========================================================================
  18170. * Compute the optimal bit lengths for a tree and update the total bit length
  18171. * for the current block.
  18172. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  18173. * above are the tree nodes sorted by increasing frequency.
  18174. * OUT assertions: the field len is set to the optimal bit length, the
  18175. * array bl_count contains the frequencies for each bit length.
  18176. * The length opt_len is updated; static_len is also updated if stree is
  18177. * not null.
  18178. */
  18179. function gen_bitlen(s, desc)
  18180. // deflate_state *s;
  18181. // tree_desc *desc; /* the tree descriptor */
  18182. {
  18183. var tree = desc.dyn_tree;
  18184. var max_code = desc.max_code;
  18185. var stree = desc.stat_desc.static_tree;
  18186. var has_stree = desc.stat_desc.has_stree;
  18187. var extra = desc.stat_desc.extra_bits;
  18188. var base = desc.stat_desc.extra_base;
  18189. var max_length = desc.stat_desc.max_length;
  18190. var h; /* heap index */
  18191. var n, m; /* iterate over the tree elements */
  18192. var bits; /* bit length */
  18193. var xbits; /* extra bits */
  18194. var f; /* frequency */
  18195. var overflow = 0; /* number of elements with bit length too large */
  18196. for (bits = 0; bits <= MAX_BITS; bits++) {
  18197. s.bl_count[bits] = 0;
  18198. }
  18199. /* In a first pass, compute the optimal bit lengths (which may
  18200. * overflow in the case of the bit length tree).
  18201. */
  18202. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  18203. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  18204. n = s.heap[h];
  18205. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  18206. if (bits > max_length) {
  18207. bits = max_length;
  18208. overflow++;
  18209. }
  18210. tree[n*2 + 1]/*.Len*/ = bits;
  18211. /* We overwrite tree[n].Dad which is no longer needed */
  18212. if (n > max_code) { continue; } /* not a leaf node */
  18213. s.bl_count[bits]++;
  18214. xbits = 0;
  18215. if (n >= base) {
  18216. xbits = extra[n-base];
  18217. }
  18218. f = tree[n * 2]/*.Freq*/;
  18219. s.opt_len += f * (bits + xbits);
  18220. if (has_stree) {
  18221. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  18222. }
  18223. }
  18224. if (overflow === 0) { return; }
  18225. // Trace((stderr,"\nbit length overflow\n"));
  18226. /* This happens for example on obj2 and pic of the Calgary corpus */
  18227. /* Find the first bit length which could increase: */
  18228. do {
  18229. bits = max_length-1;
  18230. while (s.bl_count[bits] === 0) { bits--; }
  18231. s.bl_count[bits]--; /* move one leaf down the tree */
  18232. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  18233. s.bl_count[max_length]--;
  18234. /* The brother of the overflow item also moves one step up,
  18235. * but this does not affect bl_count[max_length]
  18236. */
  18237. overflow -= 2;
  18238. } while (overflow > 0);
  18239. /* Now recompute all bit lengths, scanning in increasing frequency.
  18240. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  18241. * lengths instead of fixing only the wrong ones. This idea is taken
  18242. * from 'ar' written by Haruhiko Okumura.)
  18243. */
  18244. for (bits = max_length; bits !== 0; bits--) {
  18245. n = s.bl_count[bits];
  18246. while (n !== 0) {
  18247. m = s.heap[--h];
  18248. if (m > max_code) { continue; }
  18249. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  18250. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  18251. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  18252. tree[m*2 + 1]/*.Len*/ = bits;
  18253. }
  18254. n--;
  18255. }
  18256. }
  18257. }
  18258. /* ===========================================================================
  18259. * Generate the codes for a given tree and bit counts (which need not be
  18260. * optimal).
  18261. * IN assertion: the array bl_count contains the bit length statistics for
  18262. * the given tree and the field len is set for all tree elements.
  18263. * OUT assertion: the field code is set for all tree elements of non
  18264. * zero code length.
  18265. */
  18266. function gen_codes(tree, max_code, bl_count)
  18267. // ct_data *tree; /* the tree to decorate */
  18268. // int max_code; /* largest code with non zero frequency */
  18269. // ushf *bl_count; /* number of codes at each bit length */
  18270. {
  18271. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  18272. var code = 0; /* running code value */
  18273. var bits; /* bit index */
  18274. var n; /* code index */
  18275. /* The distribution counts are first used to generate the code values
  18276. * without bit reversal.
  18277. */
  18278. for (bits = 1; bits <= MAX_BITS; bits++) {
  18279. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  18280. }
  18281. /* Check that the bit counts in bl_count are consistent. The last code
  18282. * must be all ones.
  18283. */
  18284. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  18285. // "inconsistent bit counts");
  18286. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  18287. for (n = 0; n <= max_code; n++) {
  18288. var len = tree[n*2 + 1]/*.Len*/;
  18289. if (len === 0) { continue; }
  18290. /* Now reverse the bits */
  18291. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  18292. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  18293. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  18294. }
  18295. }
  18296. /* ===========================================================================
  18297. * Initialize the various 'constant' tables.
  18298. */
  18299. function tr_static_init() {
  18300. var n; /* iterates over tree elements */
  18301. var bits; /* bit counter */
  18302. var length; /* length value */
  18303. var code; /* code value */
  18304. var dist; /* distance index */
  18305. var bl_count = new Array(MAX_BITS+1);
  18306. /* number of codes at each bit length for an optimal tree */
  18307. // do check in _tr_init()
  18308. //if (static_init_done) return;
  18309. /* For some embedded targets, global variables are not initialized: */
  18310. /*#ifdef NO_INIT_GLOBAL_POINTERS
  18311. static_l_desc.static_tree = static_ltree;
  18312. static_l_desc.extra_bits = extra_lbits;
  18313. static_d_desc.static_tree = static_dtree;
  18314. static_d_desc.extra_bits = extra_dbits;
  18315. static_bl_desc.extra_bits = extra_blbits;
  18316. #endif*/
  18317. /* Initialize the mapping length (0..255) -> length code (0..28) */
  18318. length = 0;
  18319. for (code = 0; code < LENGTH_CODES-1; code++) {
  18320. base_length[code] = length;
  18321. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  18322. _length_code[length++] = code;
  18323. }
  18324. }
  18325. //Assert (length == 256, "tr_static_init: length != 256");
  18326. /* Note that the length 255 (match length 258) can be represented
  18327. * in two different ways: code 284 + 5 bits or code 285, so we
  18328. * overwrite length_code[255] to use the best encoding:
  18329. */
  18330. _length_code[length-1] = code;
  18331. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  18332. dist = 0;
  18333. for (code = 0 ; code < 16; code++) {
  18334. base_dist[code] = dist;
  18335. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  18336. _dist_code[dist++] = code;
  18337. }
  18338. }
  18339. //Assert (dist == 256, "tr_static_init: dist != 256");
  18340. dist >>= 7; /* from now on, all distances are divided by 128 */
  18341. for (; code < D_CODES; code++) {
  18342. base_dist[code] = dist << 7;
  18343. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  18344. _dist_code[256 + dist++] = code;
  18345. }
  18346. }
  18347. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  18348. /* Construct the codes of the static literal tree */
  18349. for (bits = 0; bits <= MAX_BITS; bits++) {
  18350. bl_count[bits] = 0;
  18351. }
  18352. n = 0;
  18353. while (n <= 143) {
  18354. static_ltree[n*2 + 1]/*.Len*/ = 8;
  18355. n++;
  18356. bl_count[8]++;
  18357. }
  18358. while (n <= 255) {
  18359. static_ltree[n*2 + 1]/*.Len*/ = 9;
  18360. n++;
  18361. bl_count[9]++;
  18362. }
  18363. while (n <= 279) {
  18364. static_ltree[n*2 + 1]/*.Len*/ = 7;
  18365. n++;
  18366. bl_count[7]++;
  18367. }
  18368. while (n <= 287) {
  18369. static_ltree[n*2 + 1]/*.Len*/ = 8;
  18370. n++;
  18371. bl_count[8]++;
  18372. }
  18373. /* Codes 286 and 287 do not exist, but we must include them in the
  18374. * tree construction to get a canonical Huffman tree (longest code
  18375. * all ones)
  18376. */
  18377. gen_codes(static_ltree, L_CODES+1, bl_count);
  18378. /* The static distance tree is trivial: */
  18379. for (n = 0; n < D_CODES; n++) {
  18380. static_dtree[n*2 + 1]/*.Len*/ = 5;
  18381. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  18382. }
  18383. // Now data ready and we can init static trees
  18384. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  18385. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  18386. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  18387. //static_init_done = true;
  18388. }
  18389. /* ===========================================================================
  18390. * Initialize a new block.
  18391. */
  18392. function init_block(s) {
  18393. var n; /* iterates over tree elements */
  18394. /* Initialize the trees. */
  18395. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  18396. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  18397. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  18398. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  18399. s.opt_len = s.static_len = 0;
  18400. s.last_lit = s.matches = 0;
  18401. }
  18402. /* ===========================================================================
  18403. * Flush the bit buffer and align the output on a byte boundary
  18404. */
  18405. function bi_windup(s)
  18406. {
  18407. if (s.bi_valid > 8) {
  18408. put_short(s, s.bi_buf);
  18409. } else if (s.bi_valid > 0) {
  18410. //put_byte(s, (Byte)s->bi_buf);
  18411. s.pending_buf[s.pending++] = s.bi_buf;
  18412. }
  18413. s.bi_buf = 0;
  18414. s.bi_valid = 0;
  18415. }
  18416. /* ===========================================================================
  18417. * Copy a stored block, storing first the length and its
  18418. * one's complement if requested.
  18419. */
  18420. function copy_block(s, buf, len, header)
  18421. //DeflateState *s;
  18422. //charf *buf; /* the input data */
  18423. //unsigned len; /* its length */
  18424. //int header; /* true if block header must be written */
  18425. {
  18426. bi_windup(s); /* align on byte boundary */
  18427. if (header) {
  18428. put_short(s, len);
  18429. put_short(s, ~len);
  18430. }
  18431. // while (len--) {
  18432. // put_byte(s, *buf++);
  18433. // }
  18434. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  18435. s.pending += len;
  18436. }
  18437. /* ===========================================================================
  18438. * Compares to subtrees, using the tree depth as tie breaker when
  18439. * the subtrees have equal frequency. This minimizes the worst case length.
  18440. */
  18441. function smaller(tree, n, m, depth) {
  18442. var _n2 = n*2;
  18443. var _m2 = m*2;
  18444. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  18445. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  18446. }
  18447. /* ===========================================================================
  18448. * Restore the heap property by moving down the tree starting at node k,
  18449. * exchanging a node with the smallest of its two sons if necessary, stopping
  18450. * when the heap property is re-established (each father smaller than its
  18451. * two sons).
  18452. */
  18453. function pqdownheap(s, tree, k)
  18454. // deflate_state *s;
  18455. // ct_data *tree; /* the tree to restore */
  18456. // int k; /* node to move down */
  18457. {
  18458. var v = s.heap[k];
  18459. var j = k << 1; /* left son of k */
  18460. while (j <= s.heap_len) {
  18461. /* Set j to the smallest of the two sons: */
  18462. if (j < s.heap_len &&
  18463. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  18464. j++;
  18465. }
  18466. /* Exit if v is smaller than both sons */
  18467. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  18468. /* Exchange v with the smallest son */
  18469. s.heap[k] = s.heap[j];
  18470. k = j;
  18471. /* And continue down the tree, setting j to the left son of k */
  18472. j <<= 1;
  18473. }
  18474. s.heap[k] = v;
  18475. }
  18476. // inlined manually
  18477. // var SMALLEST = 1;
  18478. /* ===========================================================================
  18479. * Send the block data compressed using the given Huffman trees
  18480. */
  18481. function compress_block(s, ltree, dtree)
  18482. // deflate_state *s;
  18483. // const ct_data *ltree; /* literal tree */
  18484. // const ct_data *dtree; /* distance tree */
  18485. {
  18486. var dist; /* distance of matched string */
  18487. var lc; /* match length or unmatched char (if dist == 0) */
  18488. var lx = 0; /* running index in l_buf */
  18489. var code; /* the code to send */
  18490. var extra; /* number of extra bits to send */
  18491. if (s.last_lit !== 0) {
  18492. do {
  18493. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  18494. lc = s.pending_buf[s.l_buf + lx];
  18495. lx++;
  18496. if (dist === 0) {
  18497. send_code(s, lc, ltree); /* send a literal byte */
  18498. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  18499. } else {
  18500. /* Here, lc is the match length - MIN_MATCH */
  18501. code = _length_code[lc];
  18502. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  18503. extra = extra_lbits[code];
  18504. if (extra !== 0) {
  18505. lc -= base_length[code];
  18506. send_bits(s, lc, extra); /* send the extra length bits */
  18507. }
  18508. dist--; /* dist is now the match distance - 1 */
  18509. code = d_code(dist);
  18510. //Assert (code < D_CODES, "bad d_code");
  18511. send_code(s, code, dtree); /* send the distance code */
  18512. extra = extra_dbits[code];
  18513. if (extra !== 0) {
  18514. dist -= base_dist[code];
  18515. send_bits(s, dist, extra); /* send the extra distance bits */
  18516. }
  18517. } /* literal or match pair ? */
  18518. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  18519. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  18520. // "pendingBuf overflow");
  18521. } while (lx < s.last_lit);
  18522. }
  18523. send_code(s, END_BLOCK, ltree);
  18524. }
  18525. /* ===========================================================================
  18526. * Construct one Huffman tree and assigns the code bit strings and lengths.
  18527. * Update the total bit length for the current block.
  18528. * IN assertion: the field freq is set for all tree elements.
  18529. * OUT assertions: the fields len and code are set to the optimal bit length
  18530. * and corresponding code. The length opt_len is updated; static_len is
  18531. * also updated if stree is not null. The field max_code is set.
  18532. */
  18533. function build_tree(s, desc)
  18534. // deflate_state *s;
  18535. // tree_desc *desc; /* the tree descriptor */
  18536. {
  18537. var tree = desc.dyn_tree;
  18538. var stree = desc.stat_desc.static_tree;
  18539. var has_stree = desc.stat_desc.has_stree;
  18540. var elems = desc.stat_desc.elems;
  18541. var n, m; /* iterate over heap elements */
  18542. var max_code = -1; /* largest code with non zero frequency */
  18543. var node; /* new node being created */
  18544. /* Construct the initial heap, with least frequent element in
  18545. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  18546. * heap[0] is not used.
  18547. */
  18548. s.heap_len = 0;
  18549. s.heap_max = HEAP_SIZE;
  18550. for (n = 0; n < elems; n++) {
  18551. if (tree[n * 2]/*.Freq*/ !== 0) {
  18552. s.heap[++s.heap_len] = max_code = n;
  18553. s.depth[n] = 0;
  18554. } else {
  18555. tree[n*2 + 1]/*.Len*/ = 0;
  18556. }
  18557. }
  18558. /* The pkzip format requires that at least one distance code exists,
  18559. * and that at least one bit should be sent even if there is only one
  18560. * possible code. So to avoid special checks later on we force at least
  18561. * two codes of non zero frequency.
  18562. */
  18563. while (s.heap_len < 2) {
  18564. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  18565. tree[node * 2]/*.Freq*/ = 1;
  18566. s.depth[node] = 0;
  18567. s.opt_len--;
  18568. if (has_stree) {
  18569. s.static_len -= stree[node*2 + 1]/*.Len*/;
  18570. }
  18571. /* node is 0 or 1 so it does not have extra bits */
  18572. }
  18573. desc.max_code = max_code;
  18574. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  18575. * establish sub-heaps of increasing lengths:
  18576. */
  18577. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  18578. /* Construct the Huffman tree by repeatedly combining the least two
  18579. * frequent nodes.
  18580. */
  18581. node = elems; /* next internal node of the tree */
  18582. do {
  18583. //pqremove(s, tree, n); /* n = node of least frequency */
  18584. /*** pqremove ***/
  18585. n = s.heap[1/*SMALLEST*/];
  18586. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  18587. pqdownheap(s, tree, 1/*SMALLEST*/);
  18588. /***/
  18589. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  18590. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  18591. s.heap[--s.heap_max] = m;
  18592. /* Create a new node father of n and m */
  18593. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  18594. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  18595. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  18596. /* and insert the new node in the heap */
  18597. s.heap[1/*SMALLEST*/] = node++;
  18598. pqdownheap(s, tree, 1/*SMALLEST*/);
  18599. } while (s.heap_len >= 2);
  18600. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  18601. /* At this point, the fields freq and dad are set. We can now
  18602. * generate the bit lengths.
  18603. */
  18604. gen_bitlen(s, desc);
  18605. /* The field len is now set, we can generate the bit codes */
  18606. gen_codes(tree, max_code, s.bl_count);
  18607. }
  18608. /* ===========================================================================
  18609. * Scan a literal or distance tree to determine the frequencies of the codes
  18610. * in the bit length tree.
  18611. */
  18612. function scan_tree(s, tree, max_code)
  18613. // deflate_state *s;
  18614. // ct_data *tree; /* the tree to be scanned */
  18615. // int max_code; /* and its largest code of non zero frequency */
  18616. {
  18617. var n; /* iterates over all tree elements */
  18618. var prevlen = -1; /* last emitted length */
  18619. var curlen; /* length of current code */
  18620. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  18621. var count = 0; /* repeat count of the current code */
  18622. var max_count = 7; /* max repeat count */
  18623. var min_count = 4; /* min repeat count */
  18624. if (nextlen === 0) {
  18625. max_count = 138;
  18626. min_count = 3;
  18627. }
  18628. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  18629. for (n = 0; n <= max_code; n++) {
  18630. curlen = nextlen;
  18631. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  18632. if (++count < max_count && curlen === nextlen) {
  18633. continue;
  18634. } else if (count < min_count) {
  18635. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  18636. } else if (curlen !== 0) {
  18637. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  18638. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  18639. } else if (count <= 10) {
  18640. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  18641. } else {
  18642. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  18643. }
  18644. count = 0;
  18645. prevlen = curlen;
  18646. if (nextlen === 0) {
  18647. max_count = 138;
  18648. min_count = 3;
  18649. } else if (curlen === nextlen) {
  18650. max_count = 6;
  18651. min_count = 3;
  18652. } else {
  18653. max_count = 7;
  18654. min_count = 4;
  18655. }
  18656. }
  18657. }
  18658. /* ===========================================================================
  18659. * Send a literal or distance tree in compressed form, using the codes in
  18660. * bl_tree.
  18661. */
  18662. function send_tree(s, tree, max_code)
  18663. // deflate_state *s;
  18664. // ct_data *tree; /* the tree to be scanned */
  18665. // int max_code; /* and its largest code of non zero frequency */
  18666. {
  18667. var n; /* iterates over all tree elements */
  18668. var prevlen = -1; /* last emitted length */
  18669. var curlen; /* length of current code */
  18670. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  18671. var count = 0; /* repeat count of the current code */
  18672. var max_count = 7; /* max repeat count */
  18673. var min_count = 4; /* min repeat count */
  18674. /* tree[max_code+1].Len = -1; */ /* guard already set */
  18675. if (nextlen === 0) {
  18676. max_count = 138;
  18677. min_count = 3;
  18678. }
  18679. for (n = 0; n <= max_code; n++) {
  18680. curlen = nextlen;
  18681. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  18682. if (++count < max_count && curlen === nextlen) {
  18683. continue;
  18684. } else if (count < min_count) {
  18685. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  18686. } else if (curlen !== 0) {
  18687. if (curlen !== prevlen) {
  18688. send_code(s, curlen, s.bl_tree);
  18689. count--;
  18690. }
  18691. //Assert(count >= 3 && count <= 6, " 3_6?");
  18692. send_code(s, REP_3_6, s.bl_tree);
  18693. send_bits(s, count-3, 2);
  18694. } else if (count <= 10) {
  18695. send_code(s, REPZ_3_10, s.bl_tree);
  18696. send_bits(s, count-3, 3);
  18697. } else {
  18698. send_code(s, REPZ_11_138, s.bl_tree);
  18699. send_bits(s, count-11, 7);
  18700. }
  18701. count = 0;
  18702. prevlen = curlen;
  18703. if (nextlen === 0) {
  18704. max_count = 138;
  18705. min_count = 3;
  18706. } else if (curlen === nextlen) {
  18707. max_count = 6;
  18708. min_count = 3;
  18709. } else {
  18710. max_count = 7;
  18711. min_count = 4;
  18712. }
  18713. }
  18714. }
  18715. /* ===========================================================================
  18716. * Construct the Huffman tree for the bit lengths and return the index in
  18717. * bl_order of the last bit length code to send.
  18718. */
  18719. function build_bl_tree(s) {
  18720. var max_blindex; /* index of last bit length code of non zero freq */
  18721. /* Determine the bit length frequencies for literal and distance trees */
  18722. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  18723. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  18724. /* Build the bit length tree: */
  18725. build_tree(s, s.bl_desc);
  18726. /* opt_len now includes the length of the tree representations, except
  18727. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  18728. */
  18729. /* Determine the number of bit length codes to send. The pkzip format
  18730. * requires that at least 4 bit length codes be sent. (appnote.txt says
  18731. * 3 but the actual value used is 4.)
  18732. */
  18733. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  18734. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  18735. break;
  18736. }
  18737. }
  18738. /* Update opt_len to include the bit length tree and counts */
  18739. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  18740. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  18741. // s->opt_len, s->static_len));
  18742. return max_blindex;
  18743. }
  18744. /* ===========================================================================
  18745. * Send the header for a block using dynamic Huffman trees: the counts, the
  18746. * lengths of the bit length codes, the literal tree and the distance tree.
  18747. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  18748. */
  18749. function send_all_trees(s, lcodes, dcodes, blcodes)
  18750. // deflate_state *s;
  18751. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  18752. {
  18753. var rank; /* index in bl_order */
  18754. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  18755. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  18756. // "too many codes");
  18757. //Tracev((stderr, "\nbl counts: "));
  18758. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  18759. send_bits(s, dcodes-1, 5);
  18760. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  18761. for (rank = 0; rank < blcodes; rank++) {
  18762. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  18763. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  18764. }
  18765. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  18766. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  18767. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  18768. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  18769. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  18770. }
  18771. /* ===========================================================================
  18772. * Check if the data type is TEXT or BINARY, using the following algorithm:
  18773. * - TEXT if the two conditions below are satisfied:
  18774. * a) There are no non-portable control characters belonging to the
  18775. * "black list" (0..6, 14..25, 28..31).
  18776. * b) There is at least one printable character belonging to the
  18777. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  18778. * - BINARY otherwise.
  18779. * - The following partially-portable control characters form a
  18780. * "gray list" that is ignored in this detection algorithm:
  18781. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  18782. * IN assertion: the fields Freq of dyn_ltree are set.
  18783. */
  18784. function detect_data_type(s) {
  18785. /* black_mask is the bit mask of black-listed bytes
  18786. * set bits 0..6, 14..25, and 28..31
  18787. * 0xf3ffc07f = binary 11110011111111111100000001111111
  18788. */
  18789. var black_mask = 0xf3ffc07f;
  18790. var n;
  18791. /* Check for non-textual ("black-listed") bytes. */
  18792. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  18793. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  18794. return Z_BINARY;
  18795. }
  18796. }
  18797. /* Check for textual ("white-listed") bytes. */
  18798. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  18799. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  18800. return Z_TEXT;
  18801. }
  18802. for (n = 32; n < LITERALS; n++) {
  18803. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  18804. return Z_TEXT;
  18805. }
  18806. }
  18807. /* There are no "black-listed" or "white-listed" bytes:
  18808. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  18809. */
  18810. return Z_BINARY;
  18811. }
  18812. var static_init_done = false;
  18813. /* ===========================================================================
  18814. * Initialize the tree data structures for a new zlib stream.
  18815. */
  18816. function _tr_init(s)
  18817. {
  18818. if (!static_init_done) {
  18819. tr_static_init();
  18820. static_init_done = true;
  18821. }
  18822. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  18823. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  18824. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  18825. s.bi_buf = 0;
  18826. s.bi_valid = 0;
  18827. /* Initialize the first block of the first file: */
  18828. init_block(s);
  18829. }
  18830. /* ===========================================================================
  18831. * Send a stored block
  18832. */
  18833. function _tr_stored_block(s, buf, stored_len, last)
  18834. //DeflateState *s;
  18835. //charf *buf; /* input block */
  18836. //ulg stored_len; /* length of input block */
  18837. //int last; /* one if this is the last block for a file */
  18838. {
  18839. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  18840. copy_block(s, buf, stored_len, true); /* with header */
  18841. }
  18842. /* ===========================================================================
  18843. * Send one empty static block to give enough lookahead for inflate.
  18844. * This takes 10 bits, of which 7 may remain in the bit buffer.
  18845. */
  18846. function _tr_align(s) {
  18847. send_bits(s, STATIC_TREES<<1, 3);
  18848. send_code(s, END_BLOCK, static_ltree);
  18849. bi_flush(s);
  18850. }
  18851. /* ===========================================================================
  18852. * Determine the best encoding for the current block: dynamic trees, static
  18853. * trees or store, and output the encoded block to the zip file.
  18854. */
  18855. function _tr_flush_block(s, buf, stored_len, last)
  18856. //DeflateState *s;
  18857. //charf *buf; /* input block, or NULL if too old */
  18858. //ulg stored_len; /* length of input block */
  18859. //int last; /* one if this is the last block for a file */
  18860. {
  18861. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  18862. var max_blindex = 0; /* index of last bit length code of non zero freq */
  18863. /* Build the Huffman trees unless a stored block is forced */
  18864. if (s.level > 0) {
  18865. /* Check if the file is binary or text */
  18866. if (s.strm.data_type === Z_UNKNOWN) {
  18867. s.strm.data_type = detect_data_type(s);
  18868. }
  18869. /* Construct the literal and distance trees */
  18870. build_tree(s, s.l_desc);
  18871. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  18872. // s->static_len));
  18873. build_tree(s, s.d_desc);
  18874. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  18875. // s->static_len));
  18876. /* At this point, opt_len and static_len are the total bit lengths of
  18877. * the compressed block data, excluding the tree representations.
  18878. */
  18879. /* Build the bit length tree for the above two trees, and get the index
  18880. * in bl_order of the last bit length code to send.
  18881. */
  18882. max_blindex = build_bl_tree(s);
  18883. /* Determine the best encoding. Compute the block lengths in bytes. */
  18884. opt_lenb = (s.opt_len+3+7) >>> 3;
  18885. static_lenb = (s.static_len+3+7) >>> 3;
  18886. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  18887. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  18888. // s->last_lit));
  18889. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  18890. } else {
  18891. // Assert(buf != (char*)0, "lost buf");
  18892. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  18893. }
  18894. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  18895. /* 4: two words for the lengths */
  18896. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  18897. * Otherwise we can't have processed more than WSIZE input bytes since
  18898. * the last block flush, because compression would have been
  18899. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  18900. * transform a block into a stored block.
  18901. */
  18902. _tr_stored_block(s, buf, stored_len, last);
  18903. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  18904. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  18905. compress_block(s, static_ltree, static_dtree);
  18906. } else {
  18907. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  18908. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  18909. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  18910. }
  18911. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  18912. /* The above check is made mod 2^32, for files larger than 512 MB
  18913. * and uLong implemented on 32 bits.
  18914. */
  18915. init_block(s);
  18916. if (last) {
  18917. bi_windup(s);
  18918. }
  18919. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  18920. // s->compressed_len-7*last));
  18921. }
  18922. /* ===========================================================================
  18923. * Save the match info and tally the frequency counts. Return true if
  18924. * the current block must be flushed.
  18925. */
  18926. function _tr_tally(s, dist, lc)
  18927. // deflate_state *s;
  18928. // unsigned dist; /* distance of matched string */
  18929. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  18930. {
  18931. //var out_length, in_length, dcode;
  18932. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  18933. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  18934. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  18935. s.last_lit++;
  18936. if (dist === 0) {
  18937. /* lc is the unmatched char */
  18938. s.dyn_ltree[lc*2]/*.Freq*/++;
  18939. } else {
  18940. s.matches++;
  18941. /* Here, lc is the match length - MIN_MATCH */
  18942. dist--; /* dist = match distance - 1 */
  18943. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  18944. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  18945. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  18946. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  18947. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  18948. }
  18949. // (!) This block is disabled in zlib defailts,
  18950. // don't enable it for binary compatibility
  18951. //#ifdef TRUNCATE_BLOCK
  18952. // /* Try to guess if it is profitable to stop the current block here */
  18953. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  18954. // /* Compute an upper bound for the compressed length */
  18955. // out_length = s.last_lit*8;
  18956. // in_length = s.strstart - s.block_start;
  18957. //
  18958. // for (dcode = 0; dcode < D_CODES; dcode++) {
  18959. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  18960. // }
  18961. // out_length >>>= 3;
  18962. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  18963. // // s->last_lit, in_length, out_length,
  18964. // // 100L - out_length*100L/in_length));
  18965. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  18966. // return true;
  18967. // }
  18968. // }
  18969. //#endif
  18970. return (s.last_lit === s.lit_bufsize-1);
  18971. /* We avoid equality with lit_bufsize because of wraparound at 64K
  18972. * on 16 bit machines and because stored blocks are restricted to
  18973. * 64K-1 bytes.
  18974. */
  18975. }
  18976. exports._tr_init = _tr_init;
  18977. exports._tr_stored_block = _tr_stored_block;
  18978. exports._tr_flush_block = _tr_flush_block;
  18979. exports._tr_tally = _tr_tally;
  18980. exports._tr_align = _tr_align;
  18981. },{"../utils/common":51}],63:[function(require,module,exports){
  18982. 'use strict';
  18983. function ZStream() {
  18984. /* next input byte */
  18985. this.input = null; // JS specific, because we have no pointers
  18986. this.next_in = 0;
  18987. /* number of bytes available at input */
  18988. this.avail_in = 0;
  18989. /* total number of input bytes read so far */
  18990. this.total_in = 0;
  18991. /* next output byte should be put there */
  18992. this.output = null; // JS specific, because we have no pointers
  18993. this.next_out = 0;
  18994. /* remaining free space at output */
  18995. this.avail_out = 0;
  18996. /* total number of bytes output so far */
  18997. this.total_out = 0;
  18998. /* last error message, NULL if no error */
  18999. this.msg = ''/*Z_NULL*/;
  19000. /* not visible by applications */
  19001. this.state = null;
  19002. /* best guess about the data type: binary or text */
  19003. this.data_type = 2/*Z_UNKNOWN*/;
  19004. /* adler32 value of the uncompressed data */
  19005. this.adler = 0;
  19006. }
  19007. module.exports = ZStream;
  19008. },{}],64:[function(require,module,exports){
  19009. /* Copyright @ 2015 Atlassian Pty Ltd
  19010. *
  19011. * Licensed under the Apache License, Version 2.0 (the "License");
  19012. * you may not use this file except in compliance with the License.
  19013. * You may obtain a copy of the License at
  19014. *
  19015. * http://www.apache.org/licenses/LICENSE-2.0
  19016. *
  19017. * Unless required by applicable law or agreed to in writing, software
  19018. * distributed under the License is distributed on an "AS IS" BASIS,
  19019. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19020. * See the License for the specific language governing permissions and
  19021. * limitations under the License.
  19022. */
  19023. module.exports = function arrayEquals(array) {
  19024. // if the other array is a falsy value, return
  19025. if (!array)
  19026. return false;
  19027. // compare lengths - can save a lot of time
  19028. if (this.length != array.length)
  19029. return false;
  19030. for (var i = 0, l = this.length; i < l; i++) {
  19031. // Check if we have nested arrays
  19032. if (this[i] instanceof Array && array[i] instanceof Array) {
  19033. // recurse into the nested arrays
  19034. if (!arrayEquals.apply(this[i], [array[i]]))
  19035. return false;
  19036. } else if (this[i] != array[i]) {
  19037. // Warning - two different object instances will never be equal:
  19038. // {x:20} != {x:20}
  19039. return false;
  19040. }
  19041. }
  19042. return true;
  19043. };
  19044. },{}],65:[function(require,module,exports){
  19045. /* Copyright @ 2015 Atlassian Pty Ltd
  19046. *
  19047. * Licensed under the Apache License, Version 2.0 (the "License");
  19048. * you may not use this file except in compliance with the License.
  19049. * You may obtain a copy of the License at
  19050. *
  19051. * http://www.apache.org/licenses/LICENSE-2.0
  19052. *
  19053. * Unless required by applicable law or agreed to in writing, software
  19054. * distributed under the License is distributed on an "AS IS" BASIS,
  19055. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19056. * See the License for the specific language governing permissions and
  19057. * limitations under the License.
  19058. */
  19059. exports.Interop = require('./interop');
  19060. },{"./interop":66}],66:[function(require,module,exports){
  19061. /* Copyright @ 2015 Atlassian Pty Ltd
  19062. *
  19063. * Licensed under the Apache License, Version 2.0 (the "License");
  19064. * you may not use this file except in compliance with the License.
  19065. * You may obtain a copy of the License at
  19066. *
  19067. * http://www.apache.org/licenses/LICENSE-2.0
  19068. *
  19069. * Unless required by applicable law or agreed to in writing, software
  19070. * distributed under the License is distributed on an "AS IS" BASIS,
  19071. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19072. * See the License for the specific language governing permissions and
  19073. * limitations under the License.
  19074. */
  19075. /* global RTCSessionDescription */
  19076. /* jshint -W097 */
  19077. "use strict";
  19078. var transform = require('./transform');
  19079. var arrayEquals = require('./array-equals');
  19080. function Interop() {
  19081. /**
  19082. * This map holds the most recent Unified Plan offer/answer SDP that was
  19083. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  19084. * the SDP string as values.
  19085. *
  19086. * @type {{}}
  19087. */
  19088. this.cache = {};
  19089. }
  19090. module.exports = Interop;
  19091. /**
  19092. * Returns the index of the first m-line with the given media type and with a
  19093. * direction which allows sending, in the last Unified Plan description with
  19094. * type "answer" converted to Plan B. Returns {null} if there is no saved
  19095. * answer, or if none of its m-lines with the given type allow sending.
  19096. * @param type the media type ("audio" or "video").
  19097. * @returns {*}
  19098. */
  19099. Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {
  19100. if (!this.cache.answer) {
  19101. return null;
  19102. }
  19103. var session = transform.parse(this.cache.answer);
  19104. if (session && session.media && Array.isArray(session.media)){
  19105. for (var i = 0; i < session.media.length; i++) {
  19106. if (session.media[i].type == type &&
  19107. (!session.media[i].direction /* default to sendrecv */ ||
  19108. session.media[i].direction === 'sendrecv' ||
  19109. session.media[i].direction === 'sendonly')){
  19110. return i;
  19111. }
  19112. }
  19113. }
  19114. return null;
  19115. };
  19116. /**
  19117. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  19118. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  19119. * application.
  19120. *
  19121. * @param desc
  19122. * @returns {*}
  19123. */
  19124. Interop.prototype.toPlanB = function(desc) {
  19125. var self = this;
  19126. //#region Preliminary input validation.
  19127. if (typeof desc !== 'object' || desc === null ||
  19128. typeof desc.sdp !== 'string') {
  19129. console.warn('An empty description was passed as an argument.');
  19130. return desc;
  19131. }
  19132. // Objectify the SDP for easier manipulation.
  19133. var session = transform.parse(desc.sdp);
  19134. // If the SDP contains no media, there's nothing to transform.
  19135. if (typeof session.media === 'undefined' ||
  19136. !Array.isArray(session.media) || session.media.length === 0) {
  19137. console.warn('The description has no media.');
  19138. return desc;
  19139. }
  19140. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  19141. // SDP has a video, an audio and a data "channel" at most.
  19142. if (session.media.length <= 3 && session.media.every(function(m) {
  19143. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  19144. })) {
  19145. console.warn('This description does not look like Unified Plan.');
  19146. return desc;
  19147. }
  19148. //#endregion
  19149. // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443
  19150. var sdp = desc.sdp;
  19151. var rewrite = false;
  19152. for (var i = 0; i < session.media.length; i++) {
  19153. var uLine = session.media[i];
  19154. uLine.rtp.forEach(function(rtp) {
  19155. if (rtp.codec === 'NULL')
  19156. {
  19157. rewrite = true;
  19158. var offer = transform.parse(self.cache['offer']);
  19159. rtp.codec = offer.media[i].rtp[0].codec;
  19160. }
  19161. });
  19162. };
  19163. if (rewrite) {
  19164. sdp = transform.write(session);
  19165. }
  19166. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  19167. // -> Unified Plan transformation.
  19168. this.cache[desc.type] = sdp;
  19169. //#region Convert from Unified Plan to Plan B.
  19170. // We rebuild the session.media array.
  19171. var media = session.media;
  19172. session.media = [];
  19173. // Associative array that maps channel types to channel objects for fast
  19174. // access to channel objects by their type, e.g. type2bl['audio']->channel
  19175. // obj.
  19176. var type2bl = {};
  19177. // Used to build the group:BUNDLE value after the channels construction
  19178. // loop.
  19179. var types = [];
  19180. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  19181. media.forEach(function(uLine) {
  19182. // rtcp-mux is required in the Plan B SDP.
  19183. if ((typeof uLine.rtcpMux !== 'string' ||
  19184. uLine.rtcpMux !== 'rtcp-mux') &&
  19185. uLine.direction !== 'inactive') {
  19186. throw new Error('Cannot convert to Plan B because m-lines ' +
  19187. 'without the rtcp-mux attribute were found.');
  19188. }
  19189. if (uLine.type === 'application') {
  19190. session.media.push(uLine);
  19191. types.push(uLine.mid);
  19192. return;
  19193. }
  19194. // If we don't have a channel for this uLine.type, then use this
  19195. // uLine as the channel basis.
  19196. if (typeof type2bl[uLine.type] === 'undefined') {
  19197. type2bl[uLine.type] = uLine;
  19198. }
  19199. // Add sources to the channel and handle a=msid.
  19200. if (typeof uLine.sources === 'object') {
  19201. Object.keys(uLine.sources).forEach(function(ssrc) {
  19202. if (typeof type2bl[uLine.type].sources !== 'object')
  19203. type2bl[uLine.type].sources = {};
  19204. // Assign the sources to the channel.
  19205. type2bl[uLine.type].sources[ssrc] =
  19206. uLine.sources[ssrc];
  19207. if (typeof uLine.msid !== 'undefined') {
  19208. // In Plan B the msid is an SSRC attribute. Also, we don't
  19209. // care about the obsolete label and mslabel attributes.
  19210. //
  19211. // Note that it is not guaranteed that the uLine will
  19212. // have an msid. recvonly channels in particular don't have
  19213. // one.
  19214. type2bl[uLine.type].sources[ssrc].msid =
  19215. uLine.msid;
  19216. }
  19217. // NOTE ssrcs in ssrc groups will share msids, as
  19218. // draft-uberti-rtcweb-plan-00 mandates.
  19219. });
  19220. }
  19221. // Add ssrc groups to the channel.
  19222. if (typeof uLine.ssrcGroups !== 'undefined' &&
  19223. Array.isArray(uLine.ssrcGroups)) {
  19224. // Create the ssrcGroups array, if it's not defined.
  19225. if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||
  19226. !Array.isArray(type2bl[uLine.type].ssrcGroups)) {
  19227. type2bl[uLine.type].ssrcGroups = [];
  19228. }
  19229. type2bl[uLine.type].ssrcGroups =
  19230. type2bl[uLine.type].ssrcGroups.concat(
  19231. uLine.ssrcGroups);
  19232. }
  19233. if (type2bl[uLine.type] === uLine) {
  19234. // Copy ICE related stuff from the principal media line.
  19235. uLine.candidates = media[0].candidates;
  19236. uLine.iceUfrag = media[0].iceUfrag;
  19237. uLine.icePwd = media[0].icePwd;
  19238. uLine.fingerprint = media[0].fingerprint;
  19239. // Plan B mids are in ['audio', 'video', 'data']
  19240. uLine.mid = uLine.type;
  19241. // Plan B doesn't support/need the bundle-only attribute.
  19242. delete uLine.bundleOnly;
  19243. // In Plan B the msid is an SSRC attribute.
  19244. delete uLine.msid;
  19245. // Used to build the group:BUNDLE value after this loop.
  19246. types.push(uLine.type);
  19247. // Add the channel to the new media array.
  19248. session.media.push(uLine);
  19249. }
  19250. });
  19251. // We regenerate the BUNDLE group with the new mids.
  19252. session.groups.some(function(group) {
  19253. if (group.type === 'BUNDLE') {
  19254. group.mids = types.join(' ');
  19255. return true;
  19256. }
  19257. });
  19258. // msid semantic
  19259. session.msidSemantic = {
  19260. semantic: 'WMS',
  19261. token: '*'
  19262. };
  19263. var resStr = transform.write(session);
  19264. return new RTCSessionDescription({
  19265. type: desc.type,
  19266. sdp: resStr
  19267. });
  19268. //#endregion
  19269. };
  19270. /**
  19271. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  19272. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  19273. * to FF.
  19274. *
  19275. * @param desc
  19276. * @returns {*}
  19277. */
  19278. Interop.prototype.toUnifiedPlan = function(desc) {
  19279. var self = this;
  19280. //#region Preliminary input validation.
  19281. if (typeof desc !== 'object' || desc === null ||
  19282. typeof desc.sdp !== 'string') {
  19283. console.warn('An empty description was passed as an argument.');
  19284. return desc;
  19285. }
  19286. var session = transform.parse(desc.sdp);
  19287. // If the SDP contains no media, there's nothing to transform.
  19288. if (typeof session.media === 'undefined' ||
  19289. !Array.isArray(session.media) || session.media.length === 0) {
  19290. console.warn('The description has no media.');
  19291. return desc;
  19292. }
  19293. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  19294. // a video, an audio and a data "channel" at most.
  19295. if (session.media.length > 3 || !session.media.every(function(m) {
  19296. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  19297. })) {
  19298. console.warn('This description does not look like Plan B.');
  19299. return desc;
  19300. }
  19301. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  19302. var mids = [];
  19303. session.media.forEach(function(m) {
  19304. mids.push(m.mid);
  19305. });
  19306. var hasBundle = false;
  19307. if (typeof session.groups !== 'undefined' &&
  19308. Array.isArray(session.groups)) {
  19309. hasBundle = session.groups.every(function(g) {
  19310. return g.type !== 'BUNDLE' ||
  19311. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  19312. });
  19313. }
  19314. if (!hasBundle) {
  19315. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  19316. " are not bundled were found.");
  19317. }
  19318. //#endregion
  19319. //#region Convert from Plan B to Unified Plan.
  19320. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  19321. // rebuild an equivalent Unified Plan offer/answer.
  19322. //
  19323. // For example, if this is a local answer (in Unified Plan style) that we
  19324. // convert to Plan B prior to handing it over to the application (the
  19325. // PeerConnection wrapper called us, for instance, after a successful
  19326. // createAnswer), we want to remember the m-line at which we've seen the
  19327. // (local) SSRC. That's because when the application wants to do call the
  19328. // SLD method, forcing us to do the inverse transformation (from Plan B to
  19329. // Unified Plan), we need to know to which m-line to assign the (local)
  19330. // SSRC. We also need to know all the other m-lines that the original
  19331. // answer had and include them in the transformed answer as well.
  19332. //
  19333. // Another example is if this is a remote offer that we convert to Plan B
  19334. // prior to giving it to the application, we want to remember the mid at
  19335. // which we've seen the (remote) SSRC.
  19336. //
  19337. // In the iteration that follows, we use the cached Unified Plan (if it
  19338. // exists) to assign mids to ssrcs.
  19339. var cached;
  19340. if (typeof this.cache[desc.type] !== 'undefined') {
  19341. cached = transform.parse(this.cache[desc.type]);
  19342. }
  19343. var recvonlySsrcs = {
  19344. audio: {},
  19345. video: {}
  19346. };
  19347. // A helper map that sends mids to m-line objects. We use it later to
  19348. // rebuild the Unified Plan style session.media array.
  19349. var mid2ul = {};
  19350. session.media.forEach(function(bLine) {
  19351. if ((typeof bLine.rtcpMux !== 'string' ||
  19352. bLine.rtcpMux !== 'rtcp-mux') &&
  19353. bLine.direction !== 'inactive') {
  19354. throw new Error("Cannot convert to Unified Plan because m-lines " +
  19355. "without the rtcp-mux attribute were found.");
  19356. }
  19357. if (bLine.type === 'application') {
  19358. mid2ul[bLine.mid] = bLine;
  19359. return;
  19360. }
  19361. // With rtcp-mux and bundle all the channels should have the same ICE
  19362. // stuff.
  19363. var sources = bLine.sources;
  19364. var ssrcGroups = bLine.ssrcGroups;
  19365. var candidates = bLine.candidates;
  19366. var iceUfrag = bLine.iceUfrag;
  19367. var icePwd = bLine.icePwd;
  19368. var fingerprint = bLine.fingerprint;
  19369. var port = bLine.port;
  19370. // We'll use the "bLine" object as a prototype for each new "mLine"
  19371. // that we create, but first we need to clean it up a bit.
  19372. delete bLine.sources;
  19373. delete bLine.ssrcGroups;
  19374. delete bLine.candidates;
  19375. delete bLine.iceUfrag;
  19376. delete bLine.icePwd;
  19377. delete bLine.fingerprint;
  19378. delete bLine.port;
  19379. delete bLine.mid;
  19380. // inverted ssrc group map
  19381. var ssrc2group = {};
  19382. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  19383. ssrcGroups.forEach(function (ssrcGroup) {
  19384. // TODO(gp) find out how to receive simulcast with FF. For the
  19385. // time being, hide it.
  19386. if (ssrcGroup.semantics === 'SIM') {
  19387. return;
  19388. }
  19389. // XXX This might brake if an SSRC is in more than one group
  19390. // for some reason.
  19391. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  19392. Array.isArray(ssrcGroup.ssrcs)) {
  19393. ssrcGroup.ssrcs.forEach(function (ssrc) {
  19394. if (typeof ssrc2group[ssrc] === 'undefined') {
  19395. ssrc2group[ssrc] = [];
  19396. }
  19397. ssrc2group[ssrc].push(ssrcGroup);
  19398. });
  19399. }
  19400. });
  19401. }
  19402. // ssrc to m-line index.
  19403. var ssrc2ml = {};
  19404. if (typeof sources === 'object') {
  19405. // Explode the Plan B channel sources with one m-line per source.
  19406. Object.keys(sources).forEach(function(ssrc) {
  19407. // The (unified) m-line for this SSRC. We either create it from
  19408. // scratch or, if it's a grouped SSRC, we re-use a related
  19409. // mline. In other words, if the source is grouped with another
  19410. // source, put the two together in the same m-line.
  19411. var uLine;
  19412. // We assume here that we are the answerer in the O/A, so any
  19413. // offers which we translate come from the remote side, while
  19414. // answers are local. So the check below is to make that we
  19415. // handle receive-only SSRCs in a special way only if they come
  19416. // from the remote side.
  19417. if (desc.type==='offer') {
  19418. // We want to detect SSRCs which are used by a remote peer
  19419. // in an m-line with direction=recvonly (i.e. they are
  19420. // being used for RTCP only).
  19421. // This information would have gotten lost if the remote
  19422. // peer used Unified Plan and their local description was
  19423. // translated to Plan B. So we use the lack of an MSID
  19424. // attribute to deduce a "receive only" SSRC.
  19425. if (!sources[ssrc].msid) {
  19426. recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];
  19427. // Receive-only SSRCs must not create new m-lines. We
  19428. // will assign them to an existing m-line later.
  19429. return;
  19430. }
  19431. }
  19432. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  19433. Array.isArray(ssrc2group[ssrc])) {
  19434. ssrc2group[ssrc].some(function (ssrcGroup) {
  19435. // ssrcGroup.ssrcs *is* an Array, no need to check
  19436. // again here.
  19437. return ssrcGroup.ssrcs.some(function (related) {
  19438. if (typeof ssrc2ml[related] === 'object') {
  19439. uLine = ssrc2ml[related];
  19440. return true;
  19441. }
  19442. });
  19443. });
  19444. }
  19445. if (typeof uLine === 'object') {
  19446. // the m-line already exists. Just add the source.
  19447. uLine.sources[ssrc] = sources[ssrc];
  19448. delete sources[ssrc].msid;
  19449. } else {
  19450. // Use the "bLine" as a prototype for the "uLine".
  19451. uLine = Object.create(bLine);
  19452. ssrc2ml[ssrc] = uLine;
  19453. if (typeof sources[ssrc].msid !== 'undefined') {
  19454. // Assign the msid of the source to the m-line. Note
  19455. // that it is not guaranteed that the source will have
  19456. // msid. In particular "recvonly" sources don't have an
  19457. // msid. Note that "recvonly" is a term only defined
  19458. // for m-lines.
  19459. uLine.msid = sources[ssrc].msid;
  19460. uLine.direction = 'sendrecv';
  19461. delete sources[ssrc].msid;
  19462. }
  19463. // We assign one SSRC per media line.
  19464. uLine.sources = {};
  19465. uLine.sources[ssrc] = sources[ssrc];
  19466. uLine.ssrcGroups = ssrc2group[ssrc];
  19467. // Use the cached Unified Plan SDP (if it exists) to assign
  19468. // SSRCs to mids.
  19469. if (typeof cached !== 'undefined' &&
  19470. typeof cached.media !== 'undefined' &&
  19471. Array.isArray(cached.media)) {
  19472. cached.media.forEach(function (m) {
  19473. if (typeof m.sources === 'object') {
  19474. Object.keys(m.sources).forEach(function (s) {
  19475. if (s === ssrc) {
  19476. uLine.mid = m.mid;
  19477. }
  19478. });
  19479. }
  19480. });
  19481. }
  19482. if (typeof uLine.mid === 'undefined') {
  19483. // If this is an SSRC that we see for the first time
  19484. // assign it a new mid. This is typically the case when
  19485. // this method is called to transform a remote
  19486. // description for the first time or when there is a
  19487. // new SSRC in the remote description because a new
  19488. // peer has joined the conference. Local SSRCs should
  19489. // have already been added to the map in the toPlanB
  19490. // method.
  19491. //
  19492. // Because FF generates answers in Unified Plan style,
  19493. // we MUST already have a cached answer with all the
  19494. // local SSRCs mapped to some m-line/mid.
  19495. if (desc.type === 'answer') {
  19496. throw new Error("An unmapped SSRC was found.");
  19497. }
  19498. uLine.mid = [bLine.type, '-', ssrc].join('');
  19499. }
  19500. // Include the candidates in the 1st media line.
  19501. uLine.candidates = candidates;
  19502. uLine.iceUfrag = iceUfrag;
  19503. uLine.icePwd = icePwd;
  19504. uLine.fingerprint = fingerprint;
  19505. uLine.port = port;
  19506. mid2ul[uLine.mid] = uLine;
  19507. }
  19508. });
  19509. }
  19510. });
  19511. // Rebuild the media array in the right order and add the missing mLines
  19512. // (missing from the Plan B SDP).
  19513. session.media = [];
  19514. mids = []; // reuse
  19515. if (desc.type === 'answer') {
  19516. // The media lines in the answer must match the media lines in the
  19517. // offer. The order is important too. Here we assume that Firefox is
  19518. // the answerer, so we merely have to use the reconstructed (unified)
  19519. // answer to update the cached (unified) answer accordingly.
  19520. //
  19521. // In the general case, one would have to use the cached (unified)
  19522. // offer to find the m-lines that are missing from the reconstructed
  19523. // answer, potentially grabbing them from the cached (unified) answer.
  19524. // One has to be careful with this approach because inactive m-lines do
  19525. // not always have an mid, making it tricky (impossible?) to find where
  19526. // exactly and which m-lines are missing from the reconstructed answer.
  19527. for (var i = 0; i < cached.media.length; i++) {
  19528. var uLine = cached.media[i];
  19529. if (typeof mid2ul[uLine.mid] === 'undefined') {
  19530. // The mid isn't in the reconstructed (unified) answer.
  19531. // This is either a (unified) m-line containing a remote
  19532. // track only, or a (unified) m-line containing a remote
  19533. // track and a local track that has been removed.
  19534. // In either case, it MUST exist in the cached
  19535. // (unified) answer.
  19536. //
  19537. // In case this is a removed local track, clean-up
  19538. // the (unified) m-line and make sure it's 'recvonly' or
  19539. // 'inactive'.
  19540. delete uLine.msid;
  19541. delete uLine.sources;
  19542. delete uLine.ssrcGroups;
  19543. if (!uLine.direction
  19544. || uLine.direction === 'sendrecv')
  19545. uLine.direction = 'recvonly';
  19546. else if (uLine.direction === 'sendonly')
  19547. uLine.direction = 'inactive';
  19548. } else {
  19549. // This is an (unified) m-line/channel that contains a local
  19550. // track (sendrecv or sendonly channel) or it's a unified
  19551. // recvonly m-line/channel. In either case, since we're
  19552. // going from PlanB -> Unified Plan this m-line MUST
  19553. // exist in the cached answer.
  19554. }
  19555. session.media.push(uLine);
  19556. if (typeof uLine.mid === 'string') {
  19557. // inactive lines don't/may not have an mid.
  19558. mids.push(uLine.mid);
  19559. }
  19560. }
  19561. } else {
  19562. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  19563. // under any circumstances. If we are no longer interested in sending a
  19564. // track, we just remove the msid and ssrc attributes and set it to
  19565. // either a=recvonly (as the reofferer, we must use recvonly if the
  19566. // other side was previously sending on the m-section, but we can also
  19567. // leave the possibility open if it wasn't previously in use), or
  19568. // a=inactive.
  19569. if (typeof cached !== 'undefined' &&
  19570. typeof cached.media !== 'undefined' &&
  19571. Array.isArray(cached.media)) {
  19572. cached.media.forEach(function(uLine) {
  19573. mids.push(uLine.mid);
  19574. if (typeof mid2ul[uLine.mid] !== 'undefined') {
  19575. session.media.push(mid2ul[uLine.mid]);
  19576. } else {
  19577. delete uLine.msid;
  19578. delete uLine.sources;
  19579. delete uLine.ssrcGroups;
  19580. if (!uLine.direction
  19581. || uLine.direction === 'sendrecv')
  19582. uLine.direction = 'recvonly';
  19583. if (!uLine.direction
  19584. || uLine.direction === 'sendonly')
  19585. uLine.direction = 'inactive';
  19586. session.media.push(uLine);
  19587. }
  19588. });
  19589. }
  19590. // Add all the remaining (new) m-lines of the transformed SDP.
  19591. Object.keys(mid2ul).forEach(function(mid) {
  19592. if (mids.indexOf(mid) === -1) {
  19593. mids.push(mid);
  19594. if (mid2ul[mid].direction === 'recvonly') {
  19595. // This is a remote recvonly channel. Add its SSRC to the
  19596. // appropriate sendrecv or sendonly channel.
  19597. // TODO(gp) what if we don't have sendrecv/sendonly
  19598. // channel?
  19599. session.media.some(function (uLine) {
  19600. if ((uLine.direction === 'sendrecv' ||
  19601. uLine.direction === 'sendonly') &&
  19602. uLine.type === mid2ul[mid].type) {
  19603. // mid2ul[mid] shouldn't have any ssrc-groups
  19604. Object.keys(mid2ul[mid].sources).forEach(
  19605. function (ssrc) {
  19606. uLine.sources[ssrc] =
  19607. mid2ul[mid].sources[ssrc];
  19608. });
  19609. return true;
  19610. }
  19611. });
  19612. } else {
  19613. session.media.push(mid2ul[mid]);
  19614. }
  19615. }
  19616. });
  19617. }
  19618. // After we have constructed the Plan Unified m-lines we can figure out
  19619. // where (in which m-line) to place the 'recvonly SSRCs'.
  19620. // Note: we assume here that we are the answerer in the O/A, so any offers
  19621. // which we translate come from the remote side, while answers are local
  19622. // (and so our last local description is cached as an 'answer').
  19623. ["audio", "video"].forEach(function (type) {
  19624. if (!session || !session.media || !Array.isArray(session.media))
  19625. return;
  19626. var idx = null;
  19627. if (Object.keys(recvonlySsrcs[type]).length > 0) {
  19628. idx = self.getFirstSendingIndexFromAnswer(type);
  19629. if (idx === null){
  19630. // If this is the first offer we receive, we don't have a
  19631. // cached answer. Assume that we will be sending media using
  19632. // the first m-line for each media type.
  19633. for (var i = 0; i < session.media.length; i++) {
  19634. if (session.media[i].type === type) {
  19635. idx = i;
  19636. break;
  19637. }
  19638. }
  19639. }
  19640. }
  19641. if (idx && session.media.length > idx) {
  19642. var mLine = session.media[idx];
  19643. Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {
  19644. if (mLine.sources && mLine.sources[ssrc]) {
  19645. console.warn("Replacing an existing SSRC.");
  19646. }
  19647. if (!mLine.sources) {
  19648. mLine.sources = {};
  19649. }
  19650. mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];
  19651. });
  19652. }
  19653. });
  19654. // We regenerate the BUNDLE group (since we regenerated the mids)
  19655. session.groups.some(function(group) {
  19656. if (group.type === 'BUNDLE') {
  19657. group.mids = mids.join(' ');
  19658. return true;
  19659. }
  19660. });
  19661. // msid semantic
  19662. session.msidSemantic = {
  19663. semantic: 'WMS',
  19664. token: '*'
  19665. };
  19666. var resStr = transform.write(session);
  19667. // Cache the transformed SDP (Unified Plan) for later re-use in this
  19668. // function.
  19669. this.cache[desc.type] = resStr;
  19670. return new RTCSessionDescription({
  19671. type: desc.type,
  19672. sdp: resStr
  19673. });
  19674. //#endregion
  19675. };
  19676. },{"./array-equals":64,"./transform":67}],67:[function(require,module,exports){
  19677. /* Copyright @ 2015 Atlassian Pty Ltd
  19678. *
  19679. * Licensed under the Apache License, Version 2.0 (the "License");
  19680. * you may not use this file except in compliance with the License.
  19681. * You may obtain a copy of the License at
  19682. *
  19683. * http://www.apache.org/licenses/LICENSE-2.0
  19684. *
  19685. * Unless required by applicable law or agreed to in writing, software
  19686. * distributed under the License is distributed on an "AS IS" BASIS,
  19687. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19688. * See the License for the specific language governing permissions and
  19689. * limitations under the License.
  19690. */
  19691. var transform = require('sdp-transform');
  19692. exports.write = function(session, opts) {
  19693. if (typeof session !== 'undefined' &&
  19694. typeof session.media !== 'undefined' &&
  19695. Array.isArray(session.media)) {
  19696. session.media.forEach(function (mLine) {
  19697. // expand sources to ssrcs
  19698. if (typeof mLine.sources !== 'undefined' &&
  19699. Object.keys(mLine.sources).length !== 0) {
  19700. mLine.ssrcs = [];
  19701. Object.keys(mLine.sources).forEach(function (ssrc) {
  19702. var source = mLine.sources[ssrc];
  19703. Object.keys(source).forEach(function (attribute) {
  19704. mLine.ssrcs.push({
  19705. id: ssrc,
  19706. attribute: attribute,
  19707. value: source[attribute]
  19708. });
  19709. });
  19710. });
  19711. delete mLine.sources;
  19712. }
  19713. // join ssrcs in ssrc groups
  19714. if (typeof mLine.ssrcGroups !== 'undefined' &&
  19715. Array.isArray(mLine.ssrcGroups)) {
  19716. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  19717. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  19718. Array.isArray(ssrcGroup.ssrcs)) {
  19719. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  19720. }
  19721. });
  19722. }
  19723. });
  19724. }
  19725. // join group mids
  19726. if (typeof session !== 'undefined' &&
  19727. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  19728. session.groups.forEach(function (g) {
  19729. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  19730. g.mids = g.mids.join(' ');
  19731. }
  19732. });
  19733. }
  19734. return transform.write(session, opts);
  19735. };
  19736. exports.parse = function(sdp) {
  19737. var session = transform.parse(sdp);
  19738. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  19739. Array.isArray(session.media)) {
  19740. session.media.forEach(function (mLine) {
  19741. // group sources attributes by ssrc
  19742. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  19743. mLine.sources = {};
  19744. mLine.ssrcs.forEach(function (ssrc) {
  19745. if (!mLine.sources[ssrc.id])
  19746. mLine.sources[ssrc.id] = {};
  19747. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  19748. });
  19749. delete mLine.ssrcs;
  19750. }
  19751. // split ssrcs in ssrc groups
  19752. if (typeof mLine.ssrcGroups !== 'undefined' &&
  19753. Array.isArray(mLine.ssrcGroups)) {
  19754. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  19755. if (typeof ssrcGroup.ssrcs === 'string') {
  19756. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  19757. }
  19758. });
  19759. }
  19760. });
  19761. }
  19762. // split group mids
  19763. if (typeof session !== 'undefined' &&
  19764. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  19765. session.groups.forEach(function (g) {
  19766. if (typeof g.mids === 'string') {
  19767. g.mids = g.mids.split(' ');
  19768. }
  19769. });
  19770. }
  19771. return session;
  19772. };
  19773. },{"sdp-transform":69}],68:[function(require,module,exports){
  19774. var grammar = module.exports = {
  19775. v: [{
  19776. name: 'version',
  19777. reg: /^(\d*)$/
  19778. }],
  19779. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  19780. // NB: sessionId will be a String in most cases because it is huge
  19781. name: 'origin',
  19782. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  19783. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  19784. format: "%s %s %d %s IP%d %s"
  19785. }],
  19786. // default parsing of these only (though some of these feel outdated)
  19787. s: [{ name: 'name' }],
  19788. i: [{ name: 'description' }],
  19789. u: [{ name: 'uri' }],
  19790. e: [{ name: 'email' }],
  19791. p: [{ name: 'phone' }],
  19792. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  19793. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  19794. //k: [{}], // outdated thing ignored
  19795. t: [{ //t=0 0
  19796. name: 'timing',
  19797. reg: /^(\d*) (\d*)/,
  19798. names: ['start', 'stop'],
  19799. format: "%d %d"
  19800. }],
  19801. c: [{ //c=IN IP4 10.47.197.26
  19802. name: 'connection',
  19803. reg: /^IN IP(\d) (\S*)/,
  19804. names: ['version', 'ip'],
  19805. format: "IN IP%d %s"
  19806. }],
  19807. b: [{ //b=AS:4000
  19808. push: 'bandwidth',
  19809. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  19810. names: ['type', 'limit'],
  19811. format: "%s:%s"
  19812. }],
  19813. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  19814. // NB: special - pushes to session
  19815. // TODO: rtp/fmtp should be filtered by the payloads found here?
  19816. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  19817. names: ['type', 'port', 'protocol', 'payloads'],
  19818. format: "%s %d %s %s"
  19819. }],
  19820. a: [
  19821. { //a=rtpmap:110 opus/48000/2
  19822. push: 'rtp',
  19823. reg: /^rtpmap:(\d*) ([\w\-]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,
  19824. names: ['payload', 'codec', 'rate', 'encoding'],
  19825. format: function (o) {
  19826. return (o.encoding) ?
  19827. "rtpmap:%d %s/%s/%s":
  19828. o.rate ?
  19829. "rtpmap:%d %s/%s":
  19830. "rtpmap:%d %s";
  19831. }
  19832. },
  19833. {
  19834. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  19835. //a=fmtp:111 minptime=10; useinbandfec=1
  19836. push: 'fmtp',
  19837. reg: /^fmtp:(\d*) ([\S| ]*)/,
  19838. names: ['payload', 'config'],
  19839. format: "fmtp:%d %s"
  19840. },
  19841. { //a=control:streamid=0
  19842. name: 'control',
  19843. reg: /^control:(.*)/,
  19844. format: "control:%s"
  19845. },
  19846. { //a=rtcp:65179 IN IP4 193.84.77.194
  19847. name: 'rtcp',
  19848. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  19849. names: ['port', 'netType', 'ipVer', 'address'],
  19850. format: function (o) {
  19851. return (o.address != null) ?
  19852. "rtcp:%d %s IP%d %s":
  19853. "rtcp:%d";
  19854. }
  19855. },
  19856. { //a=rtcp-fb:98 trr-int 100
  19857. push: 'rtcpFbTrrInt',
  19858. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  19859. names: ['payload', 'value'],
  19860. format: "rtcp-fb:%d trr-int %d"
  19861. },
  19862. { //a=rtcp-fb:98 nack rpsi
  19863. push: 'rtcpFb',
  19864. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  19865. names: ['payload', 'type', 'subtype'],
  19866. format: function (o) {
  19867. return (o.subtype != null) ?
  19868. "rtcp-fb:%s %s %s":
  19869. "rtcp-fb:%s %s";
  19870. }
  19871. },
  19872. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  19873. //a=extmap:1/recvonly URI-gps-string
  19874. push: 'ext',
  19875. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  19876. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  19877. format: function (o) {
  19878. return (o.config != null) ?
  19879. "extmap:%s %s %s":
  19880. "extmap:%s %s";
  19881. }
  19882. },
  19883. {
  19884. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  19885. push: 'crypto',
  19886. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  19887. names: ['id', 'suite', 'config', 'sessionConfig'],
  19888. format: function (o) {
  19889. return (o.sessionConfig != null) ?
  19890. "crypto:%d %s %s %s":
  19891. "crypto:%d %s %s";
  19892. }
  19893. },
  19894. { //a=setup:actpass
  19895. name: 'setup',
  19896. reg: /^setup:(\w*)/,
  19897. format: "setup:%s"
  19898. },
  19899. { //a=mid:1
  19900. name: 'mid',
  19901. reg: /^mid:([^\s]*)/,
  19902. format: "mid:%s"
  19903. },
  19904. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  19905. name: 'msid',
  19906. reg: /^msid:(.*)/,
  19907. format: "msid:%s"
  19908. },
  19909. { //a=ptime:20
  19910. name: 'ptime',
  19911. reg: /^ptime:(\d*)/,
  19912. format: "ptime:%d"
  19913. },
  19914. { //a=maxptime:60
  19915. name: 'maxptime',
  19916. reg: /^maxptime:(\d*)/,
  19917. format: "maxptime:%d"
  19918. },
  19919. { //a=sendrecv
  19920. name: 'direction',
  19921. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  19922. },
  19923. { //a=ice-lite
  19924. name: 'icelite',
  19925. reg: /^(ice-lite)/
  19926. },
  19927. { //a=ice-ufrag:F7gI
  19928. name: 'iceUfrag',
  19929. reg: /^ice-ufrag:(\S*)/,
  19930. format: "ice-ufrag:%s"
  19931. },
  19932. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  19933. name: 'icePwd',
  19934. reg: /^ice-pwd:(\S*)/,
  19935. format: "ice-pwd:%s"
  19936. },
  19937. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  19938. name: 'fingerprint',
  19939. reg: /^fingerprint:(\S*) (\S*)/,
  19940. names: ['type', 'hash'],
  19941. format: "fingerprint:%s %s"
  19942. },
  19943. {
  19944. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  19945. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  19946. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  19947. //a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0
  19948. //a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0
  19949. push:'candidates',
  19950. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,
  19951. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation'],
  19952. format: function (o) {
  19953. var str = "candidate:%s %d %s %d %s %d typ %s";
  19954. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  19955. // NB: candidate has three optional chunks, so %void middles one if it's missing
  19956. str += (o.tcptype != null) ? " tcptype %s" : "%v";
  19957. if (o.generation != null) {
  19958. str += " generation %d";
  19959. }
  19960. return str;
  19961. }
  19962. },
  19963. { //a=end-of-candidates (keep after the candidates line for readability)
  19964. name: 'endOfCandidates',
  19965. reg: /^(end-of-candidates)/
  19966. },
  19967. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  19968. name: 'remoteCandidates',
  19969. reg: /^remote-candidates:(.*)/,
  19970. format: "remote-candidates:%s"
  19971. },
  19972. { //a=ice-options:google-ice
  19973. name: 'iceOptions',
  19974. reg: /^ice-options:(\S*)/,
  19975. format: "ice-options:%s"
  19976. },
  19977. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  19978. push: "ssrcs",
  19979. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  19980. names: ['id', 'attribute', 'value'],
  19981. format: "ssrc:%d %s:%s"
  19982. },
  19983. { //a=ssrc-group:FEC 1 2
  19984. push: "ssrcGroups",
  19985. reg: /^ssrc-group:(\w*) (.*)/,
  19986. names: ['semantics', 'ssrcs'],
  19987. format: "ssrc-group:%s %s"
  19988. },
  19989. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  19990. name: "msidSemantic",
  19991. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  19992. names: ['semantic', 'token'],
  19993. format: "msid-semantic: %s %s" // space after ":" is not accidental
  19994. },
  19995. { //a=group:BUNDLE audio video
  19996. push: 'groups',
  19997. reg: /^group:(\w*) (.*)/,
  19998. names: ['type', 'mids'],
  19999. format: "group:%s %s"
  20000. },
  20001. { //a=rtcp-mux
  20002. name: 'rtcpMux',
  20003. reg: /^(rtcp-mux)/
  20004. },
  20005. { //a=rtcp-rsize
  20006. name: 'rtcpRsize',
  20007. reg: /^(rtcp-rsize)/
  20008. },
  20009. { // any a= that we don't understand is kepts verbatim on media.invalid
  20010. push: 'invalid',
  20011. names: ["value"]
  20012. }
  20013. ]
  20014. };
  20015. // set sensible defaults to avoid polluting the grammar with boring details
  20016. Object.keys(grammar).forEach(function (key) {
  20017. var objs = grammar[key];
  20018. objs.forEach(function (obj) {
  20019. if (!obj.reg) {
  20020. obj.reg = /(.*)/;
  20021. }
  20022. if (!obj.format) {
  20023. obj.format = "%s";
  20024. }
  20025. });
  20026. });
  20027. },{}],69:[function(require,module,exports){
  20028. var parser = require('./parser');
  20029. var writer = require('./writer');
  20030. exports.write = writer;
  20031. exports.parse = parser.parse;
  20032. exports.parseFmtpConfig = parser.parseFmtpConfig;
  20033. exports.parsePayloads = parser.parsePayloads;
  20034. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  20035. },{"./parser":70,"./writer":71}],70:[function(require,module,exports){
  20036. var toIntIfInt = function (v) {
  20037. return String(Number(v)) === v ? Number(v) : v;
  20038. };
  20039. var attachProperties = function (match, location, names, rawName) {
  20040. if (rawName && !names) {
  20041. location[rawName] = toIntIfInt(match[1]);
  20042. }
  20043. else {
  20044. for (var i = 0; i < names.length; i += 1) {
  20045. if (match[i+1] != null) {
  20046. location[names[i]] = toIntIfInt(match[i+1]);
  20047. }
  20048. }
  20049. }
  20050. };
  20051. var parseReg = function (obj, location, content) {
  20052. var needsBlank = obj.name && obj.names;
  20053. if (obj.push && !location[obj.push]) {
  20054. location[obj.push] = [];
  20055. }
  20056. else if (needsBlank && !location[obj.name]) {
  20057. location[obj.name] = {};
  20058. }
  20059. var keyLocation = obj.push ?
  20060. {} : // blank object that will be pushed
  20061. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  20062. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  20063. if (obj.push) {
  20064. location[obj.push].push(keyLocation);
  20065. }
  20066. };
  20067. var grammar = require('./grammar');
  20068. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  20069. exports.parse = function (sdp) {
  20070. var session = {}
  20071. , media = []
  20072. , location = session; // points at where properties go under (one of the above)
  20073. // parse lines we understand
  20074. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  20075. var type = l[0];
  20076. var content = l.slice(2);
  20077. if (type === 'm') {
  20078. media.push({rtp: [], fmtp: []});
  20079. location = media[media.length-1]; // point at latest media line
  20080. }
  20081. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  20082. var obj = grammar[type][j];
  20083. if (obj.reg.test(content)) {
  20084. return parseReg(obj, location, content);
  20085. }
  20086. }
  20087. });
  20088. session.media = media; // link it up
  20089. return session;
  20090. };
  20091. var fmtpReducer = function (acc, expr) {
  20092. var s = expr.split('=');
  20093. if (s.length === 2) {
  20094. acc[s[0]] = toIntIfInt(s[1]);
  20095. }
  20096. return acc;
  20097. };
  20098. exports.parseFmtpConfig = function (str) {
  20099. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  20100. };
  20101. exports.parsePayloads = function (str) {
  20102. return str.split(' ').map(Number);
  20103. };
  20104. exports.parseRemoteCandidates = function (str) {
  20105. var candidates = [];
  20106. var parts = str.split(' ').map(toIntIfInt);
  20107. for (var i = 0; i < parts.length; i += 3) {
  20108. candidates.push({
  20109. component: parts[i],
  20110. ip: parts[i + 1],
  20111. port: parts[i + 2]
  20112. });
  20113. }
  20114. return candidates;
  20115. };
  20116. },{"./grammar":68}],71:[function(require,module,exports){
  20117. var grammar = require('./grammar');
  20118. // customized util.format - discards excess arguments and can void middle ones
  20119. var formatRegExp = /%[sdv%]/g;
  20120. var format = function (formatStr) {
  20121. var i = 1;
  20122. var args = arguments;
  20123. var len = args.length;
  20124. return formatStr.replace(formatRegExp, function (x) {
  20125. if (i >= len) {
  20126. return x; // missing argument
  20127. }
  20128. var arg = args[i];
  20129. i += 1;
  20130. switch (x) {
  20131. case '%%':
  20132. return '%';
  20133. case '%s':
  20134. return String(arg);
  20135. case '%d':
  20136. return Number(arg);
  20137. case '%v':
  20138. return '';
  20139. }
  20140. });
  20141. // NB: we discard excess arguments - they are typically undefined from makeLine
  20142. };
  20143. var makeLine = function (type, obj, location) {
  20144. var str = obj.format instanceof Function ?
  20145. (obj.format(obj.push ? location : location[obj.name])) :
  20146. obj.format;
  20147. var args = [type + '=' + str];
  20148. if (obj.names) {
  20149. for (var i = 0; i < obj.names.length; i += 1) {
  20150. var n = obj.names[i];
  20151. if (obj.name) {
  20152. args.push(location[obj.name][n]);
  20153. }
  20154. else { // for mLine and push attributes
  20155. args.push(location[obj.names[i]]);
  20156. }
  20157. }
  20158. }
  20159. else {
  20160. args.push(location[obj.name]);
  20161. }
  20162. return format.apply(null, args);
  20163. };
  20164. // RFC specified order
  20165. // TODO: extend this with all the rest
  20166. var defaultOuterOrder = [
  20167. 'v', 'o', 's', 'i',
  20168. 'u', 'e', 'p', 'c',
  20169. 'b', 't', 'r', 'z', 'a'
  20170. ];
  20171. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  20172. module.exports = function (session, opts) {
  20173. opts = opts || {};
  20174. // ensure certain properties exist
  20175. if (session.version == null) {
  20176. session.version = 0; // "v=0" must be there (only defined version atm)
  20177. }
  20178. if (session.name == null) {
  20179. session.name = " "; // "s= " must be there if no meaningful name set
  20180. }
  20181. session.media.forEach(function (mLine) {
  20182. if (mLine.payloads == null) {
  20183. mLine.payloads = "";
  20184. }
  20185. });
  20186. var outerOrder = opts.outerOrder || defaultOuterOrder;
  20187. var innerOrder = opts.innerOrder || defaultInnerOrder;
  20188. var sdp = [];
  20189. // loop through outerOrder for matching properties on session
  20190. outerOrder.forEach(function (type) {
  20191. grammar[type].forEach(function (obj) {
  20192. if (obj.name in session && session[obj.name] != null) {
  20193. sdp.push(makeLine(type, obj, session));
  20194. }
  20195. else if (obj.push in session && session[obj.push] != null) {
  20196. session[obj.push].forEach(function (el) {
  20197. sdp.push(makeLine(type, obj, el));
  20198. });
  20199. }
  20200. });
  20201. });
  20202. // then for each media line, follow the innerOrder
  20203. session.media.forEach(function (mLine) {
  20204. sdp.push(makeLine('m', grammar.m[0], mLine));
  20205. innerOrder.forEach(function (type) {
  20206. grammar[type].forEach(function (obj) {
  20207. if (obj.name in mLine && mLine[obj.name] != null) {
  20208. sdp.push(makeLine(type, obj, mLine));
  20209. }
  20210. else if (obj.push in mLine && mLine[obj.push] != null) {
  20211. mLine[obj.push].forEach(function (el) {
  20212. sdp.push(makeLine(type, obj, el));
  20213. });
  20214. }
  20215. });
  20216. });
  20217. });
  20218. return sdp.join('\r\n') + '\r\n';
  20219. };
  20220. },{"./grammar":68}],72:[function(require,module,exports){
  20221. /* Copyright @ 2015 Atlassian Pty Ltd
  20222. *
  20223. * Licensed under the Apache License, Version 2.0 (the "License");
  20224. * you may not use this file except in compliance with the License.
  20225. * You may obtain a copy of the License at
  20226. *
  20227. * http://www.apache.org/licenses/LICENSE-2.0
  20228. *
  20229. * Unless required by applicable law or agreed to in writing, software
  20230. * distributed under the License is distributed on an "AS IS" BASIS,
  20231. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20232. * See the License for the specific language governing permissions and
  20233. * limitations under the License.
  20234. */
  20235. var transform = require('sdp-transform');
  20236. var transformUtils = require('./transform-utils');
  20237. var parseSsrcs = transformUtils.parseSsrcs;
  20238. var writeSsrcs = transformUtils.writeSsrcs;
  20239. //region Constants
  20240. var DEFAULT_NUM_OF_LAYERS = 3;
  20241. //endregion
  20242. //region Ctor
  20243. function Simulcast(options) {
  20244. this.options = options ? options : {};
  20245. if (!this.options.numOfLayers) {
  20246. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  20247. }
  20248. this.layers = [];
  20249. }
  20250. //endregion
  20251. //region Stateless private utility functions
  20252. /**
  20253. * Returns a random integer between min (included) and max (excluded)
  20254. * Using Math.round() gives a non-uniform distribution!
  20255. * @returns {number}
  20256. */
  20257. function generateSSRC() {
  20258. var min = 0, max = 0xffffffff;
  20259. return Math.floor(Math.random() * (max - min)) + min;
  20260. };
  20261. function processVideo(session, action) {
  20262. if (session == null || !Array.isArray(session.media)) {
  20263. return;
  20264. }
  20265. session.media.forEach(function (mLine) {
  20266. if (mLine.type === 'video') {
  20267. action(mLine);
  20268. }
  20269. });
  20270. }
  20271. function validateDescription(desc)
  20272. {
  20273. return desc && desc != null
  20274. && desc.type && desc.type != ''
  20275. && desc.sdp && desc.sdp != '';
  20276. }
  20277. function explodeRemoteSimulcast(mLine) {
  20278. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  20279. return;
  20280. }
  20281. var sources = parseSsrcs(mLine);
  20282. var order = [];
  20283. // Find the SIM group and explode its sources.
  20284. var j = mLine.ssrcGroups.length;
  20285. while (j--) {
  20286. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  20287. continue;
  20288. }
  20289. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  20290. for (var i = 0; i < simulcastSsrcs.length; i++) {
  20291. var ssrc = simulcastSsrcs[i];
  20292. order.push(ssrc);
  20293. var parts = sources[ssrc].msid.split(' ');
  20294. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  20295. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  20296. // Remove all the groups that this SSRC participates in.
  20297. mLine.ssrcGroups.forEach(function (relatedGroup) {
  20298. if (relatedGroup.semantics === 'SIM') {
  20299. return;
  20300. }
  20301. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  20302. if (relatedSsrcs.indexOf(ssrc) === -1) {
  20303. return;
  20304. }
  20305. // Nuke all the related SSRCs.
  20306. relatedSsrcs.forEach(function (relatedSSRC) {
  20307. sources[relatedSSRC].msid = sources[ssrc].msid;
  20308. sources[relatedSSRC].cname = sources[ssrc].cname;
  20309. if (relatedSSRC !== ssrc) {
  20310. order.push(relatedSSRC);
  20311. }
  20312. });
  20313. // Schedule the related group for nuking.
  20314. })
  20315. }
  20316. mLine.ssrcs = writeSsrcs(sources, order);
  20317. mLine.ssrcGroups.splice(j, 1);
  20318. };
  20319. }
  20320. function implodeRemoteSimulcast(mLine) {
  20321. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  20322. console.info('Halt: There are no SSRC groups in the remote ' +
  20323. 'description.');
  20324. return;
  20325. }
  20326. var sources = parseSsrcs(mLine);
  20327. // Find the SIM group and nuke it.
  20328. mLine.ssrcGroups.forEach(function (simulcastGroup) {
  20329. if (simulcastGroup.semantics !== 'SIM') {
  20330. return;
  20331. }
  20332. console.info("Imploding SIM group: " + simulcastGroup.ssrcs);
  20333. // Schedule the SIM group for nuking.
  20334. simulcastGroup.nuke = true;
  20335. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  20336. // Nuke all the higher layer SSRCs.
  20337. for (var i = 1; i < simulcastSsrcs.length; i++) {
  20338. var ssrc = simulcastSsrcs[i];
  20339. delete sources[ssrc];
  20340. // Remove all the groups that this SSRC participates in.
  20341. mLine.ssrcGroups.forEach(function (relatedGroup) {
  20342. if (relatedGroup.semantics === 'SIM') {
  20343. return;
  20344. }
  20345. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  20346. if (relatedSsrcs.indexOf(ssrc) === -1) {
  20347. return;
  20348. }
  20349. // Nuke all the related SSRCs.
  20350. relatedSsrcs.forEach(function (relatedSSRC) {
  20351. delete sources[relatedSSRC];
  20352. });
  20353. // Schedule the related group for nuking.
  20354. relatedGroup.nuke = true;
  20355. })
  20356. }
  20357. return;
  20358. });
  20359. mLine.ssrcs = writeSsrcs(sources);
  20360. // Nuke all the scheduled groups.
  20361. var i = mLine.ssrcGroups.length;
  20362. while (i--) {
  20363. if (mLine.ssrcGroups[i].nuke) {
  20364. mLine.ssrcGroups.splice(i, 1);
  20365. }
  20366. }
  20367. }
  20368. function removeGoogConference(mLine) {
  20369. if (!mLine || !Array.isArray(mLine.invalid)) {
  20370. return;
  20371. }
  20372. var i = mLine.invalid.length;
  20373. while (i--) {
  20374. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  20375. mLine.invalid.splice(i, 1);
  20376. }
  20377. }
  20378. }
  20379. function assertGoogConference(mLine) {
  20380. if (!mLine) {
  20381. return;
  20382. }
  20383. if (!Array.isArray(mLine.invalid)) {
  20384. mLine.invalid = [];
  20385. }
  20386. if (!mLine.invalid.some(
  20387. function (i) { return i.value === 'x-google-flag:conference' })) {
  20388. mLine.invalid.push({'value': 'x-google-flag:conference'});
  20389. }
  20390. }
  20391. //endregion
  20392. //region "Private" functions
  20393. /**
  20394. *
  20395. * @param mLine
  20396. * @private
  20397. */
  20398. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  20399. if (!mLine || mLine.type !== 'video') {
  20400. return;
  20401. }
  20402. var sources = parseSsrcs(mLine);
  20403. if (Object.keys(sources).length === 0) {
  20404. // no sources, disable simulcast.
  20405. if (this.layers.length !== 0) {
  20406. this.layers = [];
  20407. }
  20408. return;
  20409. }
  20410. // find the base layer (we'll reuse its msid and cname).
  20411. var baseLayerSSRC = Object.keys(sources)[0];
  20412. var baseLayer = sources[baseLayerSSRC];
  20413. // todo(gp) handle screen sharing.
  20414. // check if base CNAME has changed and reinitialise layers.
  20415. if (this.layers.length > 0
  20416. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  20417. this.layers = [];
  20418. }
  20419. // (re)initialise layers
  20420. if (this.layers.length < 1) {
  20421. // first push the base layer.
  20422. this.layers.push({
  20423. ssrc: baseLayerSSRC,
  20424. msid: baseLayer.msid,
  20425. cname: baseLayer.cname
  20426. });
  20427. var rtx = false; // RFC 4588
  20428. if (Array.isArray(mLine.rtp)) {
  20429. rtx = mLine.rtp.some(
  20430. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  20431. }
  20432. if (rtx) {
  20433. this.layers[0].rtx = generateSSRC();
  20434. }
  20435. // now push additional layers.
  20436. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  20437. var layer = { ssrc: generateSSRC() };
  20438. if (rtx) {
  20439. layer.rtx = generateSSRC();
  20440. }
  20441. this.layers.push(layer);
  20442. }
  20443. }
  20444. };
  20445. /**
  20446. *
  20447. * @param mLine
  20448. * @private
  20449. */
  20450. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  20451. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  20452. var sources = {};
  20453. var msid = this.layers[0].msid;
  20454. var cname = this.layers[0].cname;
  20455. var simulcastSsrcs = [];
  20456. var ssrcGroups = [];
  20457. for (var i = 0; i < this.layers.length; i++) {
  20458. var layer = this.layers[i];
  20459. sources[layer.ssrc] = { msid: msid, cname: cname };
  20460. simulcastSsrcs.push(layer.ssrc);
  20461. if (layer.rtx) {
  20462. sources[layer.rtx] = {
  20463. msid: msid,
  20464. cname: cname
  20465. }
  20466. ssrcGroups.push({
  20467. semantics: 'FID',
  20468. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  20469. });
  20470. }
  20471. }
  20472. ssrcGroups.push({
  20473. semantics: 'SIM',
  20474. ssrcs: simulcastSsrcs.join(' ')
  20475. });
  20476. mLine.ssrcGroups = ssrcGroups;
  20477. mLine.ssrcs = writeSsrcs(sources);
  20478. }
  20479. }
  20480. //endregion
  20481. //region "Public" functions
  20482. Simulcast.prototype.isSupported = function () {
  20483. return window.chrome;
  20484. // TODO this needs improvements. For example I doubt that Chrome in Android
  20485. // has simulcast support. Also, only recent versions of Chromium have native
  20486. // simulcast support.
  20487. }
  20488. /**
  20489. *
  20490. * @param desc
  20491. * @returns {RTCSessionDescription}
  20492. */
  20493. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  20494. if (!validateDescription(desc)) {
  20495. return desc;
  20496. }
  20497. var session = transform.parse(desc.sdp);
  20498. var self = this;
  20499. processVideo(session, function (mLine) {
  20500. // Handle simulcast reception.
  20501. if (self.options.explodeRemoteSimulcast) {
  20502. explodeRemoteSimulcast(mLine);
  20503. } else {
  20504. implodeRemoteSimulcast(mLine);
  20505. }
  20506. // If native simulcast is enabled, we must append the x-goog-conference
  20507. // attribute to the SDP.
  20508. if (self.layers.length < 1) {
  20509. removeGoogConference(mLine);
  20510. } else {
  20511. assertGoogConference(mLine);
  20512. }
  20513. });
  20514. return new RTCSessionDescription({
  20515. type: desc.type,
  20516. sdp: transform.write(session)
  20517. });
  20518. };
  20519. /**
  20520. *
  20521. * @param desc
  20522. * @returns {RTCSessionDescription}
  20523. */
  20524. Simulcast.prototype.mungeLocalDescription = function (desc) {
  20525. if (!validateDescription(desc) || !this.isSupported()) {
  20526. return desc;
  20527. }
  20528. var session = transform.parse(desc.sdp);
  20529. var self = this;
  20530. processVideo(session, function (mLine) {
  20531. // Initialize native simulcast layers, if not already done.
  20532. self._maybeInitializeLayers(mLine);
  20533. // Update the SDP with the simulcast layers.
  20534. self._restoreSimulcastView(mLine);
  20535. });
  20536. return new RTCSessionDescription({
  20537. type: desc.type,
  20538. sdp: transform.write(session)
  20539. });
  20540. };
  20541. //endregion
  20542. module.exports = Simulcast;
  20543. },{"./transform-utils":73,"sdp-transform":75}],73:[function(require,module,exports){
  20544. /* Copyright @ 2015 Atlassian Pty Ltd
  20545. *
  20546. * Licensed under the Apache License, Version 2.0 (the "License");
  20547. * you may not use this file except in compliance with the License.
  20548. * You may obtain a copy of the License at
  20549. *
  20550. * http://www.apache.org/licenses/LICENSE-2.0
  20551. *
  20552. * Unless required by applicable law or agreed to in writing, software
  20553. * distributed under the License is distributed on an "AS IS" BASIS,
  20554. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20555. * See the License for the specific language governing permissions and
  20556. * limitations under the License.
  20557. */
  20558. exports.writeSsrcs = function(sources, order) {
  20559. var ssrcs = [];
  20560. // expand sources to ssrcs
  20561. if (typeof sources !== 'undefined' &&
  20562. Object.keys(sources).length !== 0) {
  20563. if (Array.isArray(order)) {
  20564. for (var i = 0; i < order.length; i++) {
  20565. var ssrc = order[i];
  20566. var source = sources[ssrc];
  20567. Object.keys(source).forEach(function (attribute) {
  20568. ssrcs.push({
  20569. id: ssrc,
  20570. attribute: attribute,
  20571. value: source[attribute]
  20572. });
  20573. });
  20574. }
  20575. } else {
  20576. Object.keys(sources).forEach(function (ssrc) {
  20577. var source = sources[ssrc];
  20578. Object.keys(source).forEach(function (attribute) {
  20579. ssrcs.push({
  20580. id: ssrc,
  20581. attribute: attribute,
  20582. value: source[attribute]
  20583. });
  20584. });
  20585. });
  20586. }
  20587. }
  20588. return ssrcs;
  20589. };
  20590. exports.parseSsrcs = function (mLine) {
  20591. var sources = {};
  20592. // group sources attributes by ssrc.
  20593. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  20594. mLine.ssrcs.forEach(function (ssrc) {
  20595. if (!sources[ssrc.id])
  20596. sources[ssrc.id] = {};
  20597. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  20598. });
  20599. }
  20600. return sources;
  20601. };
  20602. },{}],74:[function(require,module,exports){
  20603. arguments[4][68][0].apply(exports,arguments)
  20604. },{"dup":68}],75:[function(require,module,exports){
  20605. arguments[4][69][0].apply(exports,arguments)
  20606. },{"./parser":76,"./writer":77,"dup":69}],76:[function(require,module,exports){
  20607. arguments[4][70][0].apply(exports,arguments)
  20608. },{"./grammar":74,"dup":70}],77:[function(require,module,exports){
  20609. arguments[4][71][0].apply(exports,arguments)
  20610. },{"./grammar":74,"dup":71}],78:[function(require,module,exports){
  20611. var MediaStreamType = {
  20612. VIDEO_TYPE: "Video",
  20613. AUDIO_TYPE: "Audio"
  20614. };
  20615. module.exports = MediaStreamType;
  20616. },{}],79:[function(require,module,exports){
  20617. var RTCEvents = {
  20618. RTC_READY: "rtc.ready",
  20619. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  20620. LASTN_CHANGED: "rtc.lastn_changed",
  20621. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  20622. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  20623. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  20624. };
  20625. module.exports = RTCEvents;
  20626. },{}],80:[function(require,module,exports){
  20627. var Resolutions = {
  20628. "1080": {
  20629. width: 1920,
  20630. height: 1080,
  20631. order: 7
  20632. },
  20633. "fullhd": {
  20634. width: 1920,
  20635. height: 1080,
  20636. order: 7
  20637. },
  20638. "720": {
  20639. width: 1280,
  20640. height: 720,
  20641. order: 6
  20642. },
  20643. "hd": {
  20644. width: 1280,
  20645. height: 720,
  20646. order: 6
  20647. },
  20648. "960": {
  20649. width: 960,
  20650. height: 720,
  20651. order: 5
  20652. },
  20653. "640": {
  20654. width: 640,
  20655. height: 480,
  20656. order: 4
  20657. },
  20658. "vga": {
  20659. width: 640,
  20660. height: 480,
  20661. order: 4
  20662. },
  20663. "360": {
  20664. width: 640,
  20665. height: 360,
  20666. order: 3
  20667. },
  20668. "320": {
  20669. width: 320,
  20670. height: 240,
  20671. order: 2
  20672. },
  20673. "180": {
  20674. width: 320,
  20675. height: 180,
  20676. order: 1
  20677. }
  20678. };
  20679. module.exports = Resolutions;
  20680. },{}],81:[function(require,module,exports){
  20681. var AuthenticationEvents = {
  20682. /**
  20683. * Event callback arguments:
  20684. * function(authenticationEnabled, userIdentity)
  20685. * authenticationEnabled - indicates whether authentication has been enabled
  20686. * in this session
  20687. * userIdentity - if user has been logged in then it contains user name. If
  20688. * contains 'null' or 'undefined' then user is not logged in.
  20689. */
  20690. IDENTITY_UPDATED: "authentication.identity_updated"
  20691. };
  20692. module.exports = AuthenticationEvents;
  20693. },{}],82:[function(require,module,exports){
  20694. var DesktopSharingEventTypes = {
  20695. /**
  20696. * An event which indicates that the jidesha extension for Firefox is
  20697. * needed to proceed with screen sharing, and that it is not installed.
  20698. */
  20699. FIREFOX_EXTENSION_NEEDED: "ds.firefox_extension_needed"
  20700. };
  20701. module.exports = DesktopSharingEventTypes;
  20702. },{}],83:[function(require,module,exports){
  20703. module.exports = {
  20704. /**
  20705. * An event carrying connection statistics.
  20706. */
  20707. CONNECTION_STATS: "statistics.connectionstats",
  20708. /**
  20709. * FIXME: needs documentation.
  20710. */
  20711. AUDIO_LEVEL: "statistics.audioLevel",
  20712. /**
  20713. * FIXME: needs documentation.
  20714. */
  20715. STOP: "statistics.stop"
  20716. };
  20717. },{}],84:[function(require,module,exports){
  20718. var Constants = {
  20719. LOCAL_JID: 'local'
  20720. };
  20721. module.exports = Constants;
  20722. },{}],85:[function(require,module,exports){
  20723. var XMPPEvents = {
  20724. // Designates an event indicating that the connection to the XMPP server
  20725. // failed.
  20726. CONNECTION_FAILED: "xmpp.connection.failed",
  20727. // Designates an event indicating that the media (ICE) connection was
  20728. // interrupted. This should go to the RTC module.
  20729. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  20730. // Designates an event indicating that the media (ICE) connection was
  20731. // restored. This should go to the RTC module.
  20732. CONNECTION_RESTORED: "xmpp.connection.restored",
  20733. // Designates an event indicating that an offer (e.g. Jingle
  20734. // session-initiate) was received.
  20735. CALL_INCOMING: "xmpp.callincoming.jingle",
  20736. // Designates an event indicating that we were kicked from the XMPP MUC.
  20737. KICKED: "xmpp.kicked",
  20738. // Designates an event indicating that the userID for a specific JID has
  20739. // changed.
  20740. // Note: currently this event fires every time we receive presence from
  20741. // someone (regardless of whether or not the "userID" changed).
  20742. USER_ID_CHANGED: "xmpp.user_id_changed",
  20743. // Designates an event indicating that we have joined the XMPP MUC.
  20744. MUC_JOINED: "xmpp.muc_joined",
  20745. // Designates an event indicating that a participant joined the XMPP MUC.
  20746. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  20747. // Designates an event indicating that a participant left the XMPP MUC.
  20748. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  20749. // Designates an event indicating that the MUC role of a participant has
  20750. // changed.
  20751. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  20752. // Designates an event indicating that the XMPP MUC was destroyed.
  20753. MUC_DESTROYED: "xmpp.muc_destroyed",
  20754. // Designates an event indicating that the display name of a participant
  20755. // has changed.
  20756. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  20757. // Designates an event indicating that we received statistics from a
  20758. // participant in the MUC.
  20759. REMOTE_STATS: "xmpp.remote_stats",
  20760. // Designates an event indicating that our role in the XMPP MUC has changed.
  20761. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  20762. // Designates an event indicating that the subject of the XMPP MUC has
  20763. // changed.
  20764. SUBJECT_CHANGED: "xmpp.subject_changed",
  20765. // Designates an event indicating that an XMPP message in the MUC was
  20766. // received.
  20767. MESSAGE_RECEIVED: "xmpp.message_received",
  20768. // Designates an event indicating that we sent an XMPP message to the MUC.
  20769. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  20770. // Designates an event indicating that the video type (e.g. 'camera' or
  20771. // 'screen') for a participant has changed.
  20772. // Note: currently this event fires every time we receive presence from
  20773. // someone (regardless of whether or not the "video type" changed).
  20774. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  20775. // Designates an event indicating that a participant in the XMPP MUC has
  20776. // advertised that they have audio muted (or unmuted).
  20777. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  20778. // Designates an event indicating that a participant in the XMPP MUC has
  20779. // advertised that they have video muted (or unmuted).
  20780. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  20781. // Designates an event indicating that the focus has asked us to mute our
  20782. // audio.
  20783. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  20784. // Designates an event indicating that we should join the conference with
  20785. // audio and/or video muted.
  20786. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  20787. // Designates an event indicating that a remote participant's available
  20788. // devices (whether he supports a audio and/or video) changed.
  20789. // Note: currently this event fires every time we receive presence from
  20790. // someone (regardless of whether or not the devices changed).
  20791. DEVICE_AVAILABLE: "xmpp.device_available",
  20792. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  20793. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  20794. PASSWORD_REQUIRED: "xmpp.password_required",
  20795. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  20796. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  20797. ETHERPAD: "xmpp.etherpad",
  20798. BRIDGE_DOWN: "xmpp.bridge_down",
  20799. PRESENCE_STATUS: "xmpp.presence_status",
  20800. RESERVATION_ERROR: "xmpp.room_reservation_error",
  20801. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  20802. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  20803. // TODO: only used in a hack, should probably be removed.
  20804. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  20805. // TODO: only used in a hack, should probably be removed.
  20806. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  20807. // TODO: only used in a hack, should probably be removed.
  20808. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  20809. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  20810. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  20811. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  20812. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  20813. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  20814. // xmpp is connected and obtained user media
  20815. READY_TO_JOIN: 'xmpp.ready_to_join',
  20816. FOCUS_LEFT: "xmpp.focus_left",
  20817. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received",
  20818. /**
  20819. * Indicates that recording state changed.
  20820. */
  20821. RECORDING_STATE_CHANGED: "xmpp.recordingStateChanged",
  20822. /**
  20823. * Indicates that phone number changed.
  20824. */
  20825. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged"
  20826. };
  20827. module.exports = XMPPEvents;
  20828. },{}]},{},[7])(7)
  20829. });